From 343390057da6fe47b00043cdba6326d2591fa5b1 Mon Sep 17 00:00:00 2001 From: Heatherm Huang Date: Tue, 14 Jul 2026 00:34:03 +0800 Subject: [PATCH 01/83] fix(grok): fail over OAuth credential errors safely --- .../handler/admin/grok_oauth_handler_test.go | 7 +- backend/internal/handler/admin/ops_handler.go | 8 +- backend/internal/handler/failover_loop.go | 6 + .../internal/handler/failover_loop_test.go | 49 +- .../gateway_handler_cancellation_test.go | 98 + .../gateway_handler_chat_completions.go | 11 + .../handler/gateway_handler_responses.go | 11 + backend/internal/handler/gateway_helper.go | 19 +- .../internal/handler/gateway_helper_test.go | 17 + backend/internal/handler/grok_media.go | 14 +- .../handler/openai_chat_completions.go | 14 +- ...i_gateway_credential_failover_loop_test.go | 732 ++++++++ ...openai_gateway_credential_failover_test.go | 211 +++ .../handler/openai_gateway_handler.go | 164 +- backend/internal/handler/ops_error_logger.go | 182 +- backend/internal/repository/account_repo.go | 103 ++ .../account_repo_temp_unsched_test.go | 104 ++ .../internal/repository/grok_oauth_client.go | 23 +- .../repository/grok_oauth_client_test.go | 54 +- .../repository/ops_error_where_test.go | 34 + backend/internal/repository/ops_repo.go | 42 +- .../internal/repository/ops_repo_args_test.go | 37 + ...po_get_error_log_by_id_integration_test.go | 17 + backend/internal/service/account.go | 33 +- .../internal/service/account_base_url_test.go | 34 +- .../internal/service/account_test_service.go | 4 +- .../service/account_test_service_grok_test.go | 15 +- backend/internal/service/gateway_service.go | 62 +- .../service/grok_credential_failure.go | 650 +++++++ .../service/grok_credential_failure_test.go | 1622 +++++++++++++++++ backend/internal/service/grok_media.go | 7 +- .../internal/service/grok_oauth_service.go | 10 +- .../internal/service/grok_quota_service.go | 8 +- .../service/grok_quota_service_test.go | 89 +- .../internal/service/grok_token_provider.go | 218 ++- .../service/grok_token_provider_test.go | 226 ++- .../internal/service/grok_token_refresher.go | 3 +- backend/internal/service/oauth_refresh_api.go | 132 +- .../service/oauth_refresh_api_test.go | 208 ++- .../openai_account_runtime_block_fastpath.go | 34 +- .../service/openai_gateway_cc_pipeline.go | 5 +- .../openai_gateway_chat_completions_raw.go | 5 +- .../internal/service/openai_gateway_grok.go | 8 +- .../openai_gateway_grok_chat_bridge.go | 3 +- .../openai_gateway_grok_chat_bridge_test.go | 49 +- .../service/openai_gateway_grok_test.go | 224 ++- .../service/openai_gateway_messages.go | 2 +- .../service/openai_gateway_service.go | 4 + backend/internal/service/ops_models.go | 15 +- backend/internal/service/ops_service.go | 29 +- .../service/ops_service_batch_test.go | 48 + .../internal/service/ops_upstream_context.go | 8 + backend/internal/service/ops_user_error.go | 4 +- .../internal/service/ops_user_error_test.go | 3 +- backend/internal/service/refresh_policy.go | 8 + .../service/token_refresh_service_test.go | 74 +- backend/internal/service/wire.go | 2 +- .../components/admin/usage/UsageFilters.vue | 1 + frontend/src/i18n/locales/en/admin/ops.ts | 2 + frontend/src/i18n/locales/zh/admin/ops.ts | 2 + frontend/src/utils/errorCategory.ts | 1 + .../ops/components/OpsErrorDetailsModal.vue | 1 + .../admin/ops/components/OpsErrorLogTable.vue | 3 + 63 files changed, 5291 insertions(+), 522 deletions(-) create mode 100644 backend/internal/handler/gateway_handler_cancellation_test.go create mode 100644 backend/internal/handler/openai_gateway_credential_failover_loop_test.go create mode 100644 backend/internal/handler/openai_gateway_credential_failover_test.go create mode 100644 backend/internal/repository/ops_repo_args_test.go create mode 100644 backend/internal/service/grok_credential_failure.go create mode 100644 backend/internal/service/grok_credential_failure_test.go diff --git a/backend/internal/handler/admin/grok_oauth_handler_test.go b/backend/internal/handler/admin/grok_oauth_handler_test.go index 64ea044aa3..9065e3321b 100644 --- a/backend/internal/handler/admin/grok_oauth_handler_test.go +++ b/backend/internal/handler/admin/grok_oauth_handler_test.go @@ -90,10 +90,13 @@ func TestGrokOAuthHandlerQueryQuotaProbesUpstream(t *testing.T) { ID: 42, Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, + Status: service.StatusActive, + Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "access_token": "access-token", + "refresh_token": "refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), }, }} upstream := &grokQuotaHandlerUpstream{} diff --git a/backend/internal/handler/admin/ops_handler.go b/backend/internal/handler/admin/ops_handler.go index e820aef0c6..0284dbfd0b 100644 --- a/backend/internal/handler/admin/ops_handler.go +++ b/backend/internal/handler/admin/ops_handler.go @@ -386,8 +386,8 @@ func (h *OpsHandler) ListRequestErrorUpstreamErrors(c *gin.Context) { filter.EndTime = &endTime } filter.View = "all" - filter.Phase = "upstream" - // 上游错误列表需含 status<400 的 recovered 行,显式豁免客户端可见守卫。 + filter.ErrorPhasesAny = []string{"upstream", "account_auth"} + // Provider-health list includes recovered inference and credential rows. filter.IncludeRecoveredUpstream = true filter.Owner = "provider" filter.Source = strings.TrimSpace(c.Query("error_source")) @@ -470,8 +470,8 @@ func (h *OpsHandler) ListUpstreamErrors(c *gin.Context) { } filter.View = parseOpsViewParam(c) - filter.Phase = "upstream" - // 上游错误列表需含 status<400 的 recovered 行,显式豁免客户端可见守卫。 + filter.ErrorPhasesAny = []string{"upstream", "account_auth"} + // Provider-health list includes recovered inference and credential rows. filter.IncludeRecoveredUpstream = true filter.Owner = "provider" filter.Source = strings.TrimSpace(c.Query("error_source")) diff --git a/backend/internal/handler/failover_loop.go b/backend/internal/handler/failover_loop.go index 5838e58f48..15d2966299 100644 --- a/backend/internal/handler/failover_loop.go +++ b/backend/internal/handler/failover_loop.go @@ -71,7 +71,13 @@ func (s *FailoverState) HandleFailoverError( retryLimit int, failoverErr *service.UpstreamFailoverError, ) FailoverAction { + if ctx != nil && ctx.Err() != nil { + return FailoverCanceled + } s.LastFailoverErr = failoverErr + if failoverErr == nil || !failoverErr.ShouldRetryNextAccount() { + return FailoverExhausted + } // 缓存计费判断 if needForceCacheBilling(s.hasBoundSession, failoverErr) { diff --git a/backend/internal/handler/failover_loop_test.go b/backend/internal/handler/failover_loop_test.go index 9fabe75f25..bcfc91e07a 100644 --- a/backend/internal/handler/failover_loop_test.go +++ b/backend/internal/handler/failover_loop_test.go @@ -2,6 +2,7 @@ package handler import ( "context" + "net/http" "testing" "time" @@ -128,6 +129,50 @@ func TestSleepWithContext(t *testing.T) { // --------------------------------------------------------------------------- func TestHandleFailoverError_BasicSwitch(t *testing.T) { + t.Run("显式停止不切换账号且旧错误默认仍切换", func(t *testing.T) { + mock := &mockTempUnscheduler{} + fs := NewFailoverState(3, false) + stopErr := &service.UpstreamFailoverError{ + Stage: service.GatewayFailureStageAccountAuth, + Scope: service.GatewayFailureScopeProvider, + NextAccountAction: service.NextAccountStop, + } + + action := fs.HandleFailoverError(context.Background(), mock, 100, service.PlatformGrok, maxSameAccountRetries, stopErr) + + require.Equal(t, FailoverExhausted, action) + require.Zero(t, fs.SwitchCount) + require.Empty(t, fs.FailedAccountIDs) + require.Equal(t, stopErr, fs.LastFailoverErr) + + legacyErr := newTestFailoverErr(http.StatusTooManyRequests, false, false) + action = fs.HandleFailoverError(context.Background(), mock, 100, service.PlatformGrok, maxSameAccountRetries, legacyErr) + + require.Equal(t, FailoverContinue, action) + require.Equal(t, 1, fs.SwitchCount) + require.Contains(t, fs.FailedAccountIDs, int64(100)) + }) + + t.Run("已取消的认证失败不改变切换状态", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + mock := &mockTempUnscheduler{} + fs := NewFailoverState(3, false) + err := &service.UpstreamFailoverError{ + Stage: service.GatewayFailureStageAccountAuth, + Scope: service.GatewayFailureScopeAccount, + NextAccountAction: service.NextAccountRetry, + } + + action := fs.HandleFailoverError(ctx, mock, 101, service.PlatformGrok, maxSameAccountRetries, err) + + require.Equal(t, FailoverCanceled, action) + require.Zero(t, fs.SwitchCount) + require.Empty(t, fs.FailedAccountIDs) + require.Nil(t, fs.LastFailoverErr) + require.Empty(t, mock.calls) + }) + t.Run("非重试错误_非Antigravity_直接切换", func(t *testing.T) { mock := &mockTempUnscheduler{} fs := NewFailoverState(3, false) @@ -452,8 +497,8 @@ func TestHandleFailoverError_ContextCanceled(t *testing.T) { require.Equal(t, FailoverCanceled, action) require.Less(t, elapsed, 100*time.Millisecond, "应立即返回") - // 重试计数仍应递增 - require.Equal(t, 1, fs.SameAccountRetryCount[100]) + // 入口已取消时不得改变任何重试状态。 + require.Zero(t, fs.SameAccountRetryCount[100]) }) t.Run("Antigravity延迟期间context取消", func(t *testing.T) { diff --git a/backend/internal/handler/gateway_handler_cancellation_test.go b/backend/internal/handler/gateway_handler_cancellation_test.go new file mode 100644 index 0000000000..d53961174a --- /dev/null +++ b/backend/internal/handler/gateway_handler_cancellation_test.go @@ -0,0 +1,98 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type countingGatewaySchedulerCache struct { + *fakeSchedulerCache + snapshotCalls atomic.Int64 +} + +func (c *countingGatewaySchedulerCache) GetSnapshot(ctx context.Context, bucket service.SchedulerBucket) ([]*service.Account, bool, error) { + c.snapshotCalls.Add(1) + return c.fakeSchedulerCache.GetSnapshot(ctx, bucket) +} + +func TestGatewayHandlerPreCancelledCompatibleRequestsDoNotSelectAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + groupID := int64(9100) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive} + account := &service.Account{ + ID: 9101, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, + AccountGroups: []service.AccountGroup{{AccountID: 9101, GroupID: groupID}}, + } + schedulerCache := &countingGatewaySchedulerCache{fakeSchedulerCache: &fakeSchedulerCache{accounts: []*service.Account{account}}} + schedulerSnapshot := service.NewSchedulerSnapshotService(schedulerCache, nil, nil, nil, nil) + gatewayService := service.NewGatewayService( + nil, &fakeGroupRepo{group: group}, nil, nil, nil, nil, nil, nil, nil, + schedulerSnapshot, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + cfg := &config.Config{RunMode: config.RunModeSimple} + billingCacheService := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCacheService.Stop) + h := &GatewayHandler{ + gatewayService: gatewayService, + billingCacheService: billingCacheService, + concurrencyHelper: NewConcurrencyHelper(service.NewConcurrencyService(&fakeConcurrencyCache{}), SSEPingFormatClaude, 0), + maxAccountSwitches: 1, + cfg: cfg, + } + apiKey := &service.APIKey{ + ID: 9102, UserID: 9103, GroupID: &groupID, Group: group, Status: service.StatusActive, + User: &service.User{ID: 9103, Concurrency: 10, Balance: 100}, + } + + tests := []struct { + name string + path string + body string + call func(*gin.Context) + }{ + { + name: "responses", path: "/v1/responses", body: `{"model":"claude-test","input":"hello","stream":false}`, + call: h.Responses, + }, + { + name: "chat completions", path: "/v1/chat/completions", body: `{"model":"claude-test","messages":[{"role":"user","content":"hello"}],"stream":false}`, + call: h.ChatCompletions, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + schedulerCache.snapshotCalls.Store(0) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + ctx = context.WithValue(ctx, ctxkey.Group, group) + req := httptest.NewRequest(http.MethodPost, tt.path, bytes.NewBufferString(tt.body)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + c.Request = req + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.UserID, Concurrency: 10}) + + tt.call(c) + + require.Zero(t, schedulerCache.snapshotCalls.Load(), "a cancelled request must stop before the account selector") + _, selected := c.Get(opsAccountIDKey) + require.False(t, selected) + }) + } +} diff --git a/backend/internal/handler/gateway_handler_chat_completions.go b/backend/internal/handler/gateway_handler_chat_completions.go index af9bcdb344..d7893b6cd4 100644 --- a/backend/internal/handler/gateway_handler_chat_completions.go +++ b/backend/internal/handler/gateway_handler_chat_completions.go @@ -159,6 +159,9 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) { } for { + if c.Request.Context().Err() != nil { + return + } selection, err := h.gatewayService.SelectAccountWithLoadAwareness(c.Request.Context(), apiKey.GroupID, selectionSessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) if err != nil { if len(fs.FailedAccountIDs) == 0 { @@ -328,6 +331,14 @@ func (h *GatewayHandler) handleCCFailoverExhausted(c *gin.Context, lastErr *serv if streamStarted { return } + if lastErr != nil { + copyFailoverRetryAfter(c, lastErr.ResponseHeaders) + } + if lastErr != nil && lastErr.IsCredentialFailure() { + status, message := credentialFailoverClientResponse(lastErr) + h.chatCompletionsErrorResponse(c, status, "server_error", message) + return + } statusCode := http.StatusBadGateway if lastErr != nil && lastErr.StatusCode > 0 { statusCode = lastErr.StatusCode diff --git a/backend/internal/handler/gateway_handler_responses.go b/backend/internal/handler/gateway_handler_responses.go index 8a88d5fa57..844de47669 100644 --- a/backend/internal/handler/gateway_handler_responses.go +++ b/backend/internal/handler/gateway_handler_responses.go @@ -157,6 +157,9 @@ func (h *GatewayHandler) Responses(c *gin.Context) { fs := NewFailoverState(h.maxAccountSwitches, false) for { + if requestCtx.Err() != nil { + return + } selection, err := h.gatewayService.SelectAccountWithLoadAwareness(requestCtx, apiKey.GroupID, sessionHash, reqModel, fs.FailedAccountIDs, "", int64(0)) if err != nil { if len(fs.FailedAccountIDs) == 0 { @@ -307,6 +310,14 @@ func (h *GatewayHandler) handleResponsesFailoverExhausted(c *gin.Context, lastEr if streamStarted { return // Can't write error after stream started } + if lastErr != nil { + copyFailoverRetryAfter(c, lastErr.ResponseHeaders) + } + if lastErr != nil && lastErr.IsCredentialFailure() { + status, message := credentialFailoverClientResponse(lastErr) + h.responsesErrorResponse(c, status, "server_error", message) + return + } statusCode := http.StatusBadGateway if lastErr != nil && lastErr.StatusCode > 0 { statusCode = lastErr.StatusCode diff --git a/backend/internal/handler/gateway_helper.go b/backend/internal/handler/gateway_helper.go index 8489b17f6d..1f6daf5291 100644 --- a/backend/internal/handler/gateway_helper.go +++ b/backend/internal/handler/gateway_helper.go @@ -163,20 +163,15 @@ func wrapReleaseOnDone(ctx context.Context, releaseFunc func()) func() { return nil } var once sync.Once - var stop func() bool - - release := func() { - once.Do(func() { - if stop != nil { - _ = stop() - } - releaseFunc() - }) + releaseOnce := func() { + once.Do(releaseFunc) } + stop := context.AfterFunc(ctx, releaseOnce) - stop = context.AfterFunc(ctx, release) - - return release + return func() { + _ = stop() + releaseOnce() + } } // IncrementWaitCount increments the wait count for a user diff --git a/backend/internal/handler/gateway_helper_test.go b/backend/internal/handler/gateway_helper_test.go index 664258f8c9..bc0f50f0b6 100644 --- a/backend/internal/handler/gateway_helper_test.go +++ b/backend/internal/handler/gateway_helper_test.go @@ -6,6 +6,8 @@ import ( "sync/atomic" "testing" "time" + + "github.com/stretchr/testify/require" ) // TestWrapReleaseOnDone_NoGoroutineLeak 验证 wrapReleaseOnDone 修复后不会泄露 goroutine @@ -67,6 +69,21 @@ func TestWrapReleaseOnDone_ContextCancellation(t *testing.T) { } } +func TestWrapReleaseOnDone_AlreadyCancelledReleasesExactlyOnce(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + var releaseCount int32 + release := wrapReleaseOnDone(ctx, func() { + atomic.AddInt32(&releaseCount, 1) + }) + release() + + require.Eventually(t, func() bool { + return atomic.LoadInt32(&releaseCount) == 1 + }, time.Second, time.Millisecond) +} + // TestWrapReleaseOnDone_MultipleCallsOnlyReleaseOnce 验证多次调用 release 只释放一次 func TestWrapReleaseOnDone_MultipleCallsOnlyReleaseOnce(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index b7092fcc42..408020f0a6 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -174,6 +174,9 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. routingStart := time.Now() for { + if requestCtx.Err() != nil { + return + } selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( requestCtx, apiKey.GroupID, @@ -257,11 +260,20 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. if err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { - h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + if requestCtx.Err() != nil { + return + } + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + } if c.Writer.Size() != writerSizeBeforeForward { h.handleFailoverExhausted(c, failoverErr, true) return } + if !failoverErr.ShouldRetryNextAccount() { + h.handleFailoverExhausted(c, failoverErr, false) + return + } if failoverErr.RetryableOnSameAccount { retryLimit := account.GetPoolModeRetryCount() if sameAccountRetryCount[account.ID] < retryLimit { diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index 636e143740..fc58b3a25a 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -135,6 +135,9 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { var lastFailoverErr *service.UpstreamFailoverError for { + if c.Request.Context().Err() != nil { + return + } reqLog.Debug("openai_chat_completions.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( c.Request.Context(), @@ -231,11 +234,20 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { } else { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { + if c.Request.Context().Err() != nil { + return + } if c.Writer.Size() != writerSizeBeforeForward { h.handleFailoverExhausted(c, failoverErr, true) return } - h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + } + if !failoverErr.ShouldRetryNextAccount() { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } // Pool mode: retry on the same account if failoverErr.RetryableOnSameAccount { retryLimit := account.GetPoolModeRetryCount() diff --git a/backend/internal/handler/openai_gateway_credential_failover_loop_test.go b/backend/internal/handler/openai_gateway_credential_failover_loop_test.go new file mode 100644 index 0000000000..e7030d9d2f --- /dev/null +++ b/backend/internal/handler/openai_gateway_credential_failover_loop_test.go @@ -0,0 +1,732 @@ +//go:build unit + +package handler + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type grokCredentialHandlerRepo struct { + service.AccountRepository + mu sync.Mutex + accounts []service.Account + setErrorIDs []int64 + setTempIDs []int64 + updateExtraIDs []int64 + selectionCalls int + setErrorErr error + setTempErr error + missingOnGet map[int64]bool +} + +func (r *grokCredentialHandlerRepo) ListSchedulableByPlatform(_ context.Context, platform string) ([]service.Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.selectionCalls++ + out := make([]service.Account, 0, len(r.accounts)) + for _, account := range r.accounts { + if account.Platform == platform && account.IsSchedulable() { + out = append(out, account) + } + } + return out, nil +} + +func (r *grokCredentialHandlerRepo) ListSchedulableByGroupIDAndPlatform(ctx context.Context, _ int64, platform string) ([]service.Account, error) { + return r.ListSchedulableByPlatform(ctx, platform) +} + +func (r *grokCredentialHandlerRepo) ListSchedulableUngroupedByPlatform(ctx context.Context, platform string) ([]service.Account, error) { + return r.ListSchedulableByPlatform(ctx, platform) +} + +func (r *grokCredentialHandlerRepo) GetByID(_ context.Context, id int64) (*service.Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + if r.missingOnGet[id] { + return nil, nil + } + for _, account := range r.accounts { + if account.ID == id { + copy := account + copy.Credentials = cloneCredentialMap(account.Credentials) + return ©, nil + } + } + return nil, nil +} + +func (r *grokCredentialHandlerRepo) SetError(_ context.Context, id int64, message string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.setErrorIDs = append(r.setErrorIDs, id) + if r.setErrorErr != nil { + return r.setErrorErr + } + for i := range r.accounts { + if r.accounts[i].ID == id { + r.accounts[i].Status = service.StatusError + r.accounts[i].Schedulable = false + r.accounts[i].ErrorMessage = message + } + } + return nil +} + +func (r *grokCredentialHandlerRepo) SetTempUnschedulable(_ context.Context, id int64, until time.Time, _ string) error { + r.mu.Lock() + defer r.mu.Unlock() + r.setTempIDs = append(r.setTempIDs, id) + if r.setTempErr != nil { + return r.setTempErr + } + for i := range r.accounts { + if r.accounts[i].ID == id { + value := until + r.accounts[i].TempUnschedulableUntil = &value + } + } + return nil +} + +func (r *grokCredentialHandlerRepo) SetGrokCredentialErrorIfMatch( + _ context.Context, + id int64, + snapshot service.GrokCredentialMutationSnapshot, + message string, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + account := &r.accounts[i] + if account.ID != id || !handlerGrokCredentialSnapshotMatches(account, snapshot) { + continue + } + r.setErrorIDs = append(r.setErrorIDs, id) + if r.setErrorErr != nil { + return false, r.setErrorErr + } + account.Status = service.StatusError + account.Schedulable = false + account.ErrorMessage = message + return true, nil + } + return false, nil +} + +func (r *grokCredentialHandlerRepo) SetGrokCredentialTempUnschedulableIfMatch( + _ context.Context, + id int64, + snapshot service.GrokCredentialMutationSnapshot, + until time.Time, + _ string, +) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + for i := range r.accounts { + account := &r.accounts[i] + if account.ID != id || !handlerGrokCredentialSnapshotMatches(account, snapshot) { + continue + } + r.setTempIDs = append(r.setTempIDs, id) + if r.setTempErr != nil { + return false, r.setTempErr + } + value := until + account.TempUnschedulableUntil = &value + return true, nil + } + return false, nil +} + +func handlerGrokCredentialSnapshotMatches(account *service.Account, snapshot service.GrokCredentialMutationSnapshot) bool { + if account == nil { + return false + } + credentialsJSON, err := json.Marshal(account.Credentials) + return err == nil && account.IsGrokOAuth() && account.IsSchedulable() && string(credentialsJSON) == snapshot.CredentialsJSON && + handlerGrokCredentialProxyIDsEqual(account.ProxyID, snapshot.ProxyID) +} + +func handlerGrokCredentialProxyIDsEqual(left, right *int64) bool { + if left == nil || right == nil { + return left == nil && right == nil + } + return *left == *right +} + +func (r *grokCredentialHandlerRepo) UpdateExtra(_ context.Context, id int64, updates map[string]any) error { + r.mu.Lock() + defer r.mu.Unlock() + r.updateExtraIDs = append(r.updateExtraIDs, id) + for i := range r.accounts { + if r.accounts[i].ID != id { + continue + } + if r.accounts[i].Extra == nil { + r.accounts[i].Extra = map[string]any{} + } + for key, value := range updates { + r.accounts[i].Extra[key] = value + } + } + return nil +} + +func (r *grokCredentialHandlerRepo) errorIDs() []int64 { + r.mu.Lock() + defer r.mu.Unlock() + return append([]int64(nil), r.setErrorIDs...) +} + +func (r *grokCredentialHandlerRepo) selectorCalls() int { + r.mu.Lock() + defer r.mu.Unlock() + return r.selectionCalls +} + +type grokCredentialHandlerTokenCache struct { + service.GrokTokenCache + mu sync.Mutex + deleteErr error +} + +func (c *grokCredentialHandlerTokenCache) GetAccessToken(context.Context, string) (string, error) { + return "", errors.New("not cached") +} + +func (c *grokCredentialHandlerTokenCache) SetAccessToken(context.Context, string, string, time.Duration) error { + return nil +} + +func (c *grokCredentialHandlerTokenCache) DeleteAccessToken(context.Context, string) error { + c.mu.Lock() + defer c.mu.Unlock() + return c.deleteErr +} + +func (c *grokCredentialHandlerTokenCache) AcquireRefreshLock(context.Context, string, time.Duration) (bool, error) { + return true, nil +} + +func (c *grokCredentialHandlerTokenCache) ReleaseRefreshLock(context.Context, string) error { + return nil +} + +func cloneCredentialMap(source map[string]any) map[string]any { + cloned := make(map[string]any, len(source)) + for key, value := range source { + cloned[key] = value + } + return cloned +} + +type grokCredentialHandlerRefresher struct { + mode string + started chan struct{} + once sync.Once +} + +func (r *grokCredentialHandlerRefresher) CacheKey(account *service.Account) string { + return service.GrokTokenCacheKey(account) +} + +func (r *grokCredentialHandlerRefresher) CanRefresh(account *service.Account) bool { + return account != nil && account.IsGrokOAuth() +} + +func (r *grokCredentialHandlerRefresher) NeedsRefresh(account *service.Account, _ time.Duration) bool { + return account != nil && (account.ID == 801 || r.mode == "all_revoked") +} + +func (r *grokCredentialHandlerRefresher) Refresh(ctx context.Context, _ *service.Account) (map[string]any, error) { + switch r.mode { + case "revoked", "all_revoked", "mutation_set_error", "mutation_cache": + return nil, infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant") + case "provider": + return nil, infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_client") + case "cancel": + r.once.Do(func() { close(r.started) }) + <-ctx.Done() + return nil, ctx.Err() + case "transient", "mutation_temp": + return nil, errors.New("temporary refresh transport failure") + default: + return nil, nil + } +} + +type grokCredentialHandlerUpstream struct { + service.HTTPUpstream + mu sync.Mutex + hits []int64 + requestURLs []string + authorization []string + failAccountID int64 + cancelRequest context.CancelFunc +} + +func (u *grokCredentialHandlerUpstream) Do(req *http.Request, _ string, accountID int64, _ int) (*http.Response, error) { + var requestBody []byte + if req.Body != nil { + requestBody, _ = io.ReadAll(req.Body) + } + u.mu.Lock() + u.hits = append(u.hits, accountID) + u.requestURLs = append(u.requestURLs, req.URL.String()) + u.authorization = append(u.authorization, req.Header.Get("Authorization")) + failAccountID := u.failAccountID + cancelRequest := u.cancelRequest + u.mu.Unlock() + if accountID == failAccountID { + if cancelRequest != nil { + cancelRequest() + } + return &http.Response{ + StatusCode: http.StatusPaymentRequired, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(bytes.NewBufferString(`{"error":{"message":"payment required"}}`)), + }, nil + } + if bytes.Contains(requestBody, []byte(`"stream":true`)) { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(bytes.NewBufferString( + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_healthy\",\"model\":\"grok-4.5\",\"usage\":{\"input_tokens\":1,\"output_tokens\":1}}}\n\n", + )), + }, nil + } + if strings.Contains(req.URL.Path, "/chat/completions") { + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(bytes.NewBufferString( + `{"id":"chatcmpl_healthy","object":"chat.completion","model":"grok-4.5","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}`, + )), + }, nil + } + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(bytes.NewBufferString( + `{"id":"resp_healthy","object":"response","model":"grok-4.5","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}`, + )), + }, nil +} + +func (u *grokCredentialHandlerUpstream) accountHits() []int64 { + u.mu.Lock() + defer u.mu.Unlock() + return append([]int64(nil), u.hits...) +} + +func (u *grokCredentialHandlerUpstream) requests() ([]string, []string) { + u.mu.Lock() + defer u.mu.Unlock() + return append([]string(nil), u.requestURLs...), append([]string(nil), u.authorization...) +} + +func TestResponsesCredentialFailoverLoop(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("revoked account selects healthy account", func(t *testing.T) { + h, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked") + defer cleanup() + _ = h + + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), "resp_healthy") + require.Equal(t, []int64{801}, repo.errorIDs()) + require.Equal(t, []int64{802}, upstream.accountHits()) + requestURLs, authorization := upstream.requests() + require.Equal(t, []string{xai.DefaultCLIBaseURL + "/responses"}, requestURLs) + require.Equal(t, []string{"Bearer healthy-access"}, authorization) + }) + + t.Run("provider configuration stops before healthy account", func(t *testing.T) { + h, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "provider") + defer cleanup() + + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.Empty(t, repo.errorIDs()) + require.Empty(t, upstream.accountHits()) + require.Equal(t, 1, repo.selectorCalls()) + require.Zero(t, h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics().RuntimeStatsAccountCount, + "provider-scoped auth failure must not penalize the selected account") + }) + + t.Run("parent cancellation stops before healthy account", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "cancel") + defer cleanup() + + ctx, cancel := context.WithCancel(context.Background()) + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + done := make(chan struct{}) + go func() { + defer close(done) + router.ServeHTTP(recorder, req) + }() + + select { + case <-time.After(2 * time.Second): + t.Fatal("credential refresh did not start") + case <-findHandlerRefresherStarted(router): + cancel() + } + select { + case <-time.After(2 * time.Second): + t.Fatal("handler did not stop after cancellation") + case <-done: + } + + require.Empty(t, repo.errorIDs()) + require.Empty(t, upstream.accountHits()) + }) + + t.Run("post-mapping cancellation stops before scheduler mutation or reselection", func(t *testing.T) { + h, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "postmap_cancel") + defer cleanup() + ctx, cancel := context.WithCancel(context.Background()) + upstream.mu.Lock() + upstream.failAccountID = 801 + upstream.cancelRequest = cancel + upstream.mu.Unlock() + + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, req) + + require.Equal(t, []int64{801}, upstream.accountHits()) + require.Empty(t, repo.errorIDs()) + require.Equal(t, 1, repo.selectorCalls()) + require.Zero(t, h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics().RuntimeStatsAccountCount) + }) + + t.Run("pre-cancelled request never invokes an account selector", func(t *testing.T) { + tests := []struct { + name string + method string + path string + body string + }{ + {name: "responses", method: http.MethodPost, path: "/openai/v1/responses", body: `{"model":"grok","input":"hello","stream":false}`}, + {name: "messages", method: http.MethodPost, path: "/openai/v1/messages", body: `{"model":"grok","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`}, + {name: "chat completions", method: http.MethodPost, path: "/openai/v1/chat/completions", body: `{"model":"grok","messages":[{"role":"user","content":"hello"}],"stream":false}`}, + {name: "grok media", method: http.MethodGet, path: "/openai/v1/videos/request-1"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked") + defer cleanup() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(tt.method, tt.path, bytes.NewBufferString(tt.body)).WithContext(ctx) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Zero(t, repo.selectorCalls()) + require.Empty(t, upstream.accountHits()) + }) + } + }) + + t.Run("credential state mutation failures stop before reselection", func(t *testing.T) { + for _, mode := range []string{"mutation_set_error", "mutation_temp", "mutation_cache"} { + t.Run(mode, func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, mode) + defer cleanup() + + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.Empty(t, upstream.accountHits()) + require.Equal(t, 1, repo.selectorCalls()) + }) + } + }) + + t.Run("missing credential provider stops before upstream or reselection", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "nil_provider") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.Equal(t, 1, repo.selectorCalls()) + require.Empty(t, upstream.accountHits()) + require.Empty(t, repo.errorIDs()) + }) +} + +func TestGrokOAuthCredentialFailoverAcrossHTTPHandlers(t *testing.T) { + gin.SetMode(gin.TestMode) + endpoints := []struct { + name string + method string + path string + body string + }{ + {name: "messages", method: http.MethodPost, path: "/openai/v1/messages", body: `{"model":"grok","max_tokens":16,"messages":[{"role":"user","content":"hello"}]}`}, + {name: "chat completions", method: http.MethodPost, path: "/openai/v1/chat/completions", body: `{"model":"grok","messages":[{"role":"user","content":"hello"}],"stream":false}`}, + {name: "chat completions raw fallback", method: http.MethodPost, path: "/openai/v1/chat/completions", body: `{"model":"grok","messages":[{"role":"user","content":"hello"}],"stop":["END"],"stream":false}`}, + {name: "grok media", method: http.MethodGet, path: "/openai/v1/videos/request-1"}, + } + + for _, endpoint := range endpoints { + t.Run(endpoint.name+" revoked selects healthy", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(endpoint.method, endpoint.path, bytes.NewBufferString(endpoint.body)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801}, repo.errorIDs()) + require.Equal(t, []int64{802}, upstream.accountHits()) + }) + + t.Run(endpoint.name+" all accounts exhausted safely", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "all_revoked") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(endpoint.method, endpoint.path, bytes.NewBufferString(endpoint.body)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.NotContains(t, recorder.Body.String(), "revoked-refresh") + require.NotContains(t, recorder.Body.String(), "healthy-refresh") + require.Equal(t, []int64{801, 802}, repo.errorIDs()) + require.Empty(t, upstream.accountHits()) + }) + } +} + +func TestGrokOAuthMissingSelectedRowRetriesHealthyAccountWithoutMutation(t *testing.T) { + gin.SetMode(gin.TestMode) + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "missing_row") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{802}, upstream.accountHits()) + require.Empty(t, repo.errorIDs()) + require.Empty(t, repo.setTempIDs) +} + +func TestResponsesWebSocketCredentialFailoverLoop(t *testing.T) { + gin.SetMode(gin.TestMode) + dial := func(t *testing.T, router *gin.Engine) (*coderws.Conn, func()) { + t.Helper() + server := httptest.NewServer(router) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + conn, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http")+"/openai/v1/responses", nil) + cancel() + require.NoError(t, err) + return conn, func() { + _ = conn.CloseNow() + server.Close() + } + } + writeFirst := func(t *testing.T, conn *coderws.Conn) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + require.NoError(t, conn.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"grok","input":"hello","stream":false}`))) + } + + t.Run("revoked account selects healthy account", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "revoked") + defer cleanup() + conn, closeConn := dial(t, router) + defer closeConn() + writeFirst(t, conn) + + readCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + _, payload, err := conn.Read(readCtx) + cancel() + require.NoError(t, err) + require.Contains(t, string(payload), "resp_healthy") + require.Equal(t, []int64{801}, repo.errorIDs()) + require.Equal(t, 2, repo.selectorCalls()) + require.Equal(t, []int64{802}, upstream.accountHits()) + }) + + t.Run("provider configuration stops", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "provider") + defer cleanup() + conn, closeConn := dial(t, router) + defer closeConn() + writeFirst(t, conn) + + readCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + _, _, err := conn.Read(readCtx) + cancel() + var closeErr coderws.CloseError + require.ErrorAs(t, err, &closeErr) + require.Contains(t, closeErr.Reason, service.GrokCredentialUnavailableClientMessage) + require.Equal(t, 1, repo.selectorCalls()) + require.Empty(t, upstream.accountHits()) + }) + + t.Run("parent cancellation prevents reselection", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "cancel") + defer cleanup() + conn, closeConn := dial(t, router) + writeFirst(t, conn) + select { + case <-findHandlerRefresherStarted(router): + case <-time.After(2 * time.Second): + t.Fatal("credential refresh did not start") + } + closeConn() + + require.Eventually(t, func() bool { return repo.selectorCalls() == 1 }, 2*time.Second, 20*time.Millisecond) + require.Empty(t, repo.errorIDs()) + require.Empty(t, upstream.accountHits()) + }) +} + +var handlerRefresherStarted sync.Map + +func findHandlerRefresherStarted(router *gin.Engine) <-chan struct{} { + value, _ := handlerRefresherStarted.Load(router) + return value.(chan struct{}) +} + +func newGrokCredentialFailoverHandler(t *testing.T, mode string) (*OpenAIGatewayHandler, *grokCredentialHandlerRepo, *grokCredentialHandlerUpstream, *gin.Engine, func()) { + t.Helper() + groupID := int64(901) + accounts := []service.Account{ + { + ID: 801, Name: "revoked", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: 1, + Credentials: map[string]any{ + "access_token": "expired", "refresh_token": "revoked-refresh", + "expires_at": time.Now().Add(-time.Minute).UTC().Format(time.RFC3339), + }, + }, + { + ID: 802, Name: "healthy", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: 2, + Credentials: map[string]any{ + "access_token": "healthy-access", "refresh_token": "healthy-refresh", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), + }, + }, + } + if mode == "postmap_cancel" { + accounts[0].Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + } + if mode == "all_revoked" { + accounts[1].Credentials["expires_at"] = time.Now().Add(-time.Minute).UTC().Format(time.RFC3339) + } + repo := &grokCredentialHandlerRepo{accounts: accounts, missingOnGet: map[int64]bool{}} + if mode == "missing_row" { + repo.missingOnGet[801] = true + } + if mode == "mutation_set_error" { + repo.setErrorErr = errors.New("database write failed") + } + if mode == "mutation_temp" { + repo.setTempErr = errors.New("database write failed") + } + refresher := &grokCredentialHandlerRefresher{mode: mode, started: make(chan struct{})} + tokenCache := &grokCredentialHandlerTokenCache{} + if mode == "mutation_cache" { + tokenCache.deleteErr = errors.New("cache delete failed") + } + var provider *service.GrokTokenProvider + if mode != "nil_provider" { + provider = service.NewGrokTokenProvider(repo, tokenCache) + provider.SetRefreshAPI(service.NewOAuthRefreshAPI(repo, tokenCache), refresher) + } + upstream := &grokCredentialHandlerUpstream{} + cfg := &config.Config{RunMode: config.RunModeSimple} + cfg.Gateway.MaxAccountSwitches = 3 + billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) + gateway := service.NewOpenAIGatewayService( + repo, nil, nil, nil, nil, nil, nil, cfg, nil, nil, + service.NewBillingService(cfg, nil), nil, billingCache, upstream, + &service.DeferredService{}, nil, provider, nil, nil, nil, nil, nil, + ) + cache := &concurrencyCacheMock{ + acquireUserSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil }, + acquireAccountSlotFn: func(context.Context, int64, int, string) (bool, error) { return true, nil }, + } + h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(cache), billingCache, &service.APIKeyService{}, nil, nil, nil, nil, cfg) + apiKey := &service.APIKey{ + ID: 902, GroupID: &groupID, + User: &service.User{ID: 903, Status: service.StatusActive}, + Group: &service.Group{ID: groupID, Platform: service.PlatformGrok, Status: service.StatusActive}, + } + router := gin.New() + router.Use(func(c *gin.Context) { + c.Set(string(middleware.ContextKeyAPIKey), apiKey) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: apiKey.User.ID, Concurrency: 1}) + c.Next() + }) + router.POST("/openai/v1/responses", h.Responses) + router.GET("/openai/v1/responses", h.ResponsesWebSocket) + router.POST("/openai/v1/messages", h.Messages) + router.POST("/openai/v1/chat/completions", h.ChatCompletions) + router.GET("/openai/v1/videos/:request_id", h.GrokVideoStatus) + handlerRefresherStarted.Store(router, refresher.started) + cleanup := func() { + handlerRefresherStarted.Delete(router) + billingCache.Stop() + } + return h, repo, upstream, router, cleanup +} diff --git a/backend/internal/handler/openai_gateway_credential_failover_test.go b/backend/internal/handler/openai_gateway_credential_failover_test.go new file mode 100644 index 0000000000..07a5e4999f --- /dev/null +++ b/backend/internal/handler/openai_gateway_credential_failover_test.go @@ -0,0 +1,211 @@ +//go:build unit + +package handler + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestGatewayChatCredentialStopDoesNotSelectAnotherAccountAndReturnsSafe503(t *testing.T) { + gin.SetMode(gin.TestMode) + stopErr := &service.UpstreamFailoverError{ + Stage: service.GatewayFailureStageAccountAuth, + Scope: service.GatewayFailureScopeProvider, + Reason: service.GrokCredentialReasonProviderConfig, + NextAccountAction: service.NextAccountStop, + ClientStatusCode: http.StatusTeapot, + ClientMessage: "invalid_client client_secret=must-not-leak", + } + state := NewFailoverState(3, false) + action := state.HandleFailoverError(context.Background(), &mockTempUnscheduler{}, 71, service.PlatformGrok, 0, stopErr) + + require.Equal(t, FailoverExhausted, action) + require.Zero(t, state.SwitchCount) + require.Empty(t, state.FailedAccountIDs) + + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + (&GatewayHandler{}).handleCCFailoverExhausted(c, state.LastFailoverErr, false) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.NotContains(t, recorder.Body.String(), "invalid_client") + require.NotContains(t, recorder.Body.String(), "client_secret") +} + +func TestGatewayChatInferenceExhaustionRestoresRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + + (&GatewayHandler{}).handleCCFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseHeaders: http.Header{"Retry-After": []string{"45"}}, + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Equal(t, "45", recorder.Header().Get("Retry-After")) +} + +func TestCredentialFailoverExhaustionReturnsFixedSafe503(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + Stage: service.GatewayFailureStageAccountAuth, + Scope: service.GatewayFailureScopeAccount, + Reason: service.GrokCredentialReasonRevoked, + NextAccountAction: service.NextAccountRetry, + ClientStatusCode: http.StatusTeapot, + ClientMessage: "invalid_grant refresh_token=must-not-leak", + }, false) + + require.Equal(t, http.StatusServiceUnavailable, recorder.Code) + require.Contains(t, recorder.Body.String(), service.GrokCredentialUnavailableClientMessage) + require.NotContains(t, strings.ToLower(recorder.Body.String()), "invalid_grant") + require.NotContains(t, strings.ToLower(recorder.Body.String()), "refresh_token") + require.NotContains(t, recorder.Body.String(), "must-not-leak") +} + +func TestInferenceFailoverExhaustionRestoresRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseHeaders: http.Header{"Retry-After": []string{"17"}}, + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Equal(t, "17", recorder.Header().Get("Retry-After")) +} + +func TestFailoverExhaustionRejectsSecretBearingRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseHeaders: http.Header{"Retry-After": []string{"refresh_token=must-not-leak"}}, + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Empty(t, recorder.Header().Get("Retry-After")) + require.NotContains(t, recorder.Body.String(), "must-not-leak") +} + +func TestFailoverExhaustionRejectsFarFutureRetryAfterDate(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseHeaders: http.Header{ + "Retry-After": []string{time.Now().Add(30 * 24 * time.Hour).UTC().Format(http.TimeFormat)}, + }, + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Empty(t, recorder.Header().Get("Retry-After")) +} + +func TestFailoverExhaustionAllowsBoundedRetryAfterDate(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + h := &OpenAIGatewayHandler{} + retryAfter := time.Now().Add(time.Hour).UTC().Format(http.TimeFormat) + + h.handleFailoverExhausted(c, &service.UpstreamFailoverError{ + StatusCode: http.StatusTooManyRequests, + ResponseHeaders: http.Header{"Retry-After": []string{retryAfter}}, + }, false) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code) + require.Equal(t, retryAfter, recorder.Header().Get("Retry-After")) +} + +func TestOpsClassificationTreatsCredentialFailureAsAuthNotInference(t *testing.T) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Set(service.OpsUpstreamStatusCodeKey, http.StatusForbidden) + c.Set(service.OpsUpstreamErrorMessageKey, "stale inference message") + c.Set(service.OpsUpstreamErrorDetailKey, "stale inference detail") + c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{ + {Stage: string(service.GatewayFailureStageInference), UpstreamStatusCode: http.StatusForbidden, Message: "stale inference message", Detail: "stale inference detail"}, + { + Stage: string(service.GatewayFailureStageAccountAuth), + Scope: string(service.GatewayFailureScopeAccount), + Reason: string(service.GrokCredentialReasonRevoked), + UpstreamStatusCode: 0, + Message: "Grok OAuth credentials require account action", + }, + }) + + phase, _, owner, source := classifyOpsErrorLog(c, "upstream_error", service.GrokCredentialUnavailableClientMessage, "", http.StatusServiceUnavailable) + require.Equal(t, "account_auth", phase) + require.Equal(t, "provider", owner) + require.Equal(t, "gateway", source) + + entry := &service.OpsInsertErrorLogInput{} + applyOpsUpstreamFieldsFromContext(c, entry) + require.NotNil(t, entry.UpstreamStatusCode) + require.Zero(t, *entry.UpstreamStatusCode) + require.NotNil(t, entry.UpstreamErrorMessage) + require.Equal(t, "Grok OAuth credentials require account action", *entry.UpstreamErrorMessage) + require.Nil(t, entry.UpstreamErrorDetail) + require.Len(t, entry.UpstreamErrors, 2) + require.Equal(t, http.StatusForbidden, entry.UpstreamErrors[0].UpstreamStatusCode) +} + +func TestOpsRecoveredCredentialFailoverUsesAccountAuthAttribution(t *testing.T) { + setupOpsErrorLogTestQueue(t, 2) + gin.SetMode(gin.TestMode) + ops := service.NewOpsService(nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + router := gin.New() + router.Use(OpsErrorLoggerMiddleware(ops)) + router.GET("/openai/v1/responses", func(c *gin.Context) { + c.Set(service.OpsUpstreamErrorsKey, []*service.OpsUpstreamErrorEvent{ + {Stage: string(service.GatewayFailureStageInference), UpstreamStatusCode: http.StatusForbidden, Message: "earlier inference failure"}, + { + Stage: string(service.GatewayFailureStageAccountAuth), Scope: string(service.GatewayFailureScopeAccount), + Reason: string(service.GrokCredentialReasonRevoked), Message: "Grok OAuth credentials require account action", + }, + }) + c.JSON(http.StatusOK, gin.H{"ok": true}) + }) + + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/openai/v1/responses", nil)) + + require.Equal(t, http.StatusOK, recorder.Code) + require.Equal(t, int64(1), OpsErrorLogQueueLength()) + job := <-opsErrorLogQueue + require.Equal(t, "account_auth", job.entry.ErrorPhase) + require.Equal(t, "provider", job.entry.ErrorOwner) + require.Equal(t, "gateway", job.entry.ErrorSource) + require.Contains(t, job.entry.ErrorMessage, "Recovered account authentication failure") + require.NotContains(t, job.entry.ErrorMessage, "403") + require.NotContains(t, job.entry.ErrorMessage, "earlier inference failure") + require.NotNil(t, job.entry.UpstreamStatusCode) + require.Zero(t, *job.entry.UpstreamStatusCode) + require.Len(t, job.entry.UpstreamErrors, 2) + require.Equal(t, http.StatusForbidden, job.entry.UpstreamErrors[0].UpstreamStatusCode) +} diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 231363a8a3..6db72c270b 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -334,6 +334,9 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { var lastFailoverErr *service.UpstreamFailoverError for { + if c.Request.Context().Err() != nil { + return + } // Select account supporting the requested model reqLog.Debug("openai.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( @@ -443,11 +446,20 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { } else { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { + if c.Request.Context().Err() != nil { + return + } if service.OpenAICompactKeepaliveAdjustedWrittenSize(c) != writerSizeBeforeForward { h.handleFailoverExhausted(c, failoverErr, true) return } - h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + } + if !failoverErr.ShouldRetryNextAccount() { + h.handleFailoverExhausted(c, failoverErr, streamStarted) + return + } // 池模式:同账号重试 if failoverErr.RetryableOnSameAccount { retryLimit := account.GetPoolModeRetryCount() @@ -835,6 +847,9 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { effectiveMappedModel := preferredMappedModel for { + if c.Request.Context().Err() != nil { + return + } currentRoutingModel := routingModel if effectiveMappedModel != "" { currentRoutingModel = effectiveMappedModel @@ -935,11 +950,20 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { } else { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { + if c.Request.Context().Err() != nil { + return + } if c.Writer.Size() != writerSizeBeforeForward { h.handleAnthropicFailoverExhausted(c, failoverErr, true) return } - h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + } + if !failoverErr.ShouldRetryNextAccount() { + h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted) + return + } // 池模式:同账号重试 if failoverErr.RetryableOnSameAccount { retryLimit := account.GetPoolModeRetryCount() @@ -1093,6 +1117,14 @@ func (h *OpenAIGatewayHandler) anthropicStreamingAwareError(c *gin.Context, stat // handleAnthropicFailoverExhausted maps upstream failover errors to Anthropic format. func (h *OpenAIGatewayHandler) handleAnthropicFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) { + if failoverErr != nil { + copyFailoverRetryAfter(c, failoverErr.ResponseHeaders) + } + if failoverErr != nil && failoverErr.IsCredentialFailure() { + status, message := credentialFailoverClientResponse(failoverErr) + h.anthropicStreamingAwareError(c, status, "api_error", message, streamStarted) + return + } status, errType, errMsg := h.mapUpstreamError(failoverErr.StatusCode) h.anthropicStreamingAwareError(c, status, errType, errMsg, streamStarted) } @@ -1464,8 +1496,49 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { switchCount := 0 failedAccountIDs := make(map[int64]struct{}) var lastFailoverErr *service.UpstreamFailoverError + handleWSFailover := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { + if ctx.Err() != nil { + return false + } + if failoverErr.ShouldReportAccountScheduleFailure() { + h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) + } + releaseAccountSlot() + if !failoverErr.ShouldRetryNextAccount() { + closeOpenAIWSFailoverExhausted(wsConn, failoverErr) + return false + } + if ctx.Err() != nil { + return false + } + h.gatewayService.RecordOpenAIAccountSwitch() + failedAccountIDs[account.ID] = struct{}{} + lastFailoverErr = failoverErr + if switchCount >= maxAccountSwitches { + closeOpenAIWSFailoverExhausted(wsConn, failoverErr) + return false + } + switchCount++ + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + closeOpenAIWSFailoverExhausted(wsConn, failoverErr) + return false + } + reqLog.Warn("openai.websocket_upstream_failover_switching", + zap.Int64("account_id", account.ID), + zap.Int("upstream_status", failoverErr.StatusCode), + zap.Int("switch_count", switchCount), + zap.Int("max_switches", maxAccountSwitches), + ) + if ctx.Err() != nil { + return false + } + return ensureUserSlotHeld() + } for { + if ctx.Err() != nil { + return + } reqLog.Debug("openai.websocket_account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) selection, scheduleDecision, err := h.gatewayService.SelectAccountWithSchedulerForCapability( ctx, @@ -1533,9 +1606,19 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { reqLog.Warn("openai.websocket_bind_sticky_session_failed", zap.Int64("account_id", account.ID), zap.Error(err)) } - token, _, err := h.gatewayService.GetAccessToken(ctx, account) + token, _, err := h.gatewayService.GetRequestCredential(ctx, c, account) if err != nil { reqLog.Warn("openai.websocket_get_access_token_failed", zap.Int64("account_id", account.ID), zap.Error(err)) + if ctx.Err() != nil { + return + } + var failoverErr *service.UpstreamFailoverError + if errors.As(err, &failoverErr) { + if handleWSFailover(account, failoverErr) { + continue + } + return + } closeOpenAIClientWS(wsConn, coderws.StatusInternalError, "failed to get access token") return } @@ -1692,30 +1775,10 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { if err := h.gatewayService.ProxyResponsesWebSocketFromClient(ctx, c, wsConn, account, token, wsFirstMessage, hooks); err != nil { var failoverErr *service.UpstreamFailoverError if errors.As(err, &failoverErr) { - h.gatewayService.ReportOpenAIAccountScheduleResult(account.ID, false, nil) - releaseAccountSlot() - failedAccountIDs[account.ID] = struct{}{} - lastFailoverErr = failoverErr - if switchCount >= maxAccountSwitches { - closeOpenAIWSFailoverExhausted(wsConn, failoverErr) - return + if handleWSFailover(account, failoverErr) { + continue } - switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { - closeOpenAIWSFailoverExhausted(wsConn, failoverErr) - return - } - h.gatewayService.RecordOpenAIAccountSwitch() - reqLog.Warn("openai.websocket_upstream_failover_switching", - zap.Int64("account_id", account.ID), - zap.Int("upstream_status", failoverErr.StatusCode), - zap.Int("switch_count", switchCount), - zap.Int("max_switches", maxAccountSwitches), - ) - if !ensureUserSlotHeld() { - return - } - continue + return } if errors.Is(context.Cause(ctx), service.ErrOpenAIWSIngressLeaseLost) { @@ -1946,6 +2009,16 @@ func (h *OpenAIGatewayHandler) handleConcurrencyError(c *gin.Context, err error, } func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverErr *service.UpstreamFailoverError, streamStarted bool) { + if failoverErr == nil { + h.handleFailoverExhaustedSimple(c, http.StatusBadGateway, streamStarted) + return + } + copyFailoverRetryAfter(c, failoverErr.ResponseHeaders) + if failoverErr.IsCredentialFailure() { + status, message := credentialFailoverClientResponse(failoverErr) + h.handleStreamingAwareError(c, status, "upstream_error", message, streamStarted) + return + } statusCode := failoverErr.StatusCode responseBody := failoverErr.ResponseBody if service.IsOpenAISilentRefusalErrorBody(responseBody) { @@ -1987,6 +2060,41 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE h.handleStreamingAwareError(c, status, errType, errMsg, streamStarted) } +func credentialFailoverClientResponse(failoverErr *service.UpstreamFailoverError) (int, string) { + _ = failoverErr + return http.StatusServiceUnavailable, service.GrokCredentialUnavailableClientMessage +} + +func copyFailoverRetryAfter(c *gin.Context, headers http.Header) { + if c == nil || headers == nil { + return + } + retryAfter := strings.TrimSpace(headers.Get("Retry-After")) + if retryAfter == "" || len(retryAfter) > 128 || strings.ContainsAny(retryAfter, "\r\n") || !isSafeRetryAfter(retryAfter) { + return + } + c.Header("Retry-After", retryAfter) +} + +func isSafeRetryAfter(value string) bool { + digitsOnly := true + for _, char := range value { + if char < '0' || char > '9' { + digitsOnly = false + break + } + } + if digitsOnly { + seconds, err := strconv.ParseUint(value, 10, 32) + return err == nil && seconds <= uint64((7*24*time.Hour)/time.Second) + } + retryAt, err := http.ParseTime(value) + if err != nil { + return false + } + return !retryAt.After(time.Now().Add(7 * 24 * time.Hour)) +} + // handleFailoverExhaustedSimple 简化版本,用于没有响应体的情况 func (h *OpenAIGatewayHandler) handleFailoverExhaustedSimple(c *gin.Context, statusCode int, streamStarted bool) { status, errType, errMsg := h.mapUpstreamError(statusCode) @@ -2194,6 +2302,10 @@ func closeOpenAIWSFailoverExhausted(conn *coderws.Conn, failoverErr *service.Ups closeOpenAIClientWS(conn, coderws.StatusInternalError, "upstream websocket proxy failed") return } + if failoverErr.Stage == service.GatewayFailureStageAccountAuth { + closeOpenAIClientWS(conn, coderws.StatusTryAgainLater, service.GrokCredentialUnavailableClientMessage) + return + } switch failoverErr.StatusCode { case http.StatusTooManyRequests: closeOpenAIClientWS(conn, coderws.StatusTryAgainLater, "upstream rate limit exceeded, please retry later") diff --git a/backend/internal/handler/ops_error_logger.go b/backend/internal/handler/ops_error_logger.go index 64aa3ba495..f32ca9c054 100644 --- a/backend/internal/handler/ops_error_logger.go +++ b/backend/internal/handler/ops_error_logger.go @@ -721,10 +721,15 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { var upstreamStatusCode *int var upstreamErrorMessage *string var upstreamErrorDetail *string + finalAccountAuth := false if len(events) > 0 { last := events[len(events)-1] if last != nil { - if last.UpstreamStatusCode > 0 { + finalAccountAuth = last.Stage == string(service.GatewayFailureStageAccountAuth) + if finalAccountAuth { + code := 0 + upstreamStatusCode = &code + } else if last.UpstreamStatusCode > 0 { code := last.UpstreamStatusCode upstreamStatusCode = &code } @@ -737,7 +742,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { } } - if upstreamStatusCode == nil { + if !finalAccountAuth && upstreamStatusCode == nil { if v, ok := c.Get(service.OpsUpstreamStatusCodeKey); ok { switch t := v.(type) { case int: @@ -753,7 +758,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { } } } - if upstreamErrorMessage == nil { + if !finalAccountAuth && upstreamErrorMessage == nil { if v, ok := c.Get(service.OpsUpstreamErrorMessageKey); ok { if s, ok := v.(string); ok && strings.TrimSpace(s) != "" { msg := strings.TrimSpace(s) @@ -761,7 +766,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { } } } - if upstreamErrorDetail == nil { + if !finalAccountAuth && upstreamErrorDetail == nil { if v, ok := c.Get(service.OpsUpstreamErrorDetailKey); ok { if s, ok := v.(string); ok && strings.TrimSpace(s) != "" { detail := strings.TrimSpace(s) @@ -781,13 +786,18 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { } recoveredMsg := "Recovered upstream error" - if effectiveUpstreamStatus > 0 { + if finalAccountAuth { + recoveredMsg = "Recovered account authentication failure" + } else if effectiveUpstreamStatus > 0 { recoveredMsg += " " + strconvItoa(effectiveUpstreamStatus) } if upstreamErrorMessage != nil && strings.TrimSpace(*upstreamErrorMessage) != "" { recoveredMsg += ": " + strings.TrimSpace(*upstreamErrorMessage) } recoveredMsg = truncateString(recoveredMsg, 2048) + recoveredPhase, recoveredBusinessLimited, recoveredOwner, recoveredSource := classifyOpsErrorLog( + c, "upstream_error", recoveredMsg, "", effectiveUpstreamStatus, + ) entry := &service.OpsInsertErrorLogInput{ RequestID: requestID, @@ -828,19 +838,19 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { }(), UserAgent: c.GetHeader("User-Agent"), - ErrorPhase: "upstream", + ErrorPhase: recoveredPhase, ErrorType: "upstream_error", // Severity should reflect the upstream failure, not the final client status (200). Severity: classifyOpsSeverity("upstream_error", effectiveUpstreamStatus), StatusCode: status, - IsBusinessLimited: false, + IsBusinessLimited: recoveredBusinessLimited, IsCountTokens: isCountTokensRequest(c), ErrorMessage: recoveredMsg, ErrorBody: "", - ErrorSource: "upstream_http", - ErrorOwner: "provider", + ErrorSource: recoveredSource, + ErrorOwner: recoveredOwner, UpstreamStatusCode: upstreamStatusCode, UpstreamErrorMessage: upstreamErrorMessage, @@ -850,6 +860,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { CreatedAt: time.Now(), } applyOpsLatencyFieldsFromContext(c, entry) + applyOpsUpstreamFieldsFromContext(c, entry) if apiKey != nil { entry.APIKeyID = &apiKey.ID @@ -987,60 +998,7 @@ func OpsErrorLoggerMiddleware(ops *service.OpsService) gin.HandlerFunc { CreatedAt: time.Now(), } applyOpsLatencyFieldsFromContext(c, entry) - - // Capture upstream error context set by gateway services (if present). - // This does NOT affect the client response; it enriches Ops troubleshooting data. - { - if v, ok := c.Get(service.OpsUpstreamStatusCodeKey); ok { - switch t := v.(type) { - case int: - if t > 0 { - code := t - entry.UpstreamStatusCode = &code - } - case int64: - if t > 0 { - code := int(t) - entry.UpstreamStatusCode = &code - } - } - } - if v, ok := c.Get(service.OpsUpstreamErrorMessageKey); ok { - if s, ok := v.(string); ok { - if msg := strings.TrimSpace(s); msg != "" { - entry.UpstreamErrorMessage = &msg - } - } - } - if v, ok := c.Get(service.OpsUpstreamErrorDetailKey); ok { - if s, ok := v.(string); ok { - if detail := strings.TrimSpace(s); detail != "" { - entry.UpstreamErrorDetail = &detail - } - } - } - if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok { - if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok && len(events) > 0 { - entry.UpstreamErrors = events - // Best-effort backfill the single upstream fields from the last event when missing. - last := events[len(events)-1] - if last != nil { - if entry.UpstreamStatusCode == nil && last.UpstreamStatusCode > 0 { - code := last.UpstreamStatusCode - entry.UpstreamStatusCode = &code - } - if entry.UpstreamErrorMessage == nil && strings.TrimSpace(last.Message) != "" { - msg := strings.TrimSpace(last.Message) - entry.UpstreamErrorMessage = &msg - } - if entry.UpstreamErrorDetail == nil && strings.TrimSpace(last.Detail) != "" { - detail := strings.TrimSpace(last.Detail) - entry.UpstreamErrorDetail = &detail - } - } - } - } - } + applyOpsUpstreamFieldsFromContext(c, entry) if apiKey != nil { entry.APIKeyID = &apiKey.ID @@ -1235,6 +1193,77 @@ func applyOpsLatencyFieldsFromContext(c *gin.Context, entry *service.OpsInsertEr entry.TimeToFirstTokenMs = getContextLatencyMs(c, service.OpsTimeToFirstTokenMsKey) } +// applyOpsUpstreamFieldsFromContext captures attempt-level upstream context. +// A final account_auth event owns the top-level status and forces it to zero; +// prior inference statuses remain available in UpstreamErrors. +func applyOpsUpstreamFieldsFromContext(c *gin.Context, entry *service.OpsInsertErrorLogInput) { + if c == nil || entry == nil { + return + } + if v, ok := c.Get(service.OpsUpstreamStatusCodeKey); ok { + switch t := v.(type) { + case int: + if t > 0 { + code := t + entry.UpstreamStatusCode = &code + } + case int64: + if t > 0 { + code := int(t) + entry.UpstreamStatusCode = &code + } + } + } + if v, ok := c.Get(service.OpsUpstreamErrorMessageKey); ok { + if value, ok := v.(string); ok { + if message := strings.TrimSpace(value); message != "" { + entry.UpstreamErrorMessage = &message + } + } + } + if v, ok := c.Get(service.OpsUpstreamErrorDetailKey); ok { + if value, ok := v.(string); ok { + if detail := strings.TrimSpace(value); detail != "" { + entry.UpstreamErrorDetail = &detail + } + } + } + if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok { + if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok && len(events) > 0 { + entry.UpstreamErrors = events + last := events[len(events)-1] + if last == nil { + return + } + if last.Stage == string(service.GatewayFailureStageAccountAuth) { + code := 0 + entry.UpstreamStatusCode = &code + entry.UpstreamErrorMessage = nil + if message := strings.TrimSpace(last.Message); message != "" { + entry.UpstreamErrorMessage = &message + } + entry.UpstreamErrorDetail = nil + if detail := strings.TrimSpace(last.Detail); detail != "" { + entry.UpstreamErrorDetail = &detail + } + } else { + if entry.UpstreamStatusCode == nil && last.UpstreamStatusCode > 0 { + code := last.UpstreamStatusCode + entry.UpstreamStatusCode = &code + } + if entry.UpstreamErrorMessage == nil && strings.TrimSpace(last.Message) != "" { + message := strings.TrimSpace(last.Message) + entry.UpstreamErrorMessage = &message + } + if entry.UpstreamErrorDetail == nil && strings.TrimSpace(last.Detail) != "" { + detail := strings.TrimSpace(last.Detail) + entry.UpstreamErrorDetail = &detail + } + } + } + } +} + func getContextLatencyMs(c *gin.Context, key string) *int64 { if c == nil || strings.TrimSpace(key) == "" { return nil @@ -1390,7 +1419,7 @@ func normalizeOpsErrorType(errType string, code string) string { func classifyOpsPhase(errType, message, code string) string { msg := strings.ToLower(message) - // Standardized phases: request|auth|routing|upstream|network|internal + // Standardized phases: request|auth|account_auth|routing|upstream|network|internal // Map billing/concurrency/response => request; scheduling => routing. if isOpsClientAuthError(code, msg) { return "auth" @@ -1445,7 +1474,10 @@ func classifyOpsErrorLog(c *gin.Context, errType, message, code string, status i routingCapacityLimited := isOpsRoutingCapacityLimited(c) clientBusinessLimited := service.HasOpsClientBusinessLimited(c) upstreamError := hasOpsUpstreamErrorContext(c) - if upstreamError && !routingCapacityLimited { + accountAuthFailure := hasOpsAccountAuthFailure(c) + if accountAuthFailure && !routingCapacityLimited { + phase = "account_auth" + } else if upstreamError && !routingCapacityLimited { phase = "upstream" } if clientBusinessLimited && !upstreamError && !routingCapacityLimited { @@ -1570,6 +1602,22 @@ func hasOpsUpstreamErrorContext(c *gin.Context) bool { return false } +func hasOpsAccountAuthFailure(c *gin.Context) bool { + if c == nil { + return false + } + if v, ok := c.Get(service.OpsUpstreamErrorsKey); ok { + if events, ok := v.([]*service.OpsUpstreamErrorEvent); ok { + for i := len(events) - 1; i >= 0; i-- { + if events[i] != nil { + return events[i].Stage == string(service.GatewayFailureStageAccountAuth) + } + } + } + } + return false +} + func isOpsNoAvailableAccountMessage(message string) bool { msg := strings.ToLower(message) return strings.Contains(msg, opsErrNoAvailableAccounts) || @@ -1584,6 +1632,8 @@ func classifyOpsErrorOwner(phase string, message string) string { switch phase { case "upstream", "network": return "provider" + case "account_auth": + return "provider" case "request", "auth": return "client" case "routing", "internal": @@ -1601,6 +1651,8 @@ func classifyOpsErrorSource(phase string, message string) string { switch phase { case "upstream": return "upstream_http" + case "account_auth": + return "gateway" case "network": return "gateway" case "request", "auth": diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 8eb819aeab..a3eba2eaa9 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -859,6 +859,54 @@ func (r *accountRepository) SetError(ctx context.Context, id int64, errorMsg str return nil } +func (r *accountRepository) SetGrokCredentialErrorIfMatch( + ctx context.Context, + id int64, + snapshot service.GrokCredentialMutationSnapshot, + errorMsg string, +) (bool, error) { + result, err := r.sql.ExecContext(ctx, ` + WITH updated AS ( + UPDATE accounts AS a + SET status = $1, + error_message = $2, + schedulable = false, + updated_at = NOW() + WHERE a.id = $3 + AND a.deleted_at IS NULL + AND a.status = $4 + AND a.platform = $5 + AND a.type = $6 + AND a.schedulable IS TRUE + AND (a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW()) + AND (a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW()) + AND (a.overload_until IS NULL OR a.overload_until <= NOW()) + AND (a.auto_pause_on_expired IS NOT TRUE OR a.expires_at IS NULL OR a.expires_at > NOW()) + AND a.credentials = $7::jsonb + AND a.proxy_id IS NOT DISTINCT FROM $8 + AND ($2 <> $9 OR ( + a.proxy_id IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM proxies p WHERE p.id = a.proxy_id AND p.deleted_at IS NULL + ) + )) + RETURNING a.id + ) + INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload) + SELECT $10, updated.id, NULL, NULL FROM updated + `, service.StatusError, errorMsg, id, service.StatusActive, service.PlatformGrok, service.AccountTypeOAuth, + snapshot.CredentialsJSON, snapshot.ProxyID, string(service.GrokCredentialReasonProxyInvalid), + service.SchedulerOutboxEventAccountChanged) + if err != nil { + return false, err + } + affected, err := result.RowsAffected() + if err != nil || affected == 0 { + return false, err + } + r.syncSchedulerAccountSnapshotDetached(ctx, id) + return true, nil +} + // syncSchedulerAccountSnapshot 在账号状态变更时主动同步快照到调度器缓存。 // 当账号被设置为错误、禁用、不可调度或临时不可调度时调用, // 确保调度器和粘性会话逻辑能及时感知账号的最新状态,避免继续使用不可用账号。 @@ -881,6 +929,16 @@ func (r *accountRepository) syncSchedulerAccountSnapshot(ctx context.Context, ac } } +func (r *accountRepository) syncSchedulerAccountSnapshotDetached(ctx context.Context, accountID int64) { + base := context.Background() + if ctx != nil { + base = context.WithoutCancel(ctx) + } + propagationCtx, cancel := context.WithTimeout(base, 2*time.Second) + defer cancel() + r.syncSchedulerAccountSnapshot(propagationCtx, accountID) +} + func (r *accountRepository) deleteSchedulerAccountSnapshot(ctx context.Context, accountID int64) { if r == nil || r.schedulerCache == nil || accountID <= 0 { return @@ -1414,6 +1472,51 @@ func (r *accountRepository) SetTempUnschedulable(ctx context.Context, id int64, return nil } +func (r *accountRepository) SetGrokCredentialTempUnschedulableIfMatch( + ctx context.Context, + id int64, + snapshot service.GrokCredentialMutationSnapshot, + until time.Time, + reason string, +) (bool, error) { + result, err := r.sql.ExecContext(ctx, ` + WITH updated AS ( + UPDATE accounts AS a + SET temp_unschedulable_until = CASE + WHEN a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until < $1 THEN $1 + ELSE a.temp_unschedulable_until + END, + temp_unschedulable_reason = $2, + updated_at = NOW() + WHERE a.id = $3 + AND a.deleted_at IS NULL + AND a.status = $4 + AND a.platform = $5 + AND a.type = $6 + AND a.schedulable IS TRUE + AND (a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW()) + AND (a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW()) + AND (a.overload_until IS NULL OR a.overload_until <= NOW()) + AND (a.auto_pause_on_expired IS NOT TRUE OR a.expires_at IS NULL OR a.expires_at > NOW()) + AND a.credentials = $7::jsonb + AND a.proxy_id IS NOT DISTINCT FROM $8 + RETURNING a.id + ) + INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload) + SELECT $9, updated.id, NULL, NULL FROM updated + `, until, reason, id, service.StatusActive, service.PlatformGrok, service.AccountTypeOAuth, + snapshot.CredentialsJSON, snapshot.ProxyID, service.SchedulerOutboxEventAccountChanged) + if err != nil { + return false, err + } + affected, err := result.RowsAffected() + if err != nil || affected == 0 { + return false, err + } + r.syncSchedulerAccountSnapshotDetached(ctx, id) + return true, nil +} + func (r *accountRepository) ClearTempUnschedulable(ctx context.Context, id int64) error { _, err := r.sql.ExecContext(ctx, ` UPDATE accounts diff --git a/backend/internal/repository/account_repo_temp_unsched_test.go b/backend/internal/repository/account_repo_temp_unsched_test.go index 9c3e4cbdf5..2ea18bd214 100644 --- a/backend/internal/repository/account_repo_temp_unsched_test.go +++ b/backend/internal/repository/account_repo_temp_unsched_test.go @@ -9,6 +9,7 @@ import ( "time" sqlmock "github.com/DATA-DOG/go-sqlmock" + "github.com/Wei-Shaw/sub2api/internal/service" "github.com/stretchr/testify/require" ) @@ -24,6 +25,103 @@ func TestAccountRepository_SetTempUnschedulable_NoRowsAffectedDoesNotWriteOutbox require.NotContains(t, strings.Join(exec.execQueries, "\n"), "scheduler_outbox") } +func TestAccountRepository_GrokCredentialConditionalMutationsAreEligibleAndAtomicallyPropagated(t *testing.T) { + proxyID := int64(77) + snapshot := service.GrokCredentialMutationSnapshot{ + CredentialsJSON: `{"access_token":"access","refresh_token":"refresh","_token_version":123}`, + ProxyID: &proxyID, + } + + t.Run("permanent", func(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(0)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + updated, err := repo.SetGrokCredentialErrorIfMatch(context.Background(), 42, snapshot, "revoked") + + require.NoError(t, err) + require.False(t, updated) + require.Len(t, exec.execQueries, 1) + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "WITH updated AS ( UPDATE accounts AS a") + require.Contains(t, normalized, "a.schedulable IS TRUE") + require.Contains(t, normalized, "a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW()") + require.Contains(t, normalized, "a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW()") + require.Contains(t, normalized, "a.overload_until IS NULL OR a.overload_until <= NOW()") + require.Contains(t, normalized, "a.credentials = $7::jsonb") + require.Contains(t, normalized, "a.proxy_id IS NOT DISTINCT FROM $8") + require.Contains(t, normalized, "NOT EXISTS ( SELECT 1 FROM proxies p") + require.Contains(t, normalized, "INSERT INTO scheduler_outbox") + require.Len(t, exec.execArgs[0], 10) + require.Equal(t, snapshot.CredentialsJSON, exec.execArgs[0][6]) + require.Equal(t, &proxyID, exec.execArgs[0][7]) + require.Equal(t, string(service.GrokCredentialReasonProxyInvalid), exec.execArgs[0][8]) + require.Equal(t, service.SchedulerOutboxEventAccountChanged, exec.execArgs[0][9]) + }) + + t.Run("transient", func(t *testing.T) { + exec := &recordingSQLExecutor{result: rowsAffectedResult(0)} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + updated, err := repo.SetGrokCredentialTempUnschedulableIfMatch( + context.Background(), 42, snapshot, time.Now().Add(time.Minute), "temporary", + ) + + require.NoError(t, err) + require.False(t, updated) + require.Len(t, exec.execQueries, 1) + normalized := normalizeSQLWhitespace(exec.execQueries[0]) + require.Contains(t, normalized, "WITH updated AS ( UPDATE accounts AS a") + require.Contains(t, normalized, "a.schedulable IS TRUE") + require.Contains(t, normalized, "a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= NOW()") + require.Contains(t, normalized, "a.rate_limit_reset_at IS NULL OR a.rate_limit_reset_at <= NOW()") + require.Contains(t, normalized, "a.overload_until IS NULL OR a.overload_until <= NOW()") + require.Contains(t, normalized, "a.credentials = $7::jsonb") + require.Contains(t, normalized, "a.proxy_id IS NOT DISTINCT FROM $8") + require.Contains(t, normalized, "INSERT INTO scheduler_outbox") + require.Len(t, exec.execArgs[0], 9) + require.Equal(t, snapshot.CredentialsJSON, exec.execArgs[0][6]) + require.Equal(t, &proxyID, exec.execArgs[0][7]) + require.Equal(t, service.SchedulerOutboxEventAccountChanged, exec.execArgs[0][8]) + }) +} + +func TestAccountRepository_GrokCredentialCommitCarriesOutboxAcrossCallerCancellation(t *testing.T) { + snapshot := service.GrokCredentialMutationSnapshot{CredentialsJSON: `{"access_token":"access","refresh_token":"refresh"}`} + tests := []struct { + name string + mutate func(context.Context, *accountRepository) (bool, error) + }{ + { + name: "permanent", + mutate: func(ctx context.Context, repo *accountRepository) (bool, error) { + return repo.SetGrokCredentialErrorIfMatch(ctx, 42, snapshot, string(service.GrokCredentialReasonRevoked)) + }, + }, + { + name: "transient", + mutate: func(ctx context.Context, repo *accountRepository) (bool, error) { + return repo.SetGrokCredentialTempUnschedulableIfMatch(ctx, 42, snapshot, time.Now().Add(time.Minute), string(service.GrokCredentialReasonRefreshTransient)) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + exec := &recordingSQLExecutor{result: rowsAffectedResult(1), afterExec: cancel} + repo := newAccountRepositoryWithSQL(nil, exec, nil) + + updated, err := tt.mutate(ctx, repo) + + require.NoError(t, err) + require.True(t, updated) + require.ErrorIs(t, ctx.Err(), context.Canceled) + require.Len(t, exec.execQueries, 1, "state update and scheduler outbox must share one atomic SQL statement") + require.Contains(t, normalizeSQLWhitespace(exec.execQueries[0]), "INSERT INTO scheduler_outbox") + }) + } +} + func TestAccountRepository_ListOAuthRefreshCandidates_SQLFilter(t *testing.T) { db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp)) require.NoError(t, err) @@ -87,14 +185,20 @@ func (r rowsAffectedResult) RowsAffected() (int64, error) { return int64(r), nil type recordingSQLExecutor struct { result sql.Result err error + afterExec func() execQueries []string + execArgs [][]any } func (e *recordingSQLExecutor) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { e.execQueries = append(e.execQueries, query) + e.execArgs = append(e.execArgs, append([]any(nil), args...)) if e.err != nil { return nil, e.err } + if e.afterExec != nil { + e.afterExec() + } return e.result, nil } diff --git a/backend/internal/repository/grok_oauth_client.go b/backend/internal/repository/grok_oauth_client.go index 6c9c2c407f..38f6cfb96e 100644 --- a/backend/internal/repository/grok_oauth_client.go +++ b/backend/internal/repository/grok_oauth_client.go @@ -153,14 +153,29 @@ func grokOAuthStatusError(code, message string, resp *req.Response) error { statusCode := http.StatusBadGateway errorCode := code upstreamStatus := 0 - if resp != nil && resp.StatusCode == http.StatusForbidden { - statusCode = http.StatusForbidden - errorCode = "GROK_OAUTH_ENTITLEMENT_DENIED" - } body := "" if resp != nil { upstreamStatus = resp.StatusCode body = logredact.RedactText(resp.String()) + if resp.StatusCode == http.StatusForbidden && grokOAuthHasExplicitEntitlementDenial(body) { + statusCode = http.StatusForbidden + errorCode = "GROK_OAUTH_ENTITLEMENT_DENIED" + } } return infraerrors.Newf(statusCode, errorCode, "%s: status %d, body: %s", message, upstreamStatus, body) } + +func grokOAuthHasExplicitEntitlementDenial(body string) bool { + lower := strings.ToLower(body) + compact := strings.NewReplacer(" ", "", "\n", "", "\r", "", "\t", "").Replace(lower) + for _, field := range []string{"error", "code", "reason"} { + for _, value := range []string{"access_denied", "entitlement_denied", "subscription_required", "no_active_subscription"} { + if strings.Contains(compact, `"`+field+`":"`+value+`"`) { + return true + } + } + } + return strings.Contains(lower, "entitlement denied") || + strings.Contains(lower, "subscription required") || + strings.Contains(lower, "no active grok subscription") +} diff --git a/backend/internal/repository/grok_oauth_client_test.go b/backend/internal/repository/grok_oauth_client_test.go index eabeb641c7..690a8e2139 100644 --- a/backend/internal/repository/grok_oauth_client_test.go +++ b/backend/internal/repository/grok_oauth_client_test.go @@ -50,15 +50,7 @@ func TestGrokOAuthClientExchangeAndRefreshUseFormFields(t *testing.T) { t.Setenv(xai.EnvTokenURL, server.URL) client := NewGrokOAuthClient() - - exchanged, err := client.ExchangeCode( - context.Background(), - "auth-code", - "verifier", - "http://127.0.0.1:56121/callback", - "", - "client-id", - ) + exchanged, err := client.ExchangeCode(context.Background(), "auth-code", "verifier", "http://127.0.0.1:56121/callback", "", "client-id") require.NoError(t, err) require.Equal(t, "exchange-access", exchanged.AccessToken) require.Equal(t, "exchange-refresh", exchanged.RefreshToken) @@ -72,18 +64,30 @@ func TestGrokOAuthClientExchangeAndRefreshUseFormFields(t *testing.T) { require.Equal(t, int64(7200), refreshed.ExpiresIn) } -func TestGrokOAuthClientRefreshForbiddenClassifiesEntitlement(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusForbidden) - _, _ = w.Write([]byte(`{"error":"subscription required"}`)) - })) - defer server.Close() - t.Setenv(xai.EnvTokenURL, server.URL) +func TestGrokOAuthClientRefreshForbiddenClassifiesOnlyExplicitEntitlement(t *testing.T) { + tests := []struct { + name string + body string + wantReason string + }{ + {name: "explicit entitlement", body: `{"error":"access_denied"}`, wantReason: "GROK_OAUTH_ENTITLEMENT_DENIED"}, + {name: "generic forbidden", body: `{"error":"forbidden"}`, wantReason: "GROK_OAUTH_TOKEN_REFRESH_FAILED"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(tt.body)) + })) + defer server.Close() + t.Setenv(xai.EnvTokenURL, server.URL) - client := NewGrokOAuthClient() - _, err := client.RefreshToken(context.Background(), "refresh-token", "", "client-id") - require.Error(t, err) - require.Contains(t, strings.ToUpper(err.Error()), "GROK_OAUTH_ENTITLEMENT_DENIED") + client := NewGrokOAuthClient() + _, err := client.RefreshToken(context.Background(), "refresh-token", "", "client-id") + require.Error(t, err) + require.Contains(t, strings.ToUpper(err.Error()), tt.wantReason) + }) + } } func TestGrokOAuthClientStatusErrorRedactsSensitiveResponseBody(t *testing.T) { @@ -105,3 +109,13 @@ func TestGrokOAuthClientStatusErrorRedactsSensitiveResponseBody(t *testing.T) { require.NotContains(t, errText, "refresh-secret") require.NotContains(t, errText, "verifier-secret") } + +func TestGrokOAuthEntitlementDenialRequiresExplicitEvidence(t *testing.T) { + t.Parallel() + + require.True(t, grokOAuthHasExplicitEntitlementDenial(`{"error":"access_denied"}`)) + require.True(t, grokOAuthHasExplicitEntitlementDenial(`{"code":"entitlement_denied"}`)) + require.True(t, grokOAuthHasExplicitEntitlementDenial(`{"message":"no active Grok subscription"}`)) + require.False(t, grokOAuthHasExplicitEntitlementDenial(`{"error":"forbidden","message":"request forbidden"}`)) + require.False(t, grokOAuthHasExplicitEntitlementDenial(`403 Forbidden`)) +} diff --git a/backend/internal/repository/ops_error_where_test.go b/backend/internal/repository/ops_error_where_test.go index c997865ba4..c52461e8ff 100644 --- a/backend/internal/repository/ops_error_where_test.go +++ b/backend/internal/repository/ops_error_where_test.go @@ -101,6 +101,40 @@ func TestBuildOpsErrorLogsWhere_CyberPolicyStatusExemption(t *testing.T) { if strings.Contains(whereRecovered, "status_code") { t.Fatalf("upstream phase with IncludeRecoveredUpstream must not add any status_code clause\nfull: %s", whereRecovered) } + + // account_auth uses the same explicit provider-health opt-in but remains a + // distinct phase from inference upstream errors. + whereAccountAuth, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{Phase: "account_auth", IncludeRecoveredUpstream: true}) + if strings.Contains(whereAccountAuth, "status_code") { + t.Fatalf("account_auth phase with IncludeRecoveredUpstream must expose recovered rows\nfull: %s", whereAccountAuth) + } + if !strings.Contains(whereAccountAuth, "e.error_phase = $") { + t.Fatalf("account_auth recovered filter must retain its explicit phase\nfull: %s", whereAccountAuth) + } + + whereProviderHealth, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{ + ErrorPhasesAny: []string{"upstream", "account_auth"}, + IncludeRecoveredUpstream: true, + }) + if strings.Contains(whereProviderHealth, "status_code") { + t.Fatalf("provider-health ANY filter must expose recovered inference and credential rows\nfull: %s", whereProviderHealth) + } + if !strings.Contains(whereProviderHealth, "e.error_phase = ANY($") { + t.Fatalf("provider-health filter must preserve distinct phase values\nfull: %s", whereProviderHealth) + } + + whereUserAccountAuth, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{ErrorPhasesAny: []string{"account_auth"}}) + if !strings.Contains(whereUserAccountAuth, "COALESCE(e.status_code, 0) >= 400") { + t.Fatalf("request-error account_auth filters must exclude recovered successes\nfull: %s", whereUserAccountAuth) + } + + whereMixed, _ := buildOpsErrorLogsWhere(&service.OpsErrorLogFilter{ + ErrorPhasesAny: []string{"account_auth", "request"}, + IncludeRecoveredUpstream: true, + }) + if !strings.Contains(whereMixed, "COALESCE(e.status_code, 0) >= 400") { + t.Fatalf("recovered opt-in must not bypass the guard for non-provider phases\nfull: %s", whereMixed) + } } func TestBuildOpsErrorLogsWhere_MatchDeletedKeyOwner(t *testing.T) { diff --git a/backend/internal/repository/ops_repo.go b/backend/internal/repository/ops_repo.go index 900abcf212..635bcd1a1f 100644 --- a/backend/internal/repository/ops_repo.go +++ b/backend/internal/repository/ops_repo.go @@ -160,7 +160,7 @@ func opsInsertErrorLogArgs(input *service.OpsInsertErrorLogInput) []any { opsNullString(input.ErrorBody), opsNullString(input.ErrorSource), opsNullString(input.ErrorOwner), - opsNullInt(input.UpstreamStatusCode), + opsNullableIntPointer(input.UpstreamStatusCode), opsNullString(input.UpstreamErrorMessage), opsNullString(input.UpstreamErrorDetail), opsNullString(input.UpstreamErrorsJSON), @@ -582,7 +582,7 @@ LIMIT 1` s := clientIP.String out.ClientIP = &s } - if upstreamStatusCode.Valid && upstreamStatusCode.Int64 > 0 { + if upstreamStatusCode.Valid { v := int(upstreamStatusCode.Int64) out.UpstreamStatusCode = &v } @@ -978,13 +978,13 @@ func buildOpsErrorLogsWhere(filter *service.OpsErrorLogFilter) (string, []any) { resolvedFilter = filter.Resolved } // Keep list endpoints scoped to client errors unless the caller explicitly opts - // into recovered upstream rows (Phase=="upstream" + IncludeRecoveredUpstream, - // ops 专用上游列表)。请求错误语义的端点即便过滤 phase=upstream 也保留该守卫。 + // into recovered provider-health rows (upstream/account_auth). Request-error + // endpoints never set the opt-in and retain this guard. // cyber_policy is exempt from the status >= 400 guard: streaming cyber hits arrive with // status 200 (the SSE stream opened successfully before upstream returned response.failed), // but they are always client-visible blocked requests that belong in admin + user error // lists. Without the exemption the entire streaming-path cyber sink would be invisible. - if phaseFilter != "upstream" || filter == nil || !filter.IncludeRecoveredUpstream { + if !opsFilterIncludesRecoveredProviderRows(filter, phaseFilter) { clauses = append(clauses, "(COALESCE(e.status_code, 0) >= 400 OR e.error_type = 'cyber_policy')") } @@ -1117,6 +1117,28 @@ func buildOpsErrorLogsWhere(filter *service.OpsErrorLogFilter) (string, []any) { return "WHERE " + strings.Join(clauses, " AND "), args } +func opsFilterIncludesRecoveredProviderRows(filter *service.OpsErrorLogFilter, phaseFilter string) bool { + if filter == nil || !filter.IncludeRecoveredUpstream { + return false + } + if phaseFilter != "" { + return phaseFilter == "upstream" || phaseFilter == "account_auth" + } + if len(filter.ErrorPhasesAny) == 0 { + return false + } + sawProviderPhase := false + for _, rawPhase := range filter.ErrorPhasesAny { + switch strings.TrimSpace(strings.ToLower(rawPhase)) { + case "upstream", "account_auth": + sawProviderPhase = true + default: + return false + } + } + return sawProviderPhase +} + func buildOpsSystemLogsWhere(filter *service.OpsSystemLogFilter) (string, []any, bool) { clauses := make([]string, 0, 10) args := make([]any, 0, 10) @@ -1269,6 +1291,16 @@ func opsNullInt(v any) any { } } +// opsNullableIntPointer distinguishes an absent value from an explicitly +// observed zero. Credential-stage failures intentionally persist upstream +// status 0 because no inference request was sent. +func opsNullableIntPointer(v *int) any { + if v == nil { + return sql.NullInt64{} + } + return sql.NullInt64{Int64: int64(*v), Valid: true} +} + func opsNullInt16(v *int16) any { if v == nil { return sql.NullInt64{} diff --git a/backend/internal/repository/ops_repo_args_test.go b/backend/internal/repository/ops_repo_args_test.go new file mode 100644 index 0000000000..5a88758f0a --- /dev/null +++ b/backend/internal/repository/ops_repo_args_test.go @@ -0,0 +1,37 @@ +//go:build unit + +package repository + +import ( + "database/sql" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestOpsInsertErrorLogArgsPreservesExplicitZeroUpstreamStatus(t *testing.T) { + zero := 0 + args := opsInsertErrorLogArgs(&service.OpsInsertErrorLogInput{UpstreamStatusCode: &zero}) + + require.Len(t, args, 41) + encoded, ok := args[27].(sql.NullInt64) + require.True(t, ok) + require.True(t, encoded.Valid) + require.Zero(t, encoded.Int64) +} + +func TestOpsNullableIntPointerDistinguishesNilZeroAndStatus(t *testing.T) { + missing := opsNullableIntPointer(nil).(sql.NullInt64) + require.False(t, missing.Valid) + + zeroValue := 0 + zero := opsNullableIntPointer(&zeroValue).(sql.NullInt64) + require.True(t, zero.Valid) + require.Zero(t, zero.Int64) + + statusValue := 503 + status := opsNullableIntPointer(&statusValue).(sql.NullInt64) + require.True(t, status.Valid) + require.EqualValues(t, 503, status.Int64) +} diff --git a/backend/internal/repository/ops_repo_get_error_log_by_id_integration_test.go b/backend/internal/repository/ops_repo_get_error_log_by_id_integration_test.go index 470b1c0d0b..1411002be0 100644 --- a/backend/internal/repository/ops_repo_get_error_log_by_id_integration_test.go +++ b/backend/internal/repository/ops_repo_get_error_log_by_id_integration_test.go @@ -91,4 +91,21 @@ func TestGetErrorLogByID_DeletedKeyOwner(t *testing.T) { require.Equal(t, "sk-valid", valid.APIKeyPrefix) require.Empty(t, valid.AttemptedKeyPrefix, "attempted prefix and api key prefix are mutually exclusive") require.Nil(t, valid.DeletedKeyOwnerUserID, "valid key error has no deleted owner") + + // ── Case 4: account_auth with no inference attempt preserves explicit 0 ── + zero := 0 + credentialFailureID, err := repo.InsertErrorLog(ctx, &service.OpsInsertErrorLogInput{ + ErrorPhase: "account_auth", + ErrorType: "upstream_error", + Severity: "error", + StatusCode: 503, + UpstreamStatusCode: &zero, + CreatedAt: time.Now(), + }) + require.NoError(t, err) + + credentialFailure, err := repo.GetErrorLogByID(ctx, credentialFailureID) + require.NoError(t, err) + require.NotNil(t, credentialFailure.UpstreamStatusCode) + require.Zero(t, *credentialFailure.UpstreamStatusCode) } diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 3e67fa5982..539c92741d 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -1268,16 +1268,13 @@ func (a *Account) GetGrokBaseURL() string { if !a.IsGrok() { return "" } - baseURL := a.GetCredential("base_url") if a.IsGrokOAuth() { - if strings.TrimSpace(baseURL) == "" || isOfficialGrokAPIBaseURL(baseURL) { - return xai.DefaultCLIBaseURL - } - if _, err := xai.ValidateTrustedBaseURL(baseURL); err == nil { - return baseURL - } + // OAuth bearer credentials are subscription credentials and may only be + // sent to the supported CLI gateway. Stored base_url values and unsafe + // development overrides apply exclusively to API-key accounts. return xai.DefaultCLIBaseURL } + baseURL := a.GetCredential("base_url") if baseURL != "" { return baseURL } @@ -1286,27 +1283,17 @@ func (a *Account) GetGrokBaseURL() string { // GetGrokMediaBaseURL selects the upstream used by Grok Imagine APIs. // -// OAuth text requests need the CLI subscription proxy, but that proxy has a -// smaller request-body limit than the official Imagine API. Media requests can -// contain large base64 inputs, so default OAuth accounts must use api.x.ai. -// API-key accounts and explicit unsafe development overrides retain their -// configured base URL. +// OAuth media credentials have the same trust boundary as OAuth text traffic: +// they are pinned to the supported CLI gateway even for large request bodies. +// API-key accounts retain their configured public/custom upstream behavior. func (a *Account) GetGrokMediaBaseURL() string { if !a.IsGrok() { return "" } - if !a.IsGrokOAuth() { - return a.GetGrokBaseURL() + if a.IsGrokOAuth() { + return xai.DefaultCLIBaseURL } - - baseURL := a.GetCredential("base_url") - if strings.TrimSpace(baseURL) == "" || isOfficialGrokAPIBaseURL(baseURL) || isOfficialGrokCLIBaseURL(baseURL) { - return xai.DefaultBaseURL - } - if _, err := xai.ValidateTrustedBaseURL(baseURL); err == nil { - return baseURL - } - return xai.DefaultBaseURL + return a.GetGrokBaseURL() } func isOfficialGrokAPIBaseURL(raw string) bool { diff --git a/backend/internal/service/account_base_url_test.go b/backend/internal/service/account_base_url_test.go index 59f53db3db..701a37e131 100644 --- a/backend/internal/service/account_base_url_test.go +++ b/backend/internal/service/account_base_url_test.go @@ -255,7 +255,7 @@ func TestGetGrokBaseURLUsesSubscriptionProxyForOAuth(t *testing.T) { expected: xai.DefaultCLIBaseURL, }, { - name: "oauth non-default API port remains an explicit override", + name: "oauth non-default API port remains pinned to CLI proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, @@ -263,7 +263,7 @@ func TestGetGrokBaseURLUsesSubscriptionProxyForOAuth(t *testing.T) { "base_url": "https://api.x.ai:8443/v1", }, }, - expected: "https://api.x.ai:8443/v1", + expected: xai.DefaultCLIBaseURL, }, { name: "oauth explicit custom base_url stays pinned to CLI proxy by default", @@ -294,7 +294,7 @@ func TestGetGrokBaseURLUsesSubscriptionProxyForOAuth(t *testing.T) { } } -func TestGetGrokBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnabled(t *testing.T) { +func TestGetGrokBaseURLPinsOAuthWhenUnsafeOverridesEnabled(t *testing.T) { t.Setenv(xai.EnvAllowUnsafeURLOverrides, "true") account := Account{ Type: AccountTypeOAuth, @@ -304,26 +304,26 @@ func TestGetGrokBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnabled(t * }, } - require.Equal(t, "https://custom.example.com/v1", account.GetGrokBaseURL()) + require.Equal(t, xai.DefaultCLIBaseURL, account.GetGrokBaseURL()) } -func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { +func TestGetGrokMediaBaseURLPinsOAuthMediaToCLIProxy(t *testing.T) { tests := []struct { name string account Account expected string }{ { - name: "oauth without base_url uses official media API", + name: "oauth without base_url uses CLI subscription proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, Credentials: map[string]any{}, }, - expected: xai.DefaultBaseURL, + expected: xai.DefaultCLIBaseURL, }, { - name: "oauth stored CLI proxy uses official media API", + name: "oauth stored CLI proxy stays on CLI subscription proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, @@ -331,10 +331,10 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { "base_url": xai.DefaultCLIBaseURL, }, }, - expected: xai.DefaultBaseURL, + expected: xai.DefaultCLIBaseURL, }, { - name: "oauth stored CLI proxy variant uses official media API", + name: "oauth stored CLI proxy variant is canonicalized to CLI proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, @@ -342,10 +342,10 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { "base_url": "HTTPS://CLI-CHAT-PROXY.GROK.COM:443/%76%31/", }, }, - expected: xai.DefaultBaseURL, + expected: xai.DefaultCLIBaseURL, }, { - name: "oauth legacy official API remains on official media API", + name: "oauth legacy official API is pinned to CLI proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, @@ -353,10 +353,10 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { "base_url": xai.DefaultBaseURL, }, }, - expected: xai.DefaultBaseURL, + expected: xai.DefaultCLIBaseURL, }, { - name: "oauth untrusted custom base_url is pinned to official media API", + name: "oauth untrusted custom base_url is pinned to CLI proxy", account: Account{ Type: AccountTypeOAuth, Platform: PlatformGrok, @@ -364,7 +364,7 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { "base_url": "https://custom.example.com/v1", }, }, - expected: xai.DefaultBaseURL, + expected: xai.DefaultCLIBaseURL, }, { name: "API key retains its configured media API", @@ -395,7 +395,7 @@ func TestGetGrokMediaBaseURLSeparatesOAuthMediaFromCLIProxy(t *testing.T) { } } -func TestGetGrokMediaBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnabled(t *testing.T) { +func TestGetGrokMediaBaseURLPinsOAuthWhenUnsafeOverridesEnabled(t *testing.T) { t.Setenv(xai.EnvAllowUnsafeURLOverrides, "true") account := Account{ Type: AccountTypeOAuth, @@ -405,5 +405,5 @@ func TestGetGrokMediaBaseURLAllowsExplicitOAuthOverrideWhenUnsafeOverridesEnable }, } - require.Equal(t, "https://custom.example.com/v1", account.GetGrokMediaBaseURL()) + require.Equal(t, xai.DefaultCLIBaseURL, account.GetGrokMediaBaseURL()) } diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 222b3f8a4d..a9eef998e4 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -724,7 +724,9 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account * req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json, text/event-stream") req.Header.Set("Authorization", "Bearer "+authToken) - applyGrokCLIHeaders(req.Header) + if account.IsGrokOAuth() { + applyGrokCLIHeaders(req.Header) + } proxyURL := "" if account.ProxyID != nil && account.Proxy != nil { diff --git a/backend/internal/service/account_test_service_grok_test.go b/backend/internal/service/account_test_service_grok_test.go index 4b0890ff44..f311402874 100644 --- a/backend/internal/service/account_test_service_grok_test.go +++ b/backend/internal/service/account_test_service_grok_test.go @@ -40,8 +40,9 @@ func TestAccountTestService_TestAccountConnection_GrokUsesXAIResponses(t *testin Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "grok-access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "access_token": "grok-access-token", + "refresh_token": "grok-refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), "model_mapping": map[string]any{ "grok": "grok-4.3", }, @@ -133,8 +134,9 @@ func TestAccountTestService_Grok429PersistsRateLimitReset(t *testing.T) { Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "grok-access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "access_token": "grok-access-token", + "refresh_token": "grok-refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), }, } baseRepo := &mockAccountRepoForGemini{accountsByID: map[int64]*Account{account.ID: account}} @@ -166,8 +168,9 @@ func TestAccountTestService_Grok429WithoutQuotaHeadersUsesFallback(t *testing.T) ID: 15, Name: "grok-oauth-limited-no-headers", Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive, Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "grok-access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "access_token": "grok-access-token", + "refresh_token": "grok-refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), }, } baseRepo := &mockAccountRepoForGemini{accountsByID: map[int64]*Account{account.ID: account}} diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index c151375623..49ef63c0c1 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -558,19 +558,79 @@ type ForwardResult struct { ImageSizeBreakdown map[string]int } -// UpstreamFailoverError indicates an upstream error that should trigger account failover. +// GatewayFailureStage identifies which request stage failed. The zero value is +// intentionally treated as inference so existing UpstreamFailoverError callers +// retain their current behavior. +type GatewayFailureStage string + +const ( + GatewayFailureStageInference GatewayFailureStage = "inference" + GatewayFailureStageAccountAuth GatewayFailureStage = "account_auth" +) + +// GatewayFailureScope identifies whether selecting another account can help. +type GatewayFailureScope string + +const ( + GatewayFailureScopeAccount GatewayFailureScope = "account" + GatewayFailureScopeProvider GatewayFailureScope = "provider" + GatewayFailureScopeRequest GatewayFailureScope = "request" +) + +// NextAccountAction is tri-state for backwards compatibility. The zero value +// means legacy retry behavior; only NextAccountStop explicitly short-circuits. +type NextAccountAction uint8 + +const ( + NextAccountLegacyRetry NextAccountAction = iota + NextAccountRetry + NextAccountStop +) + +type GatewayFailureReason string + +// UpstreamFailoverError indicates an upstream or credential error that may +// trigger account failover. Additive metadata keeps existing composite literals +// source-compatible and preserves their legacy retry-next-account behavior. type UpstreamFailoverError struct { StatusCode int ResponseBody []byte // 上游响应体,用于错误透传规则匹配 ResponseHeaders http.Header // 上游响应头,用于透传 cf-ray/cf-mitigated/content-type 等诊断信息 ForceCacheBilling bool // Antigravity 粘性会话切换时设为 true RetryableOnSameAccount bool // 临时性错误(如 Google 间歇性 400、空响应),应在同一账号上重试 N 次再切换 + Stage GatewayFailureStage + Scope GatewayFailureScope + Reason GatewayFailureReason + NextAccountAction NextAccountAction + ClientStatusCode int + ClientMessage string } func (e *UpstreamFailoverError) Error() string { + if e != nil && e.Stage == GatewayFailureStageAccountAuth { + return fmt.Sprintf("credential failure: %s (failover)", e.Reason) + } return fmt.Sprintf("upstream error: %d (failover)", e.StatusCode) } +func (e *UpstreamFailoverError) ShouldRetryNextAccount() bool { + return e != nil && e.NextAccountAction != NextAccountStop +} + +func (e *UpstreamFailoverError) IsCredentialFailure() bool { + return e != nil && e.Stage == GatewayFailureStageAccountAuth +} + +// ShouldReportAccountScheduleFailure prevents provider- and request-scoped +// credential failures from being misattributed to the selected account. Legacy +// and inference failures retain their existing scheduler-health behavior. +func (e *UpstreamFailoverError) ShouldReportAccountScheduleFailure() bool { + if e == nil { + return false + } + return !e.IsCredentialFailure() || e.Scope == GatewayFailureScopeAccount +} + // sseStreamErrorEventError 表示上游 SSE 流体内出现 event:error 帧。 // RawData 是该事件 data: 行的原始 JSON 字符串 // (Anthropic 标准结构 {"type":"error","error":{"type":"...","message":"..."}})。 diff --git a/backend/internal/service/grok_credential_failure.go b/backend/internal/service/grok_credential_failure.go new file mode 100644 index 0000000000..8886855f12 --- /dev/null +++ b/backend/internal/service/grok_credential_failure.go @@ -0,0 +1,650 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "net/http" + "strings" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/gin-gonic/gin" +) + +const ( + grokCredentialFailoverDeadlineKey = "grok_credential_failover_deadline" + grokCredentialFailoverBudget = 15 * time.Second + grokCredentialMutationTimeout = 5 * time.Second + grokCredentialMutationConfirmWait = 250 * time.Millisecond + grokCredentialCacheCleanupTimeout = 500 * time.Millisecond + + GrokCredentialUnavailableClientMessage = "No healthy Grok OAuth account is currently available" + + GrokCredentialReasonRevoked GatewayFailureReason = "grok_oauth_credential_revoked" + GrokCredentialReasonMissing GatewayFailureReason = "grok_oauth_credentials_missing" + GrokCredentialReasonEntitlement GatewayFailureReason = "grok_oauth_entitlement_action_required" + GrokCredentialReasonProxyInvalid GatewayFailureReason = "grok_oauth_proxy_invalid" + GrokCredentialReasonRefreshTransient GatewayFailureReason = "grok_oauth_refresh_transient" + GrokCredentialReasonProviderConfig GatewayFailureReason = "grok_oauth_provider_config" + GrokCredentialReasonProviderDown GatewayFailureReason = "grok_oauth_provider_unavailable" + GrokCredentialReasonAccountChanged GatewayFailureReason = "grok_oauth_account_state_changed" + GrokCredentialReasonStateUpdate GatewayFailureReason = "grok_oauth_account_state_update_failed" + GrokCredentialReasonFailoverTimeout GatewayFailureReason = "grok_oauth_failover_timeout" +) + +var errGrokCredentialStateUpdateFailed = errors.New("grok oauth account state update failed") + +type grokCredentialFailureClass struct { + scope GatewayFailureScope + reason GatewayFailureReason + action NextAccountAction + permanent bool + transient bool + message string + snapshot *GrokCredentialMutationSnapshot +} + +// GrokCredentialMutationSnapshot is the credential identity observed when the +// request selected an account. Repository mutations compare all fields before +// quarantining that account so a concurrent refresh cannot be overwritten. +type GrokCredentialMutationSnapshot struct { + CredentialsJSON string + AccessToken string + RefreshToken string + TokenVersion int64 + ProxyID *int64 +} + +type grokCredentialFailureSnapshotError struct { + cause error + snapshot GrokCredentialMutationSnapshot +} + +func (e *grokCredentialFailureSnapshotError) Error() string { return e.cause.Error() } +func (e *grokCredentialFailureSnapshotError) Unwrap() error { return e.cause } + +func withGrokCredentialFailureSnapshot(err error, account *Account) error { + if err == nil || account == nil || !account.IsGrokOAuth() { + return err + } + var existing *grokCredentialFailureSnapshotError + if errors.As(err, &existing) { + return err + } + return &grokCredentialFailureSnapshotError{cause: err, snapshot: grokCredentialMutationSnapshot(account)} +} + +func grokCredentialFailureSnapshot(err error) (GrokCredentialMutationSnapshot, bool) { + var snapshotErr *grokCredentialFailureSnapshotError + if !errors.As(err, &snapshotErr) || snapshotErr == nil { + return GrokCredentialMutationSnapshot{}, false + } + return snapshotErr.snapshot, true +} + +type grokCredentialConditionalStateRepository interface { + SetGrokCredentialErrorIfMatch(context.Context, int64, GrokCredentialMutationSnapshot, string) (bool, error) + SetGrokCredentialTempUnschedulableIfMatch(context.Context, int64, GrokCredentialMutationSnapshot, time.Time, string) (bool, error) +} + +// GetRequestCredential applies the request-path credential and failover contract +// before any upstream transport is opened. +func (s *OpenAIGatewayService) GetRequestCredential(ctx context.Context, c *gin.Context, account *Account) (string, string, error) { + return s.getRequestCredential(ctx, c, account) +} + +func (s *OpenAIGatewayService) getRequestCredential(ctx context.Context, c *gin.Context, account *Account) (string, string, error) { + if ctx == nil { + ctx = context.Background() + } + if account == nil { + return "", "", errors.New("account is nil") + } + if !account.IsGrokOAuth() { + return s.GetAccessToken(ctx, account) + } + if err := ctx.Err(); err != nil { + return "", "", err + } + if s == nil || s.grokTokenProvider == nil { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeProvider, + reason: GrokCredentialReasonProviderConfig, + action: NextAccountStop, + message: "Grok OAuth credential provider is unavailable", + }) + } + if s.isOpenAIAccountRuntimeBlocked(account) { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeAccount, + reason: GrokCredentialReasonAccountChanged, + action: NextAccountRetry, + message: "Grok OAuth account is not currently schedulable", + }) + } + + credentialCtx, cancel, budgetExpired := grokCredentialAcquisitionContext(ctx, c) + if cancel != nil { + defer cancel() + } + if budgetExpired { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeRequest, + reason: GrokCredentialReasonFailoverTimeout, + action: NextAccountStop, + message: "Grok OAuth credential failover budget exhausted", + }) + } + + token, kind, err := s.GetAccessToken(credentialCtx, account) + if err == nil { + if s.isOpenAIAccountRuntimeBlocked(account) { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeAccount, + reason: GrokCredentialReasonAccountChanged, + action: NextAccountRetry, + message: "Grok OAuth account is not currently schedulable", + }) + } + return token, kind, nil + } + if parentErr := ctx.Err(); parentErr != nil { + return "", "", parentErr + } + if credentialCtx.Err() != nil { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeRequest, + reason: GrokCredentialReasonFailoverTimeout, + action: NextAccountStop, + message: "Grok OAuth credential failover budget exhausted", + }) + } + + class := classifyGrokCredentialFailure(account, err) + if snapshot, ok := grokCredentialFailureSnapshot(err); ok { + class.snapshot = &snapshot + } + if ctx.Err() != nil { + return "", "", ctx.Err() + } + if class.permanent || class.transient { + freshToken, mutationErr := s.applyGrokCredentialAccountFailure(credentialCtx, account, class) + if freshToken != "" { + return freshToken, "oauth", nil + } + if mutationErr != nil { + if ctx.Err() != nil { + return "", "", ctx.Err() + } + if credentialCtx.Err() != nil { + return "", "", s.newGrokCredentialFailover(c, account, grokCredentialFailureClass{ + scope: GatewayFailureScopeRequest, + reason: GrokCredentialReasonFailoverTimeout, + action: NextAccountStop, + message: "Grok OAuth credential failover budget exhausted", + }) + } + if errors.Is(mutationErr, errOAuthRefreshAccountStateChanged) { + class = grokCredentialFailureClass{ + scope: GatewayFailureScopeAccount, + reason: GrokCredentialReasonAccountChanged, + action: NextAccountRetry, + message: "Grok OAuth account eligibility changed", + } + } else if errors.Is(mutationErr, errOAuthRefreshAccountRereadFailed) { + class = grokCredentialFailureClass{ + scope: GatewayFailureScopeProvider, + reason: GrokCredentialReasonProviderDown, + action: NextAccountStop, + message: "Grok OAuth account state is temporarily unavailable", + } + } else { + class = grokCredentialFailureClass{ + scope: GatewayFailureScopeProvider, + reason: GrokCredentialReasonStateUpdate, + action: NextAccountStop, + message: "Grok OAuth account state could not be updated safely", + } + } + } + } + return "", "", s.newGrokCredentialFailover(c, account, class) +} + +func grokCredentialAcquisitionContext(ctx context.Context, c *gin.Context) (context.Context, context.CancelFunc, bool) { + if c == nil { + return ctx, nil, false + } + deadline := time.Time{} + if raw, ok := c.Get(grokCredentialFailoverDeadlineKey); ok { + deadline, _ = raw.(time.Time) + } + if deadline.IsZero() { + deadline = time.Now().Add(grokCredentialFailoverBudget) + c.Set(grokCredentialFailoverDeadlineKey, deadline) + } + if !time.Now().Before(deadline) { + return ctx, nil, true + } + acquireCtx, cancel := context.WithDeadline(ctx, deadline) + return acquireCtx, cancel, false +} + +func classifyGrokCredentialFailure(account *Account, err error) grokCredentialFailureClass { + stableReason := strings.ToLower(strings.TrimSpace(infraerrors.Reason(err))) + message := "" + if err != nil { + message = strings.ToLower(err.Error()) + } + contains := func(values ...string) bool { + for _, value := range values { + if strings.Contains(stableReason, value) || strings.Contains(message, value) { + return true + } + } + return false + } + + switch { + case errors.Is(err, errGrokOAuthRefreshTokenMissing), errors.Is(err, errGrokOAuthAccessTokenMissing), errors.Is(err, errGrokOAuthAccessTokenExpired): + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonMissing, action: NextAccountRetry, permanent: true, message: "Grok OAuth credentials are missing or expired"} + case contains("invalid_grant", "invalid_refresh_token", "token_expired", "refresh_token_reused", "refresh_token_invalidated", "app_session_terminated"): + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonRevoked, action: NextAccountRetry, permanent: true, message: "Grok OAuth credentials require account action"} + case contains("grok_oauth_entitlement_denied", "entitlement_denied", "access_denied", "subscription required", "no active grok subscription"): + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonEntitlement, action: NextAccountRetry, permanent: true, message: "Grok OAuth entitlement requires account action"} + case errors.Is(err, errGrokOAuthConfiguredProxyMiss), contains("grok_oauth_proxy_not_found"): + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonProxyInvalid, action: NextAccountRetry, permanent: true, message: "Grok OAuth account proxy configuration is invalid"} + case errors.Is(err, errOAuthRefreshAccountRereadFailed): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth account state is temporarily unavailable"} + case errors.Is(err, errOAuthRefreshCredentialPersist): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth shared credential state is temporarily unavailable"} + case errors.Is(err, errOAuthRefreshAccountStateChanged): + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonAccountChanged, action: NextAccountRetry, message: "Grok OAuth account eligibility changed"} + case errors.Is(err, errGrokOAuthRefreshNotConfigured), contains("invalid_client", "unauthorized_client", "invalid_scope", "unknown scope", "grok oauth service is not configured", "grok_oauth_proxy_not_available"): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderConfig, action: NextAccountStop, message: "Grok OAuth provider configuration is unavailable"} + case contains("grok_oauth_proxy_lookup_failed"), + contains("grok_oauth_token_refresh_failed") && contains("status 403") && (account == nil || account.ProxyID == nil): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider is temporarily unavailable"} + case contains("grok_oauth_client_init_failed") && (account == nil || account.ProxyID == nil): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderConfig, action: NextAccountStop, message: "Grok OAuth provider configuration is unavailable"} + case contains("grok_oauth_request_failed") && (account == nil || account.ProxyID == nil): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider is temporarily unavailable"} + case contains("status 429", "status 500", "status 502", "status 503", "status 504") && (account == nil || account.ProxyID == nil): + return grokCredentialFailureClass{scope: GatewayFailureScopeProvider, reason: GrokCredentialReasonProviderDown, action: NextAccountStop, message: "Grok OAuth provider is temporarily unavailable"} + default: + return grokCredentialFailureClass{scope: GatewayFailureScopeAccount, reason: GrokCredentialReasonRefreshTransient, action: NextAccountRetry, transient: true, message: "Grok OAuth credential refresh is temporarily unavailable"} + } +} + +func (s *OpenAIGatewayService) applyGrokCredentialAccountFailure(ctx context.Context, account *Account, class grokCredentialFailureClass) (string, error) { + if s == nil || account == nil || ctx == nil || ctx.Err() != nil { + if ctx != nil { + return "", ctx.Err() + } + return "", context.Canceled + } + mutationMu := s.grokCredentialMutationLock(account.ID) + if err := mutationMu.Lock(ctx); err != nil { + return "", err + } + defer mutationMu.Unlock() + stateRepo, hasConditionalStateRepo := s.accountRepo.(grokCredentialConditionalStateRepository) + snapshot := grokCredentialMutationSnapshot(account) + if class.snapshot != nil { + snapshot = *class.snapshot + } + if token, err := s.validateCurrentGrokCredentialFailure(ctx, account.ID, snapshot, class); err != nil || token != "" { + return token, err + } + + if class.permanent { + if token, ok := s.grokCredentialConcurrentlyRefreshedToken(ctx, account.ID, snapshot); ok { + return token, nil + } + if ctx.Err() != nil { + return "", ctx.Err() + } + rollbackRuntime := s.blockGrokCredentialRuntime(account, time.Time{}, string(class.reason)) + keepRuntimeBlock := false + runtimeRollbackDone := false + defer func() { + if !keepRuntimeBlock && !runtimeRollbackDone { + rollbackRuntime() + } + }() + if s.accountRepo == nil { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: account repository is not configured", errGrokCredentialStateUpdateFailed) + } + if !hasConditionalStateRepo { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: conditional account repository is not configured", errGrokCredentialStateUpdateFailed) + } + stateCtx, cancel := context.WithTimeout(ctx, grokCredentialMutationTimeout) + if err := ctx.Err(); err != nil { + cancel() + return "", err + } + updated, err := stateRepo.SetGrokCredentialErrorIfMatch(stateCtx, account.ID, snapshot, string(class.reason)) + requestErr := ctx.Err() + cancel() + if err != nil { + slog.Warn("grok_credential_failure.set_error_failed", "account_id", account.ID, "reason", class.reason, "error", err) + if requestErr != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + if s.grokCredentialMutationCommitted(account.ID, class, time.Time{}) { + updated = true + } else if requestErr != nil { + return "", requestErr + } else { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: permanent state commit could not be confirmed: %v", errGrokCredentialStateUpdateFailed, err) + } + } else { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: persist permanent state: %v", errGrokCredentialStateUpdateFailed, err) + } + } + if !updated { + rollbackRuntime() + runtimeRollbackDone = true + return s.resolveGrokCredentialCASMiss(ctx, account.ID, snapshot) + } + // SetError is the linearization point: the durable quarantine is now + // committed and this node's runtime block must not be rolled back. + keepRuntimeBlock = true + if s.grokTokenProvider == nil { + if ctx.Err() != nil { + return "", ctx.Err() + } + return "", fmt.Errorf("%w: token provider is not configured", errGrokCredentialStateUpdateFailed) + } + invalidateCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), grokCredentialCacheCleanupTimeout) + err = s.grokTokenProvider.InvalidateToken(invalidateCtx, account) + cancel() + if err != nil { + slog.Warn("grok_credential_failure.invalidate_token_failed", "account_id", account.ID, "reason", class.reason, "error", err) + if ctx.Err() != nil { + return "", ctx.Err() + } + return "", fmt.Errorf("%w: invalidate cached credential: %v", errGrokCredentialStateUpdateFailed, err) + } + if ctx.Err() != nil { + return "", ctx.Err() + } + return "", nil + } + + if class.transient { + until := time.Now().Add(tokenRefreshTempUnschedDuration) + if ctx.Err() != nil { + return "", ctx.Err() + } + rollbackRuntime := s.blockGrokCredentialRuntime(account, until, string(class.reason)) + keepRuntimeBlock := false + runtimeRollbackDone := false + defer func() { + if !keepRuntimeBlock && !runtimeRollbackDone { + rollbackRuntime() + } + }() + stateCtx, cancel := context.WithTimeout(ctx, grokCredentialMutationTimeout) + if s.accountRepo == nil { + cancel() + keepRuntimeBlock = true + return "", fmt.Errorf("%w: account repository is not configured", errGrokCredentialStateUpdateFailed) + } + if !hasConditionalStateRepo { + cancel() + keepRuntimeBlock = true + return "", fmt.Errorf("%w: conditional account repository is not configured", errGrokCredentialStateUpdateFailed) + } + if err := ctx.Err(); err != nil { + cancel() + return "", err + } + updated, err := stateRepo.SetGrokCredentialTempUnschedulableIfMatch(stateCtx, account.ID, snapshot, until, string(class.reason)) + requestErr := ctx.Err() + cancel() + if err != nil { + slog.Warn("grok_credential_failure.set_temp_unschedulable_failed", "account_id", account.ID, "reason", class.reason, "error", err) + if requestErr != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + if s.grokCredentialMutationCommitted(account.ID, class, until) { + updated = true + } else if requestErr != nil { + return "", requestErr + } else { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: transient state commit could not be confirmed: %v", errGrokCredentialStateUpdateFailed, err) + } + } else { + keepRuntimeBlock = true + return "", fmt.Errorf("%w: persist transient state: %v", errGrokCredentialStateUpdateFailed, err) + } + } + if !updated { + rollbackRuntime() + runtimeRollbackDone = true + return s.resolveGrokCredentialCASMiss(ctx, account.ID, snapshot) + } + // The temporary quarantine is durable after SetTempUnschedulable succeeds. + keepRuntimeBlock = true + if ctx.Err() != nil { + return "", ctx.Err() + } + return "", nil + } + + return "", nil +} + +func (s *OpenAIGatewayService) validateCurrentGrokCredentialFailure( + ctx context.Context, + accountID int64, + snapshot GrokCredentialMutationSnapshot, + class grokCredentialFailureClass, +) (string, error) { + if s == nil || s.accountRepo == nil || accountID <= 0 || ctx == nil || ctx.Err() != nil { + if ctx != nil { + return "", ctx.Err() + } + return "", context.Canceled + } + checkCtx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + latest, err := s.accountRepo.GetByID(checkCtx, accountID) + if err != nil { + if errors.Is(err, ErrAccountNotFound) { + return "", errOAuthRefreshAccountStateChanged + } + return "", fmt.Errorf("%w: %v", errOAuthRefreshAccountRereadFailed, err) + } + if latest == nil || !latest.IsGrokOAuth() || !latest.IsSchedulable() || s.isOpenAIAccountRuntimeBlocked(latest) { + return "", errOAuthRefreshAccountStateChanged + } + latestSnapshot := grokCredentialMutationSnapshot(latest) + if latestSnapshot.CredentialsJSON != snapshot.CredentialsJSON || + !grokCredentialProxyIDsEqual(latestSnapshot.ProxyID, snapshot.ProxyID) { + if token, ok := s.grokCredentialConcurrentlyRefreshedToken(ctx, accountID, snapshot); ok { + return token, nil + } + return "", errOAuthRefreshAccountStateChanged + } + + // A configured proxy is external to the account-row CAS identity. Recheck + // the hydrated proxy object so restoring a deleted row under the same ID + // wins over a stale proxy-invalid failure. + if class.reason == GrokCredentialReasonProxyInvalid { + if latest.ProxyID == nil || latest.Proxy != nil { + return "", errOAuthRefreshAccountStateChanged + } + } else if latest.ProxyID != nil && latest.Proxy == nil { + return "", errOAuthRefreshAccountStateChanged + } + + if class.reason == GrokCredentialReasonMissing { + expiresAt := latest.GetCredentialAsTime("expires_at") + credentialsStillMissing := strings.TrimSpace(latest.GetGrokAccessToken()) == "" || + strings.TrimSpace(latest.GetGrokRefreshToken()) == "" || expiresAt == nil || !time.Now().Before(*expiresAt) + if !credentialsStillMissing { + return "", errOAuthRefreshAccountStateChanged + } + } + return "", nil +} + +func (s *OpenAIGatewayService) grokCredentialMutationLock(accountID int64) *oauthRefreshLocalLock { + actual, _ := s.grokCredentialMutationLocks.LoadOrStore(accountID, newOAuthRefreshLocalLock()) + return actual.(*oauthRefreshLocalLock) +} + +func (s *OpenAIGatewayService) grokCredentialMutationCommitted(accountID int64, class grokCredentialFailureClass, until time.Time) bool { + if s == nil || s.accountRepo == nil || accountID <= 0 { + return false + } + confirmCtx, cancel := context.WithTimeout(context.Background(), grokCredentialMutationConfirmWait) + defer cancel() + latest, err := s.accountRepo.GetByID(confirmCtx, accountID) + if err != nil || latest == nil { + return false + } + if class.permanent { + return latest.Status == StatusError && !latest.Schedulable && latest.ErrorMessage == string(class.reason) + } + if class.transient { + return latest.TempUnschedulableUntil != nil && !latest.TempUnschedulableUntil.Before(until) && + latest.TempUnschedulableReason == string(class.reason) + } + return false +} + +func grokCredentialMutationSnapshot(account *Account) GrokCredentialMutationSnapshot { + if account == nil { + return GrokCredentialMutationSnapshot{} + } + credentialsJSON := "null" + if encoded, err := json.Marshal(account.Credentials); err == nil { + credentialsJSON = string(encoded) + } + snapshot := GrokCredentialMutationSnapshot{ + CredentialsJSON: credentialsJSON, + AccessToken: strings.TrimSpace(account.GetGrokAccessToken()), + RefreshToken: strings.TrimSpace(account.GetGrokRefreshToken()), + TokenVersion: account.GetCredentialAsInt64("_token_version"), + } + if account.ProxyID != nil { + proxyID := *account.ProxyID + snapshot.ProxyID = &proxyID + } + return snapshot +} + +func (s *OpenAIGatewayService) resolveGrokCredentialCASMiss(ctx context.Context, accountID int64, snapshot GrokCredentialMutationSnapshot) (string, error) { + if ctx.Err() != nil { + return "", ctx.Err() + } + if token, ok := s.grokCredentialConcurrentlyRefreshedToken(ctx, accountID, snapshot); ok { + return token, nil + } + return "", errOAuthRefreshAccountStateChanged +} + +func (s *OpenAIGatewayService) blockGrokCredentialRuntime(account *Account, until time.Time, reason string) func() { + if s == nil || account == nil { + return func() {} + } + mu := s.openAIAccountRuntimeBlockLock(account.ID) + mu.Lock() + before, hadBefore := s.openaiAccountRuntimeBlockUntil.Load(account.ID) + installedGeneration, changed := s.blockAccountSchedulingLocked(account, until, reason) + installed, installedOK := s.openaiAccountRuntimeBlockUntil.Load(account.ID) + installedUntil, isTime := installed.(time.Time) + mu.Unlock() + if !changed || !installedOK || !isTime { + return func() {} + } + if hadBefore { + if beforeUntil, ok := before.(time.Time); ok && beforeUntil.Equal(installedUntil) { + return func() {} + } + } + return func() { + mu.Lock() + defer mu.Unlock() + generation, ok := s.openaiAccountRuntimeBlockGeneration.Load(account.ID) + if !ok || generation != installedGeneration { + return + } + current, ok := s.openaiAccountRuntimeBlockUntil.Load(account.ID) + currentUntil, isTime := current.(time.Time) + if !ok || !isTime || !currentUntil.Equal(installedUntil) { + return + } + if hadBefore { + s.openaiAccountRuntimeBlockUntil.Store(account.ID, before) + s.openaiAccountRuntimeBlockGeneration.Store(account.ID, s.openaiAccountRuntimeBlockSequence.Add(1)) + return + } + s.openaiAccountRuntimeBlockUntil.Delete(account.ID) + s.openaiAccountRuntimeBlockGeneration.Store(account.ID, s.openaiAccountRuntimeBlockSequence.Add(1)) + } +} + +func (s *OpenAIGatewayService) grokCredentialConcurrentlyRefreshedToken(ctx context.Context, accountID int64, baseline GrokCredentialMutationSnapshot) (string, bool) { + if s == nil || s.accountRepo == nil || accountID <= 0 || ctx == nil || ctx.Err() != nil { + return "", false + } + checkCtx, cancel := context.WithTimeout(ctx, time.Second) + defer cancel() + latest, err := s.accountRepo.GetByID(checkCtx, accountID) + if err != nil || latest == nil { + return "", false + } + latestSnapshot := grokCredentialMutationSnapshot(latest) + if !grokCredentialProxyIDsEqual(latestSnapshot.ProxyID, baseline.ProxyID) || + latestSnapshot.CredentialsJSON == baseline.CredentialsJSON || !latest.IsSchedulable() || + (latest.ProxyID != nil && latest.Proxy == nil) || s.isOpenAIAccountRuntimeBlocked(latest) { + return "", false + } + latestToken := strings.TrimSpace(latest.GetGrokAccessToken()) + if latestToken == "" || strings.TrimSpace(latest.GetGrokRefreshToken()) == "" { + return "", false + } + expiresAt := latest.GetCredentialAsTime("expires_at") + if expiresAt == nil || !time.Now().Before(*expiresAt) { + return "", false + } + return latestToken, true +} + +func grokCredentialProxyIDsEqual(left, right *int64) bool { + if left == nil || right == nil { + return left == nil && right == nil + } + return *left == *right +} + +func (s *OpenAIGatewayService) newGrokCredentialFailover(c *gin.Context, account *Account, class grokCredentialFailureClass) error { + if strings.TrimSpace(class.message) == "" { + class.message = "Grok OAuth credentials are unavailable" + } + appendOpsUpstreamError(c, OpsUpstreamErrorEvent{ + Platform: PlatformGrok, + AccountID: account.ID, + Stage: string(GatewayFailureStageAccountAuth), + Scope: string(class.scope), + Reason: string(class.reason), + Kind: "credential_failover", + Message: class.message, + }) + return &UpstreamFailoverError{ + Stage: GatewayFailureStageAccountAuth, + Scope: class.scope, + Reason: class.reason, + NextAccountAction: class.action, + ClientStatusCode: http.StatusServiceUnavailable, + ClientMessage: GrokCredentialUnavailableClientMessage, + } +} diff --git a/backend/internal/service/grok_credential_failure_test.go b/backend/internal/service/grok_credential_failure_test.go new file mode 100644 index 0000000000..c32559ea12 --- /dev/null +++ b/backend/internal/service/grok_credential_failure_test.go @@ -0,0 +1,1622 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "sync" + "testing" + "time" + + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type grokCredentialPersistingRepo struct { + *tokenRefreshAccountRepo +} + +func (r *grokCredentialPersistingRepo) SetError(ctx context.Context, id int64, message string) error { + if err := ctx.Err(); err != nil { + return err + } + if err := r.tokenRefreshAccountRepo.SetError(ctx, id, message); err != nil { + return err + } + if account := r.accountsByID[id]; account != nil { + account.Status = StatusError + account.Schedulable = false + account.ErrorMessage = message + } + return nil +} + +type grokCredentialProxyRepoStub struct { + ProxyRepository + proxy *Proxy + err error +} + +func (r *grokCredentialProxyRepoStub) GetByID(context.Context, int64) (*Proxy, error) { + return r.proxy, r.err +} + +type grokCredentialBlockingRepo struct { + *tokenRefreshAccountRepo + setErrorStarted chan struct{} + setTempStarted chan struct{} + onceError sync.Once + onceTemp sync.Once +} + +type grokCredentialCommitThenCancelRepo struct { + *tokenRefreshAccountRepo + returnErr error +} + +type grokCredentialUncommittedDeadlineRepo struct { + *tokenRefreshAccountRepo +} + +func (r *grokCredentialUncommittedDeadlineRepo) SetGrokCredentialErrorIfMatch( + context.Context, + int64, + GrokCredentialMutationSnapshot, + string, +) (bool, error) { + return false, context.DeadlineExceeded +} + +func (r *grokCredentialUncommittedDeadlineRepo) SetGrokCredentialTempUnschedulableIfMatch( + context.Context, + int64, + GrokCredentialMutationSnapshot, + time.Time, + string, +) (bool, error) { + return false, context.DeadlineExceeded +} + +func (r *grokCredentialCommitThenCancelRepo) SetGrokCredentialErrorIfMatch( + ctx context.Context, + id int64, + _ GrokCredentialMutationSnapshot, + reason string, +) (bool, error) { + account := r.accountsByID[id] + account.Status = StatusError + account.Schedulable = false + account.ErrorMessage = reason + if r.returnErr != nil { + return false, r.returnErr + } + <-ctx.Done() + return false, ctx.Err() +} + +func (r *grokCredentialCommitThenCancelRepo) SetGrokCredentialTempUnschedulableIfMatch( + ctx context.Context, + id int64, + _ GrokCredentialMutationSnapshot, + until time.Time, + reason string, +) (bool, error) { + account := r.accountsByID[id] + account.TempUnschedulableUntil = &until + account.TempUnschedulableReason = reason + if r.returnErr != nil { + return false, r.returnErr + } + <-ctx.Done() + return false, ctx.Err() +} + +func (r *grokCredentialBlockingRepo) SetError(ctx context.Context, _ int64, _ string) error { + r.onceError.Do(func() { close(r.setErrorStarted) }) + <-ctx.Done() + return ctx.Err() +} + +func (r *grokCredentialBlockingRepo) SetTempUnschedulable(ctx context.Context, _ int64, _ time.Time, _ string) error { + r.onceTemp.Do(func() { close(r.setTempStarted) }) + <-ctx.Done() + return ctx.Err() +} + +func (r *grokCredentialBlockingRepo) SetGrokCredentialErrorIfMatch( + ctx context.Context, + _ int64, + _ GrokCredentialMutationSnapshot, + _ string, +) (bool, error) { + r.onceError.Do(func() { close(r.setErrorStarted) }) + <-ctx.Done() + return false, ctx.Err() +} + +func (r *grokCredentialBlockingRepo) SetGrokCredentialTempUnschedulableIfMatch( + ctx context.Context, + _ int64, + _ GrokCredentialMutationSnapshot, + _ time.Time, + _ string, +) (bool, error) { + r.onceTemp.Do(func() { close(r.setTempStarted) }) + <-ctx.Done() + return false, ctx.Err() +} + +type grokCredentialBlockingCache struct { + GrokTokenCache + deleteStarted chan struct{} + releaseDelete chan struct{} + once sync.Once + mu sync.Mutex + deleted bool +} + +type grokCredentialSequencedRepo struct { + *tokenRefreshAccountRepo + mu sync.Mutex + latest *Account + getCall int +} + +type grokCredentialRereadFailureRepo struct { + *tokenRefreshAccountRepo + account *Account + err error +} + +type grokCredentialCountingRefresher struct { + refreshCalls int +} + +func (r *grokCredentialCountingRefresher) CacheKey(account *Account) string { + return GrokTokenCacheKey(account) +} + +func (r *grokCredentialCountingRefresher) CanRefresh(*Account) bool { return true } + +func (r *grokCredentialCountingRefresher) NeedsRefresh(*Account, time.Duration) bool { return true } + +func (r *grokCredentialCountingRefresher) Refresh(context.Context, *Account) (map[string]any, error) { + r.refreshCalls++ + return map[string]any{"access_token": "must-not-be-used"}, nil +} + +func (r *grokCredentialRereadFailureRepo) GetByID(context.Context, int64) (*Account, error) { + return r.account, r.err +} + +func (r *grokCredentialSequencedRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.getCall++ + if r.getCall > 1 && r.latest != nil { + return r.latest, nil + } + return r.tokenRefreshAccountRepo.GetByID(ctx, id) +} + +func (c *grokCredentialBlockingCache) DeleteAccessToken(ctx context.Context, _ string) error { + c.once.Do(func() { close(c.deleteStarted) }) + select { + case <-c.releaseDelete: + c.mu.Lock() + c.deleted = true + c.mu.Unlock() + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (c *grokCredentialBlockingCache) wasDeleted() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.deleted +} + +func TestUpstreamFailoverErrorNextAccountActionPreservesLegacyRetry(t *testing.T) { + t.Parallel() + + require.True(t, (&UpstreamFailoverError{}).ShouldRetryNextAccount()) + require.True(t, (&UpstreamFailoverError{NextAccountAction: NextAccountRetry}).ShouldRetryNextAccount()) + require.False(t, (&UpstreamFailoverError{NextAccountAction: NextAccountStop}).ShouldRetryNextAccount()) +} + +func TestGetRequestCredentialMapsPermanentGrokOAuthFailureAndRedactsSecrets(t *testing.T) { + gin.SetMode(gin.TestMode) + account := expiredGrokOAuthAccountForCredentialTest(701) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant access_token=leaked-access refresh_token=leaked-refresh"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + require.Error(t, err) + require.Empty(t, token) + require.Empty(t, kind) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureStageAccountAuth, failoverErr.Stage) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonRevoked, failoverErr.Reason) + require.True(t, failoverErr.ShouldRetryNextAccount()) + require.Equal(t, 0, failoverErr.StatusCode) + require.Equal(t, http.StatusServiceUnavailable, failoverErr.ClientStatusCode) + require.NotContains(t, err.Error(), "leaked-access") + require.NotContains(t, err.Error(), "leaked-refresh") + + require.Equal(t, 1, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + require.NotContains(t, repo.lastErrorMessage, "leaked-access") + require.NotContains(t, repo.lastErrorMessage, "leaked-refresh") + + rawEvents, ok := c.Get(OpsUpstreamErrorsKey) + require.True(t, ok) + events, ok := rawEvents.([]*OpsUpstreamErrorEvent) + require.True(t, ok) + require.Len(t, events, 1) + require.Equal(t, string(GatewayFailureStageAccountAuth), events[0].Stage) + require.Equal(t, string(GatewayFailureScopeAccount), events[0].Scope) + require.Equal(t, string(GrokCredentialReasonRevoked), events[0].Reason) + require.Zero(t, events[0].UpstreamStatusCode) + require.NotContains(t, events[0].Message, "leaked-access") + require.NotContains(t, events[0].Message, "leaked-refresh") +} + +func TestGetRequestCredentialPermanentMappingsPersistAndInvalidate(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + prepare func(*Account) + refreshErr error + wantReason GatewayFailureReason + cachedToken string + }{ + { + name: "missing refresh credential", + prepare: func(account *Account) { + delete(account.Credentials, "refresh_token") + }, + wantReason: GrokCredentialReasonMissing, + }, + { + name: "missing access credential", + prepare: func(account *Account) { + delete(account.Credentials, "access_token") + account.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + }, + wantReason: GrokCredentialReasonMissing, + cachedToken: "stale-cached-access", + }, + { + name: "explicit entitlement action required", + prepare: func(*Account) {}, + refreshErr: infraerrors.New(http.StatusForbidden, "GROK_OAUTH_ENTITLEMENT_DENIED", "access_denied"), + wantReason: GrokCredentialReasonEntitlement, + }, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(720 + index)) + account.Status = StatusActive + account.Schedulable = true + tt.prepare(account) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true, token: tt.cachedToken} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{err: tt.refreshErr}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, tt.wantReason, failoverErr.Reason) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Equal(t, StatusError, account.Status) + require.False(t, account.Schedulable) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + }) + } +} + +func TestGetRequestCredentialMissingAccessNeverRefreshesAndPermanentlyFailsOver(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + expiresAt *time.Time + }{ + {name: "expiry missing"}, + {name: "expired", expiresAt: func() *time.Time { value := time.Now().Add(-time.Minute); return &value }()}, + {name: "near expiry", expiresAt: func() *time.Time { value := time.Now().Add(30 * time.Minute); return &value }()}, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(760 + index)) + account.Schedulable = true + delete(account.Credentials, "access_token") + if tt.expiresAt == nil { + delete(account.Credentials, "expires_at") + } else { + account.Credentials["expires_at"] = tt.expiresAt.UTC().Format(time.RFC3339) + } + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true, token: "stale-cache-must-not-win"} + refresher := &grokCredentialCountingRefresher{} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), refresher) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Empty(t, token) + require.Empty(t, kind) + require.Equal(t, GrokCredentialReasonMissing, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, refresher.refreshCalls, "structurally missing access credentials must not reach the token endpoint") + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Equal(t, StatusError, account.Status) + require.False(t, account.Schedulable) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } +} + +func TestGetRequestCredentialWarmCachedAccessWithMissingRefreshPermanentlyFailsOver(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(764) + account.Credentials["access_token"] = "valid-access" + account.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + delete(account.Credentials, "refresh_token") + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true, token: "valid-access"} + refresher := &grokCredentialCountingRefresher{} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), refresher) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GrokCredentialReasonMissing, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, refresher.refreshCalls) + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialMapsTransientAndProviderFailuresSeparately(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("account transient temporarily unschedules", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(702) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{err: errors.New("temporary refresh transport failure")}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonRefreshTransient, failoverErr.Reason) + require.True(t, failoverErr.ShouldRetryNextAccount()) + require.Zero(t, repo.setErrorCalls) + require.Equal(t, 1, repo.setTempUnschedCalls) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("shared provider configuration stops without mutation", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(703) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + provider := NewGrokTokenProvider(repo, nil) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("account reread failures preserve shared versus missing-row scope", func(t *testing.T) { + for _, tt := range []struct { + name string + account *Account + err error + }{ + {name: "repository error", err: errors.New("database temporarily unavailable")}, + {name: "missing row"}, + } { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(712) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialRereadFailureRepo{tokenRefreshAccountRepo: baseRepo, account: tt.account, err: tt.err} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(nil)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + if tt.err != nil { + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonProviderDown, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + } else { + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonAccountChanged, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + } + require.Zero(t, baseRepo.setErrorCalls) + require.Zero(t, baseRepo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } + }) + + t.Run("fresh account eligibility changes retry without mutating stale state", func(t *testing.T) { + for _, tt := range []struct { + name string + mutate func(*Account) + }{ + { + name: "account disabled", + mutate: func(account *Account) { + account.Status = StatusDisabled + }, + }, + { + name: "account converted", + mutate: func(account *Account) { + account.Type = AccountTypeUpstream + }, + }, + { + name: "account manually unschedulable", + mutate: func(account *Account) { + account.Schedulable = false + }, + }, + { + name: "account temporarily unschedulable", + mutate: func(account *Account) { + until := time.Now().Add(time.Minute) + account.TempUnschedulableUntil = &until + }, + }, + } { + t.Run(tt.name, func(t *testing.T) { + staleAccount := expiredGrokOAuthAccountForCredentialTest(713) + freshAccount := *staleAccount + freshAccount.Credentials = shallowCopyMap(staleAccount.Credentials) + tt.mutate(&freshAccount) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{staleAccount.ID: &freshAccount} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(nil)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, staleAccount) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonAccountChanged, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(staleAccount)) + }) + } + }) + + t.Run("fresh missing refresh credential permanently blocks the account", func(t *testing.T) { + staleAccount := expiredGrokOAuthAccountForCredentialTest(714) + staleAccount.Schedulable = true + freshAccount := *staleAccount + freshAccount.Credentials = shallowCopyMap(staleAccount.Credentials) + delete(freshAccount.Credentials, "refresh_token") + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{staleAccount.ID: &freshAccount} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(nil)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, staleAccount) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonMissing, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Zero(t, baseRepo.setTempUnschedCalls) + require.Equal(t, StatusError, freshAccount.Status) + require.False(t, freshAccount.Schedulable) + require.Equal(t, []string{GrokTokenCacheKey(staleAccount)}, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(staleAccount)) + }) + + t.Run("refresh added after locked structural failure wins conditional mutation", func(t *testing.T) { + staleAccount := expiredGrokOAuthAccountForCredentialTest(717) + freshAccount := *staleAccount + freshAccount.Credentials = shallowCopyMap(staleAccount.Credentials) + delete(freshAccount.Credentials, "refresh_token") + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{staleAccount.ID: &freshAccount} + repo.beforeConditionalState = func() { + repaired := freshAccount + repaired.Credentials = shallowCopyMap(freshAccount.Credentials) + repaired.Credentials["refresh_token"] = "repaired-refresh-token" + repaired.Credentials["expires_at"] = time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + repo.accountsByID[staleAccount.ID] = &repaired + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(nil)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, staleAccount) + + require.NoError(t, err) + require.Equal(t, "expired-access-token", token) + require.Equal(t, "oauth", kind) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(staleAccount)) + }) + + t.Run("expiry-only repair wins full credential fingerprint CAS", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(718) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + repo.beforeConditionalState = func() { + repaired := *account + repaired.Credentials = shallowCopyMap(account.Credentials) + repaired.Credentials["expires_at"] = time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + repo.accountsByID[account.ID] = &repaired + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + + require.NoError(t, err) + require.Equal(t, "expired-access-token", token) + require.Equal(t, "oauth", kind) + require.Zero(t, repo.setErrorCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("generic token endpoint 403 stops as shared provider failure", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(708) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "token refresh failed: status 403, body: forbidden"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonProviderDown, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("account proxy generic 403 remains bounded account transient", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(711) + proxyID := int64(43) + account.ProxyID = &proxyID + account.Proxy = &Proxy{} + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "token refresh failed: status 403, body: forbidden"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonRefreshTransient, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Equal(t, 1, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("proxy repository read failure stops without account mutation", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(709) + proxyID := int64(41) + account.ProxyID = &proxyID + account.Proxy = &Proxy{} + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + oauthSvc := NewGrokOAuthService(&grokCredentialProxyRepoStub{err: errors.New("database temporarily unavailable")}, &grokOAuthClientStub{}) + defer oauthSvc.Stop() + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(oauthSvc)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonProviderDown, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("structurally missing configured proxy permanently blocks only that account", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(710) + account.Status = StatusActive + account.Schedulable = true + proxyID := int64(42) + account.ProxyID = &proxyID + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true} + oauthSvc := NewGrokOAuthService(&grokCredentialProxyRepoStub{err: ErrProxyNotFound}, &grokOAuthClientStub{}) + defer oauthSvc.Stop() + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), NewGrokTokenRefresher(oauthSvc)) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeAccount, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonProxyInvalid, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Equal(t, StatusError, account.Status) + require.False(t, account.Schedulable) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) +} + +func TestGetRequestCredentialRuntimeBlockWinsBeforeWarmTokenCache(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(716) + account.Credentials["access_token"] = "valid-access" + account.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{token: "valid-access"} + provider := NewGrokTokenProvider(repo, cache) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + svc.BlockAccountScheduling(account, time.Now().Add(time.Minute), "independent") + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GrokCredentialReasonAccountChanged, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, cache.getCalls) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) +} + +func TestGetRequestCredentialWarmCachedAccessWithMissingConfiguredProxyPermanentlyFailsOver(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(715) + account.Credentials["access_token"] = "valid-access" + account.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + proxyID := int64(44) + account.ProxyID = &proxyID + account.Proxy = nil + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialPersistingRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: true, token: "valid-access"} + refresher := &grokCredentialCountingRefresher{} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), refresher) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GrokCredentialReasonProxyInvalid, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, refresher.refreshCalls) + require.Equal(t, 1, baseRepo.setErrorCalls) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialCancellationAndBudgetDoNotMutateAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + account := expiredGrokOAuthAccountForCredentialTest(704) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + provider := NewGrokTokenProvider(repo, nil) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + + t.Run("parent cancellation is returned directly", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(ctx, c, account) + require.ErrorIs(t, err, context.Canceled) + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr)) + }) + + t.Run("request credential budget stops safely", func(t *testing.T) { + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Set(grokCredentialFailoverDeadlineKey, time.Now().Add(-time.Second)) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeRequest, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonFailoverTimeout, failoverErr.Reason) + require.False(t, failoverErr.ShouldRetryNextAccount()) + }) + + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialStateMutationFailureStopsAndKeepsRuntimeBlock(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + refreshErr error + configure func(*tokenRefreshAccountRepo, *grokTokenCacheForProviderTest) + wantSetError int + wantSetTemp int + wantCacheDelete int + }{ + { + name: "permanent state persistence", + refreshErr: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant"), + configure: func(repo *tokenRefreshAccountRepo, _ *grokTokenCacheForProviderTest) { + repo.setErrorErr = errors.New("database write failed") + }, + wantSetError: 1, + }, + { + name: "transient state persistence", + refreshErr: errors.New("temporary refresh transport failure"), + configure: func(repo *tokenRefreshAccountRepo, _ *grokTokenCacheForProviderTest) { + repo.setTempUnschedErr = errors.New("database write failed") + }, + wantSetTemp: 1, + }, + { + name: "permanent token cache invalidation", + refreshErr: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant"), + configure: func(_ *tokenRefreshAccountRepo, cache *grokTokenCacheForProviderTest) { + cache.deleteErr = errors.New("cache delete failed") + }, + wantSetError: 1, + wantCacheDelete: 1, + }, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(740 + index)) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + tt.configure(repo, cache) + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{err: tt.refreshErr}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonStateUpdate, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Equal(t, tt.wantSetError, repo.setErrorCalls) + require.Equal(t, tt.wantSetTemp, repo.setTempUnschedCalls) + require.Len(t, cache.deletedKeys, tt.wantCacheDelete) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "failed mutation must retain the immediate local block") + }) + } +} + +func TestGrokCredentialMutationBoundariesHonorParentCancellation(t *testing.T) { + t.Run("blocked SetError cancellation prevents cache and runtime mutation", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(730) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialBlockingRepo{ + tokenRefreshAccountRepo: baseRepo, + setErrorStarted: make(chan struct{}), + setTempStarted: make(chan struct{}), + } + cache := &grokTokenCacheForProviderTest{} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, cache)} + ctx, cancel := context.WithCancel(context.Background()) + result := make(chan error, 1) + go func() { + _, err := svc.applyGrokCredentialAccountFailure(ctx, account, grokCredentialFailureClass{ + reason: GrokCredentialReasonRevoked, permanent: true, + }) + result <- err + }() + <-repo.setErrorStarted + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "runtime block must precede persistent SetError") + cancel() + + require.ErrorIs(t, <-result, context.Canceled) + require.Zero(t, baseRepo.setErrorCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("blocked temporary unschedule cancellation prevents runtime mutation", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(731) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialBlockingRepo{ + tokenRefreshAccountRepo: baseRepo, + setErrorStarted: make(chan struct{}), + setTempStarted: make(chan struct{}), + } + svc := &OpenAIGatewayService{accountRepo: repo} + ctx, cancel := context.WithCancel(context.Background()) + result := make(chan error, 1) + go func() { + _, err := svc.applyGrokCredentialAccountFailure(ctx, account, grokCredentialFailureClass{ + reason: GrokCredentialReasonRefreshTransient, transient: true, + }) + result <- err + }() + <-repo.setTempStarted + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "runtime block must precede temporary unscheduling") + cancel() + + require.ErrorIs(t, <-result, context.Canceled) + require.Zero(t, baseRepo.setTempUnschedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("post-commit cancellation finishes cache cleanup and retains quarantine", func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(732) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokCredentialBlockingCache{deleteStarted: make(chan struct{}), releaseDelete: make(chan struct{})} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, cache)} + ctx, cancel := context.WithCancel(context.Background()) + result := make(chan error, 1) + go func() { + _, err := svc.applyGrokCredentialAccountFailure(ctx, account, grokCredentialFailureClass{ + reason: GrokCredentialReasonRevoked, permanent: true, + }) + result <- err + }() + <-cache.deleteStarted + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "runtime block must precede cache invalidation") + cancel() + close(cache.releaseDelete) + + require.ErrorIs(t, <-result, context.Canceled) + require.Equal(t, 1, repo.setErrorCalls) + require.True(t, cache.wasDeleted()) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) +} + +func TestGrokCredentialMutationLockWaitHonorsCredentialBudget(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(735) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, &grokTokenCacheForProviderTest{})} + mutationLock := svc.grokCredentialMutationLock(account.ID) + require.NoError(t, mutationLock.Lock(context.Background())) + defer mutationLock.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + + startedAt := time.Now() + token, err := svc.applyGrokCredentialAccountFailure(ctx, account, grokCredentialFailureClass{ + reason: GrokCredentialReasonRevoked, permanent: true, + }) + + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Empty(t, token) + require.Less(t, time.Since(startedAt), 500*time.Millisecond) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialBudgetBoundsBlockedConditionalMutation(t *testing.T) { + gin.SetMode(gin.TestMode) + account := expiredGrokOAuthAccountForCredentialTest(736) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialBlockingRepo{ + tokenRefreshAccountRepo: baseRepo, + setErrorStarted: make(chan struct{}), + setTempStarted: make(chan struct{}), + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Set(grokCredentialFailoverDeadlineKey, time.Now().Add(40*time.Millisecond)) + + startedAt := time.Now() + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeRequest, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonFailoverTimeout, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Empty(t, token) + require.Empty(t, kind) + require.Less(t, time.Since(startedAt), 500*time.Millisecond) + require.Zero(t, baseRepo.setErrorCalls) + require.Zero(t, baseRepo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialLockHeldTimeoutDoesNotQuarantineAccount(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + buildRepo func(*Account) AccountRepository + wantScope GatewayFailureScope + wantReason GatewayFailureReason + wantAction NextAccountAction + }{ + { + name: "authoritative row unchanged", + buildRepo: func(account *Account) AccountRepository { + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + return repo + }, + wantScope: GatewayFailureScopeAccount, + wantReason: GrokCredentialReasonAccountChanged, + wantAction: NextAccountRetry, + }, + { + name: "selected account was deleted", + buildRepo: func(account *Account) AccountRepository { + base := &tokenRefreshAccountRepo{} + base.accountsByID = map[int64]*Account{account.ID: account} + return &grokCredentialRereadFailureRepo{tokenRefreshAccountRepo: base} + }, + wantScope: GatewayFailureScopeAccount, + wantReason: GrokCredentialReasonAccountChanged, + wantAction: NextAccountRetry, + }, + { + name: "shared account store unavailable", + buildRepo: func(account *Account) AccountRepository { + base := &tokenRefreshAccountRepo{} + base.accountsByID = map[int64]*Account{account.ID: account} + return &grokCredentialRereadFailureRepo{tokenRefreshAccountRepo: base, err: errors.New("database unavailable")} + }, + wantScope: GatewayFailureScopeProvider, + wantReason: GrokCredentialReasonProviderDown, + wantAction: NextAccountStop, + }, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(7400 + index)) + repo := tt.buildRepo(account) + cache := &grokTokenCacheForProviderTest{lockResult: false} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + startedAt := time.Now() + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, tt.wantScope, failoverErr.Scope) + require.Equal(t, tt.wantReason, failoverErr.Reason) + require.Equal(t, tt.wantAction, failoverErr.NextAccountAction) + require.Less(t, time.Since(startedAt), 3*time.Second) + switch countingRepo := repo.(type) { + case *tokenRefreshAccountRepo: + require.Zero(t, countingRepo.setErrorCalls) + require.Zero(t, countingRepo.setTempUnschedCalls) + case *grokCredentialRereadFailureRepo: + require.Zero(t, countingRepo.tokenRefreshAccountRepo.setErrorCalls) + require.Zero(t, countingRepo.tokenRefreshAccountRepo.setTempUnschedCalls) + } + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } +} + +func TestGrokCredentialMutationCancellationAmbiguityConfirmsDurableCommit(t *testing.T) { + tests := []struct { + name string + class grokCredentialFailureClass + committed func(*Account) bool + }{ + { + name: "permanent quarantine", + class: grokCredentialFailureClass{reason: GrokCredentialReasonRevoked, permanent: true}, + committed: func(account *Account) bool { + return account.Status == StatusError && !account.Schedulable && account.ErrorMessage == string(GrokCredentialReasonRevoked) + }, + }, + { + name: "temporary quarantine", + class: grokCredentialFailureClass{reason: GrokCredentialReasonRefreshTransient, transient: true}, + committed: func(account *Account) bool { + return account.TempUnschedulableUntil != nil && account.TempUnschedulableReason == string(GrokCredentialReasonRefreshTransient) + }, + }, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(737 + index)) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialCommitThenCancelRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, cache)} + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + + token, err := svc.applyGrokCredentialAccountFailure(ctx, account, tt.class) + + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Empty(t, token) + require.True(t, tt.committed(account), "the detached confirmation must recognize the durable mutation") + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "a confirmed durable quarantine must retain its runtime block") + if tt.class.permanent { + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + } else { + require.Empty(t, cache.deletedKeys) + } + }) + } +} + +func TestGrokCredentialInnerStateDeadlineAmbiguityConfirmsDurableCommit(t *testing.T) { + tests := []struct { + name string + class grokCredentialFailureClass + }{ + {name: "permanent quarantine", class: grokCredentialFailureClass{reason: GrokCredentialReasonRevoked, permanent: true}}, + {name: "temporary quarantine", class: grokCredentialFailureClass{reason: GrokCredentialReasonRefreshTransient, transient: true}}, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(7500 + index)) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialCommitThenCancelRepo{ + tokenRefreshAccountRepo: baseRepo, + returnErr: context.DeadlineExceeded, + } + cache := &grokTokenCacheForProviderTest{} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, cache)} + + token, err := svc.applyGrokCredentialAccountFailure(context.Background(), account, tt.class) + + require.NoError(t, err, "the detached readback must resolve the inner timeout's commit ambiguity") + require.Empty(t, token) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + if tt.class.permanent { + require.Equal(t, StatusError, account.Status) + require.False(t, account.Schedulable) + require.Equal(t, []string{GrokTokenCacheKey(account)}, cache.deletedKeys) + } else { + require.NotNil(t, account.TempUnschedulableUntil) + require.Equal(t, string(GrokCredentialReasonRefreshTransient), account.TempUnschedulableReason) + require.Empty(t, cache.deletedKeys) + } + }) + } +} + +func TestGrokCredentialUnconfirmedInnerStateDeadlineStopsAndRetainsSafetyBlock(t *testing.T) { + tests := []struct { + name string + class grokCredentialFailureClass + }{ + {name: "permanent quarantine", class: grokCredentialFailureClass{reason: GrokCredentialReasonRevoked, permanent: true}}, + {name: "temporary quarantine", class: grokCredentialFailureClass{reason: GrokCredentialReasonRefreshTransient, transient: true}}, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(7600 + index)) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialUncommittedDeadlineRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, cache)} + + token, err := svc.applyGrokCredentialAccountFailure(context.Background(), account, tt.class) + + require.ErrorIs(t, err, errGrokCredentialStateUpdateFailed) + require.Empty(t, token) + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), "an unknown commit outcome must retain the local safety block") + require.Equal(t, StatusActive, account.Status) + require.True(t, account.Schedulable) + require.Nil(t, account.TempUnschedulableUntil) + require.Empty(t, cache.deletedKeys) + }) + } +} + +func TestGrokCredentialRuntimeRollbackOwnership(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(734) + t.Run("later extending block survives", func(t *testing.T) { + svc := &OpenAIGatewayService{} + until := time.Now().Add(time.Minute) + rollbackFirst := svc.blockGrokCredentialRuntime(account, until, "first") + + secondInstalled := make(chan struct{}) + go func() { + svc.BlockAccountScheduling(account, until.Add(time.Minute), "independent") + close(secondInstalled) + }() + <-secondInstalled + rollbackFirst() + + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account), + "rollback owned by the first invocation must not remove a later extending block") + }) + + t.Run("independent shorter block steals rollback ownership", func(t *testing.T) { + svc := &OpenAIGatewayService{} + until := time.Now().Add(2 * time.Minute) + rollbackFirst := svc.blockGrokCredentialRuntime(account, until, "first") + svc.BlockAccountScheduling(account, until.Add(-time.Minute), "shorter-no-op") + + rollbackFirst() + + require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + + t.Run("serialized tentative rollbacks leave no block", func(t *testing.T) { + svc := &OpenAIGatewayService{} + for i := 0; i < 2; i++ { + mu := svc.grokCredentialMutationLock(account.ID) + require.NoError(t, mu.Lock(context.Background())) + rollback := svc.blockGrokCredentialRuntime(account, time.Now().Add(time.Minute), "tentative") + rollback() + mu.Unlock() + } + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) +} + +func TestGetRequestCredentialAPIKeyBypassesOAuthFailureMapping(t *testing.T) { + gin.SetMode(gin.TestMode) + account := &Account{ + ID: 705, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "api_key": "third-party-key", + "base_url": "https://grok.example.test/v1", + }, + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + svc := &OpenAIGatewayService{} + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + require.NoError(t, err) + require.Equal(t, "third-party-key", token) + require.Equal(t, "apikey", kind) + _, hasEvents := c.Get(OpsUpstreamErrorsKey) + require.False(t, hasEvents) +} + +func TestPermanentCredentialFailureDoesNotDisableConcurrentlyRefreshedAccount(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(707) + latest := *account + latest.Credentials = shallowCopyMap(account.Credentials) + latest.Credentials["access_token"] = "fresh-access-token" + latest.Credentials["refresh_token"] = "rotated-refresh-token" + latest.Credentials["expires_at"] = time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + latest.Credentials["_token_version"] = time.Now().UnixMilli() + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: &latest} + cache := &grokTokenCacheForProviderTest{} + svc := &OpenAIGatewayService{ + accountRepo: repo, + grokTokenProvider: NewGrokTokenProvider(repo, cache), + } + + _, mutationErr := svc.applyGrokCredentialAccountFailure(context.Background(), account, grokCredentialFailureClass{ + scope: GatewayFailureScopeAccount, + reason: GrokCredentialReasonRevoked, + action: NextAccountRetry, + permanent: true, + }) + + require.NoError(t, mutationErr) + require.Zero(t, repo.setErrorCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestCredentialFailureConditionalMutationLosesToConcurrentRefresh(t *testing.T) { + for index, tt := range []struct { + name string + refreshErr error + }{ + {name: "permanent", refreshErr: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant")}, + {name: "transient", refreshErr: errors.New("temporary refresh transport failure")}, + } { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(770 + index)) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + repo.beforeConditionalState = func() { + fresh := *account + fresh.Credentials = shallowCopyMap(account.Credentials) + fresh.Credentials["access_token"] = "refresh-won-token" + fresh.Credentials["refresh_token"] = "refresh-won-refresh" + fresh.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + fresh.Credentials["_token_version"] = time.Now().UnixMilli() + repo.accountsByID[account.ID] = &fresh + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{err: tt.refreshErr}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + + require.NoError(t, err) + require.Equal(t, "refresh-won-token", token) + require.Equal(t, "oauth", kind) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } +} + +func TestCredentialFailureConditionalMutationLosesToConcurrentProxyRepair(t *testing.T) { + for index, tt := range []struct { + name string + refreshErr error + }{ + {name: "permanent", refreshErr: infraerrors.New(http.StatusBadGateway, "GROK_OAUTH_TOKEN_REFRESH_FAILED", "invalid_grant")}, + {name: "transient", refreshErr: errors.New("temporary refresh transport failure")}, + } { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(780 + index)) + oldProxyID := int64(10) + account.ProxyID = &oldProxyID + account.Proxy = &Proxy{} + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + repo.beforeConditionalState = func() { + fresh := *account + fresh.Credentials = shallowCopyMap(account.Credentials) + repairedProxyID := int64(11) + fresh.ProxyID = &repairedProxyID + repo.accountsByID[account.ID] = &fresh + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{err: tt.refreshErr}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GrokCredentialReasonAccountChanged, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } +} + +func TestCredentialFailureConditionalMutationLosesToSameIDProxyRestoration(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(790) + proxyID := int64(10) + account.ProxyID = &proxyID + account.Proxy = nil + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + repo.beforeConditionalState = func() { + account.Proxy = &Proxy{ID: proxyID} + } + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GrokCredentialReasonAccountChanged, failoverErr.Reason) + require.Equal(t, NextAccountRetry, failoverErr.NextAccountAction) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestCredentialFailureConditionalMutationLosesToConcurrentUnschedulableState(t *testing.T) { + future := time.Now().Add(time.Hour) + states := []struct { + name string + mutate func(*Account) + }{ + {name: "admin schedulable false", mutate: func(account *Account) { account.Schedulable = false }}, + {name: "temporary cooldown", mutate: func(account *Account) { account.TempUnschedulableUntil = &future }}, + {name: "rate limit cooldown", mutate: func(account *Account) { account.RateLimitResetAt = &future }}, + {name: "overload cooldown", mutate: func(account *Account) { account.OverloadUntil = &future }}, + } + classes := []struct { + name string + class grokCredentialFailureClass + }{ + {name: "permanent", class: grokCredentialFailureClass{reason: GrokCredentialReasonRevoked, permanent: true}}, + {name: "transient", class: grokCredentialFailureClass{reason: GrokCredentialReasonRefreshTransient, transient: true}}, + } + + for classIndex, classCase := range classes { + for stateIndex, stateCase := range states { + t.Run(classCase.name+"/"+stateCase.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(791 + classIndex*10 + stateIndex)) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + repo.beforeConditionalState = func() { stateCase.mutate(account) } + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, &grokTokenCacheForProviderTest{})} + + token, err := svc.applyGrokCredentialAccountFailure(context.Background(), account, classCase.class) + + require.ErrorIs(t, err, errOAuthRefreshAccountStateChanged) + require.Empty(t, token) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } + } +} + +func TestCredentialFailureCASMissDoesNotRecoverIneligibleLatestCredential(t *testing.T) { + future := time.Now().Add(time.Hour) + states := []struct { + name string + mutate func(*OpenAIGatewayService, *Account) + wantRuntimeBlocked bool + }{ + {name: "disabled", mutate: func(_ *OpenAIGatewayService, account *Account) { account.Status = StatusDisabled }}, + {name: "not schedulable", mutate: func(_ *OpenAIGatewayService, account *Account) { account.Schedulable = false }}, + {name: "temporarily unschedulable", mutate: func(_ *OpenAIGatewayService, account *Account) { account.TempUnschedulableUntil = &future }}, + {name: "rate limited", mutate: func(_ *OpenAIGatewayService, account *Account) { account.RateLimitResetAt = &future }}, + {name: "overloaded", mutate: func(_ *OpenAIGatewayService, account *Account) { account.OverloadUntil = &future }}, + { + name: "independently runtime blocked", + mutate: func(svc *OpenAIGatewayService, account *Account) { + svc.BlockAccountScheduling(account, time.Now().Add(24*time.Hour), "independent") + }, + wantRuntimeBlocked: true, + }, + } + classes := []struct { + name string + class grokCredentialFailureClass + }{ + {name: "permanent", class: grokCredentialFailureClass{reason: GrokCredentialReasonRevoked, permanent: true}}, + {name: "transient", class: grokCredentialFailureClass{reason: GrokCredentialReasonRefreshTransient, transient: true}}, + } + + for classIndex, classCase := range classes { + for stateIndex, stateCase := range states { + t.Run(classCase.name+"/"+stateCase.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(800 + classIndex*20 + stateIndex)) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: NewGrokTokenProvider(repo, &grokTokenCacheForProviderTest{})} + repo.beforeConditionalState = func() { + latest := *account + latest.Credentials = shallowCopyMap(account.Credentials) + latest.Credentials["access_token"] = "fresh-but-ineligible-token" + latest.Credentials["refresh_token"] = "fresh-but-ineligible-refresh" + latest.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + latest.Credentials["_token_version"] = time.Now().UnixMilli() + stateCase.mutate(svc, &latest) + repo.accountsByID[account.ID] = &latest + } + + token, err := svc.applyGrokCredentialAccountFailure(context.Background(), account, classCase.class) + + require.ErrorIs(t, err, errOAuthRefreshAccountStateChanged) + require.Empty(t, token) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Equal(t, stateCase.wantRuntimeBlocked, svc.isOpenAIAccountRuntimeBlocked(account)) + }) + } + } +} + +func TestGetRequestCredentialSharedCredentialPersistenceFailureStopsWithoutAccountMutation(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(782) + repo := &tokenRefreshAccountRepo{updateErr: errors.New("database unavailable")} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{credentials: map[string]any{ + "access_token": "new-access-token", + "refresh_token": "new-refresh-token", + "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + }}) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + _, _, err := svc.getRequestCredential(context.Background(), c, account) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, GatewayFailureScopeProvider, failoverErr.Scope) + require.Equal(t, GrokCredentialReasonProviderDown, failoverErr.Reason) + require.Equal(t, NextAccountStop, failoverErr.NextAccountAction) + require.Equal(t, 1, repo.updateCredentialsCalls) + require.Zero(t, repo.setErrorCalls) + require.Zero(t, repo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) +} + +func TestGetRequestCredentialRecoversConcurrentRefreshWithoutFailover(t *testing.T) { + gin.SetMode(gin.TestMode) + account := expiredGrokOAuthAccountForCredentialTest(733) + latest := *account + latest.Credentials = shallowCopyMap(account.Credentials) + latest.Credentials["access_token"] = "fresh-concurrent-access" + latest.Credentials["refresh_token"] = "fresh-concurrent-refresh" + latest.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + latest.Credentials["_token_version"] = time.Now().UnixMilli() + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialSequencedRepo{tokenRefreshAccountRepo: baseRepo, latest: &latest} + cache := &grokTokenCacheForProviderTest{lockResult: true} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ + err: infraerrors.New(http.StatusForbidden, "GROK_OAUTH_ENTITLEMENT_DENIED", "access_denied"), + }) + svc := &OpenAIGatewayService{accountRepo: repo, grokTokenProvider: provider} + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + + token, kind, err := svc.getRequestCredential(context.Background(), c, account) + + require.NoError(t, err) + require.Equal(t, "fresh-concurrent-access", token) + require.Equal(t, "oauth", kind) + require.Zero(t, baseRepo.setErrorCalls) + require.Zero(t, baseRepo.setTempUnschedCalls) + require.Empty(t, cache.deletedKeys) + require.False(t, svc.isOpenAIAccountRuntimeBlocked(account)) + _, hasEvents := c.Get(OpsUpstreamErrorsKey) + require.False(t, hasEvents) +} + +func expiredGrokOAuthAccountForCredentialTest(id int64) *Account { + return &Account{ + ID: id, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "access_token": "expired-access-token", + "refresh_token": "refresh-token", + "expires_at": time.Now().Add(-time.Minute).UTC().Format(time.RFC3339), + "base_url": xai.DefaultCLIBaseURL, + }, + } +} diff --git a/backend/internal/service/grok_media.go b/backend/internal/service/grok_media.go index 100d720659..5cc8e2d05e 100644 --- a/backend/internal/service/grok_media.go +++ b/backend/internal/service/grok_media.go @@ -304,7 +304,7 @@ func (s *OpenAIGatewayService) ForwardGrokMedia( return nil, fmt.Errorf("account platform %s is not supported for grok media", account.Platform) } - token, _, err := s.GetAccessToken(ctx, account) + token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, err } @@ -339,7 +339,9 @@ func (s *OpenAIGatewayService) ForwardGrokMedia( } upstreamReq.Header.Set("Authorization", "Bearer "+token) upstreamReq.Header.Set("Accept", "application/json") - applyGrokCLIHeaders(upstreamReq.Header) + if account.IsGrokOAuth() { + applyGrokCLIHeaders(upstreamReq.Header) + } if endpoint.RequiresRequestBody() { contentType = strings.TrimSpace(contentType) if contentType == "" { @@ -635,6 +637,7 @@ func (s *OpenAIGatewayService) handleGrokMediaErrorResponse( return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: body, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } diff --git a/backend/internal/service/grok_oauth_service.go b/backend/internal/service/grok_oauth_service.go index 136e5e3b21..49e77bcfd7 100644 --- a/backend/internal/service/grok_oauth_service.go +++ b/backend/internal/service/grok_oauth_service.go @@ -3,6 +3,9 @@ package service import ( "context" "crypto/subtle" + "encoding/base64" + "encoding/json" + "errors" "net/http" "strings" "time" @@ -314,10 +317,13 @@ func (s *GrokOAuthService) proxyURL(ctx context.Context, proxyID *int64) (string } proxy, err := s.proxyRepo.GetByID(ctx, *proxyID) if err != nil { - return "", infraerrors.Newf(http.StatusBadRequest, "GROK_OAUTH_PROXY_NOT_FOUND", "proxy not found: %v", err) + if errors.Is(err, ErrProxyNotFound) { + return "", infraerrors.New(http.StatusBadRequest, "GROK_OAUTH_PROXY_NOT_FOUND", "configured proxy was not found") + } + return "", infraerrors.New(http.StatusServiceUnavailable, "GROK_OAUTH_PROXY_LOOKUP_FAILED", "proxy lookup is temporarily unavailable") } if proxy == nil { - return "", nil + return "", infraerrors.New(http.StatusBadRequest, "GROK_OAUTH_PROXY_NOT_FOUND", "configured proxy was not found") } return proxy.URL(), nil } diff --git a/backend/internal/service/grok_quota_service.go b/backend/internal/service/grok_quota_service.go index 2219a75c15..ef8e3e4c03 100644 --- a/backend/internal/service/grok_quota_service.go +++ b/backend/internal/service/grok_quota_service.go @@ -149,7 +149,9 @@ func (s *GrokQuotaService) probeUsage(ctx context.Context, accountID int64) (*Gr req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") - applyGrokCLIHeaders(req.Header) + if account.IsGrokOAuth() { + applyGrokCLIHeaders(req.Header) + } resp, err := s.httpUpstream.Do(req, proxyURL, account.ID, maxInt(account.Concurrency, 1)) if err != nil { @@ -387,6 +389,7 @@ func (s *GrokQuotaService) prepareProbe(ctx context.Context, accountID int64) (* if err != nil { return nil, "", "", err } + proxyURL := s.resolveProxyURL(ctx, account) token, err := s.tokenProvider.GetAccessToken(ctx, account) if err != nil { @@ -396,7 +399,7 @@ func (s *GrokQuotaService) prepareProbe(ctx context.Context, accountID int64) (* return nil, "", "", infraerrors.New(http.StatusBadGateway, "GROK_QUOTA_TOKEN_UNAVAILABLE", "access token is empty") } - return account, token, s.resolveProxyURL(ctx, account), nil + return account, token, proxyURL, nil } func (s *GrokQuotaService) resolveProxyURL(ctx context.Context, account *Account) string { @@ -408,6 +411,7 @@ func (s *GrokQuotaService) resolveProxyURL(ctx context.Context, account *Account return account.Proxy.URL() case s != nil && s.proxyRepo != nil: if proxy, err := s.proxyRepo.GetByID(ctx, *account.ProxyID); err == nil && proxy != nil { + account.Proxy = proxy return proxy.URL() } } diff --git a/backend/internal/service/grok_quota_service_test.go b/backend/internal/service/grok_quota_service_test.go index ba9b6cbcb8..4e06fe156c 100644 --- a/backend/internal/service/grok_quota_service_test.go +++ b/backend/internal/service/grok_quota_service_test.go @@ -180,19 +180,26 @@ func (r *grokQuotaProxyRepo) GetByID(_ context.Context, id int64) (*Proxy, error return r.proxies[id], nil } +func healthyGrokQuotaOAuthAccount(id int64) *Account { + return &Account{ + ID: id, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "access_token": "access-token", + "refresh_token": "refresh-token", + "expires_at": time.Now().Add(2 * grokTokenRefreshSkew).UTC().Format(time.RFC3339), + }, + } +} + func TestGrokQuotaServiceProbeUsageStoresHeaders(t *testing.T) { t.Parallel() - account := &Account{ - ID: 42, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(42) repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{42: account}, @@ -236,19 +243,10 @@ func TestGrokQuotaServiceProbeUsageStoresHeaders(t *testing.T) { func TestGrokQuotaServiceProbeUsageIgnoresAccountGrokMapping(t *testing.T) { t.Parallel() - account := &Account{ - ID: 47, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "model_mapping": map[string]any{ - "grok": "grok-composer", - "grok-composer": "grok-composer-2.5-fast", - }, - }, + account := healthyGrokQuotaOAuthAccount(47) + account.Credentials["model_mapping"] = map[string]any{ + "grok": "grok-composer", + "grok-composer": "grok-composer-2.5-fast", } repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ @@ -272,16 +270,7 @@ func TestGrokQuotaServiceProbeUsageIgnoresAccountGrokMapping(t *testing.T) { func TestGrokQuotaServiceProbeUsageReportsProbeModelOnUpstreamError(t *testing.T) { t.Parallel() - account := &Account{ - ID: 48, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(48) repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{48: account}, @@ -352,17 +341,8 @@ func TestGrokQuotaServiceProbeUsageLoadsProxyWhenAccountEdgeMissing(t *testing.T t.Parallel() proxyID := int64(7) - account := &Account{ - ID: 46, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - ProxyID: &proxyID, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(46) + account.ProxyID = &proxyID repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{46: account}, @@ -394,16 +374,7 @@ func TestGrokQuotaServiceProbeUsageLoadsProxyWhenAccountEdgeMissing(t *testing.T func TestGrokQuotaServiceProbeUsageStoresNoHeadersState(t *testing.T) { t.Parallel() - account := &Account{ - ID: 45, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(45) repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{45: account}, @@ -435,15 +406,7 @@ func TestGrokQuotaServiceProbeUsageStoresNoHeadersState(t *testing.T) { func TestGrokQuotaServiceProbeUsageReturnsRateLimitedSnapshot(t *testing.T) { t.Parallel() - account := &Account{ - ID: 43, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(43) repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{43: account}, diff --git a/backend/internal/service/grok_token_provider.go b/backend/internal/service/grok_token_provider.go index f19ee42b88..c4dc4d4b12 100644 --- a/backend/internal/service/grok_token_provider.go +++ b/backend/internal/service/grok_token_provider.go @@ -3,19 +3,26 @@ package service import ( "context" "errors" - "log/slog" + "fmt" "strconv" "strings" "time" - - "github.com/Wei-Shaw/sub2api/internal/util/logredact" ) const ( - grokTokenCacheSkew = 5 * time.Minute - grokRequestRefreshTimeout = 8 * time.Second - grokTokenProviderLogComponent = "grok_token_provider" - grokTempUnschedulableErrorCode = "token_refresh_failed" + grokTokenCacheSkew = 5 * time.Minute + grokRequestRefreshTimeout = 8 * time.Second + grokRefreshLockWaitTimeout = 2 * time.Second + grokRefreshLockPollInterval = 25 * time.Millisecond +) + +var ( + errGrokOAuthRefreshNotConfigured = errors.New("grok oauth refresh is not configured") + errGrokOAuthRefreshTokenMissing = errors.New("grok oauth refresh token is missing") + errGrokOAuthAccessTokenMissing = errors.New("grok oauth access token is missing") + errGrokOAuthAccessTokenExpired = errors.New("grok oauth access token is expired") + errGrokOAuthConfiguredProxyMiss = errors.New("grok oauth configured proxy is missing") + errGrokOAuthRefreshLockTimeout = errors.New("grok oauth refresh lock wait timed out") ) type GrokTokenCache = GeminiTokenCache @@ -36,7 +43,7 @@ func NewGrokTokenProvider( return &GrokTokenProvider{ accountRepo: accountRepo, tokenCache: tokenCache, - refreshPolicy: AntigravityProviderRefreshPolicy(), + refreshPolicy: GrokProviderRefreshPolicy(), } } @@ -60,32 +67,57 @@ func (p *GrokTokenProvider) GetAccessToken(ctx context.Context, account *Account if account.Platform != PlatformGrok || account.Type != AccountTypeOAuth { return "", errors.New("not a grok oauth account") } - - cacheKey := GrokTokenCacheKey(account) - if p.tokenCache != nil { - if token, err := p.tokenCache.GetAccessToken(ctx, cacheKey); err == nil && strings.TrimSpace(token) != "" { - return token, nil - } + selectedProxyID := cloneGrokProxyID(account.ProxyID) + if eligibilityErr := grokOAuthRequestAccountEligibilityError(account); eligibilityErr != nil { + return "", withGrokCredentialFailureSnapshot(eligibilityErr, account) } expiresAt := account.GetCredentialAsTime("expires_at") - needsRefresh := expiresAt == nil || time.Until(*expiresAt) <= grokTokenRefreshSkew - if needsRefresh && strings.TrimSpace(account.GetGrokRefreshToken()) == "" { - if expiresAt == nil || !time.Now().Before(*expiresAt) { - return "", errors.New("grok access_token expired and refresh_token is missing") - } - needsRefresh = false + accountAccessToken := strings.TrimSpace(account.GetGrokAccessToken()) + if accountAccessToken == "" { + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenMissing, account) } - if needsRefresh && p.refreshAPI != nil && p.executor != nil { + if strings.TrimSpace(account.GetGrokRefreshToken()) == "" { + return "", withGrokCredentialFailureSnapshot(errGrokOAuthRefreshTokenMissing, account) + } + cacheKey := GrokTokenCacheKey(account) + if p.tokenCache != nil { + if token, err := p.tokenCache.GetAccessToken(ctx, cacheKey); err == nil { + cachedToken := strings.TrimSpace(token) + if cachedToken != "" && accountAccessToken != "" && cachedToken == accountAccessToken && + expiresAt != nil && time.Until(*expiresAt) > grokTokenRefreshSkew { + return cachedToken, nil + } + } + } + + needsRefresh := expiresAt == nil || time.Until(*expiresAt) <= grokTokenRefreshSkew + if needsRefresh { + if p.refreshAPI == nil || p.executor == nil { + return "", errGrokOAuthRefreshNotConfigured + } refreshCtx, cancel := context.WithTimeout(ctx, grokRequestRefreshTimeout) defer cancel() - result, err := p.refreshAPI.RefreshIfNeeded(refreshCtx, account, p.executor, grokTokenRefreshSkew) + result, err := p.refreshAPI.RefreshIfNeeded(withOAuthRefreshRequestPath(refreshCtx), account, p.executor, grokTokenRefreshSkew) if err != nil { - p.markTempUnschedulable(account, err) if p.refreshPolicy.OnRefreshError == ProviderRefreshErrorReturn { return "", err } - } else if !result.LockHeld && result.Account != nil { + } else if result != nil && result.LockHeld { + if p.refreshPolicy.OnLockHeld == ProviderLockHeldWaitForCache { + token, waitErr := p.waitForRefreshedToken(refreshCtx, account, cacheKey) + return token, withGrokCredentialFailureSnapshot(waitErr, account) + } + if expiresAt == nil || !time.Now().Before(*expiresAt) { + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenExpired, account) + } + } else if result != nil && result.Account != nil { + if eligibilityErr := grokOAuthRequestAccountEligibilityError(result.Account); eligibilityErr != nil { + return "", withGrokCredentialFailureSnapshot(eligibilityErr, result.Account) + } + if !grokCredentialProxyIDsEqual(result.Account.ProxyID, selectedProxyID) { + return "", withGrokCredentialFailureSnapshot(errOAuthRefreshAccountStateChanged, result.Account) + } account = result.Account expiresAt = account.GetCredentialAsTime("expires_at") } @@ -93,15 +125,28 @@ func (p *GrokTokenProvider) GetAccessToken(ctx context.Context, account *Account accessToken := account.GetGrokAccessToken() if strings.TrimSpace(accessToken) == "" { - return "", errors.New("access_token not found in credentials") + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenMissing, account) + } + if expiresAt != nil && !time.Now().Before(*expiresAt) { + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenExpired, account) } if p.tokenCache != nil { latestAccount, isStale := CheckTokenVersion(ctx, account, p.accountRepo) if isStale && latestAccount != nil { + if eligibilityErr := grokOAuthRequestAccountEligibilityError(latestAccount); eligibilityErr != nil { + return "", withGrokCredentialFailureSnapshot(eligibilityErr, latestAccount) + } + if !grokCredentialProxyIDsEqual(latestAccount.ProxyID, selectedProxyID) { + return "", withGrokCredentialFailureSnapshot(errOAuthRefreshAccountStateChanged, latestAccount) + } accessToken = latestAccount.GetGrokAccessToken() if strings.TrimSpace(accessToken) == "" { - return "", errors.New("access_token not found after version check") + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenMissing, latestAccount) + } + latestExpiry := latestAccount.GetCredentialAsTime("expires_at") + if latestExpiry == nil || !time.Now().Before(*latestExpiry) { + return "", withGrokCredentialFailureSnapshot(errGrokOAuthAccessTokenExpired, latestAccount) } } else { ttl := 30 * time.Minute @@ -123,40 +168,105 @@ func (p *GrokTokenProvider) GetAccessToken(ctx context.Context, account *Account return accessToken, nil } -func (p *GrokTokenProvider) markTempUnschedulable(account *Account, refreshErr error) { - if p == nil || p.accountRepo == nil || account == nil { - return - } - now := time.Now() - until := now.Add(tokenRefreshTempUnschedDuration) - redactedErr := "unknown error" - if refreshErr != nil { - redactedErr = logredact.RedactText(refreshErr.Error()) - } - if isNonRetryableRefreshError(refreshErr) { - if err := p.accountRepo.SetError(context.Background(), account.ID, "grok token refresh failed (non-retryable): "+redactedErr); err != nil { - slog.Warn(grokTokenProviderLogComponent+".set_error_status_failed", "account_id", account.ID, "error", err) +func (p *GrokTokenProvider) waitForRefreshedToken(ctx context.Context, account *Account, cacheKey string) (string, error) { + waitCtx, cancel := context.WithTimeout(ctx, grokRefreshLockWaitTimeout) + defer cancel() + + initialToken := strings.TrimSpace(account.GetGrokAccessToken()) + initialVersion := account.GetCredentialAsInt64("_token_version") + selectedProxyID := cloneGrokProxyID(account.ProxyID) + sawAuthoritativeState := false + var lastAccountReadErr error + ticker := time.NewTicker(grokRefreshLockPollInterval) + defer ticker.Stop() + + for { + cachedToken := "" + if p.tokenCache != nil { + if token, err := p.tokenCache.GetAccessToken(waitCtx, cacheKey); err == nil { + cachedToken = strings.TrimSpace(token) + } } - return - } - reason := "grok token refresh failed on request path: " + redactedErr - bgCtx := context.Background() - if err := p.accountRepo.SetTempUnschedulable(bgCtx, account.ID, until, reason); err != nil { - slog.Warn(grokTokenProviderLogComponent+".set_temp_unschedulable_failed", "account_id", account.ID, "error", err) - return - } - if p.tempUnschedCache != nil { - state := &TempUnschedState{ - UntilUnix: until.Unix(), - TriggeredAtUnix: now.Unix(), - ErrorMessage: grokTempUnschedulableErrorCode + ": " + reason, + + if p.accountRepo != nil { + latest, err := p.accountRepo.GetByID(waitCtx, account.ID) + if err != nil { + lastAccountReadErr = err + } else if latest == nil { + return "", errOAuthRefreshAccountStateChanged + } else { + sawAuthoritativeState = true + if eligibilityErr := grokOAuthRequestAccountEligibilityError(latest); eligibilityErr != nil { + return "", withGrokCredentialFailureSnapshot(eligibilityErr, latest) + } + if !grokCredentialProxyIDsEqual(latest.ProxyID, selectedProxyID) { + return "", withGrokCredentialFailureSnapshot(errOAuthRefreshAccountStateChanged, latest) + } + token := strings.TrimSpace(latest.GetGrokAccessToken()) + version := latest.GetCredentialAsInt64("_token_version") + expiresAt := latest.GetCredentialAsTime("expires_at") + changed := token != initialToken || (version > 0 && version > initialVersion) + valid := expiresAt != nil && time.Now().Before(*expiresAt) + if token != "" && changed && valid { + // The versioned DB credential is authoritative. A stale cache must + // not hold the request on the old expired token; repair it best-effort. + if cachedToken != "" && cachedToken != token { + ttl := time.Until(*expiresAt) + if ttl > grokTokenCacheSkew { + ttl -= grokTokenCacheSkew + } + _ = p.tokenCache.SetAccessToken(waitCtx, cacheKey, token, ttl) + } + return token, nil + } + } } - if err := p.tempUnschedCache.SetTempUnsched(bgCtx, account.ID, state); err != nil { - slog.Warn(grokTokenProviderLogComponent+".temp_unsched_cache_set_failed", "account_id", account.ID, "error", err) + + select { + case <-waitCtx.Done(): + if ctx.Err() != nil { + return "", ctx.Err() + } + if !sawAuthoritativeState { + if lastAccountReadErr == nil { + lastAccountReadErr = waitCtx.Err() + } + return "", fmt.Errorf("%w: %v", errOAuthRefreshAccountRereadFailed, lastAccountReadErr) + } + // Another worker still owns the refresh and the authoritative row is + // unchanged. Do not quarantine the old credential: its refresh may + // commit immediately after this bounded wait. + return "", errOAuthRefreshAccountStateChanged + case <-ticker.C: } } } +func grokOAuthRequestAccountEligibilityError(account *Account) error { + if account == nil || !account.IsGrokOAuth() || !account.IsSchedulable() { + return errOAuthRefreshAccountStateChanged + } + if account.ProxyID != nil && account.Proxy == nil { + return errGrokOAuthConfiguredProxyMiss + } + return nil +} + +func cloneGrokProxyID(proxyID *int64) *int64 { + if proxyID == nil { + return nil + } + value := *proxyID + return &value +} + +func (p *GrokTokenProvider) InvalidateToken(ctx context.Context, account *Account) error { + if p == nil || p.tokenCache == nil || account == nil { + return nil + } + return p.tokenCache.DeleteAccessToken(ctx, GrokTokenCacheKey(account)) +} + func GrokTokenCacheKey(account *Account) string { if account == nil { return "grok:account:0" diff --git a/backend/internal/service/grok_token_provider_test.go b/backend/internal/service/grok_token_provider_test.go index 1f7e2d8e0e..7c68e55455 100644 --- a/backend/internal/service/grok_token_provider_test.go +++ b/backend/internal/service/grok_token_provider_test.go @@ -5,6 +5,7 @@ package service import ( "context" "errors" + "sync" "testing" "time" @@ -19,9 +20,33 @@ type grokTokenCacheForProviderTest struct { setTTL time.Duration lockResult bool releaseCalls int + deletedKeys []string + deleteErr error + getCalls int + mu sync.Mutex +} + +type grokCredentialRaceRepo struct { + *tokenRefreshAccountRepo + mu sync.RWMutex +} + +func (r *grokCredentialRaceRepo) GetByID(ctx context.Context, id int64) (*Account, error) { + r.mu.RLock() + defer r.mu.RUnlock() + return r.tokenRefreshAccountRepo.GetByID(ctx, id) +} + +func (r *grokCredentialRaceRepo) setAccount(account *Account) { + r.mu.Lock() + defer r.mu.Unlock() + r.accountsByID[account.ID] = account } func (c *grokTokenCacheForProviderTest) GetAccessToken(context.Context, string) (string, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.getCalls++ if c.token == "" { return "", errors.New("not cached") } @@ -29,14 +54,19 @@ func (c *grokTokenCacheForProviderTest) GetAccessToken(context.Context, string) } func (c *grokTokenCacheForProviderTest) SetAccessToken(_ context.Context, key string, token string, ttl time.Duration) error { + c.mu.Lock() + defer c.mu.Unlock() c.setKey = key c.setToken = token c.setTTL = ttl return nil } -func (c *grokTokenCacheForProviderTest) DeleteAccessToken(context.Context, string) error { - return nil +func (c *grokTokenCacheForProviderTest) DeleteAccessToken(_ context.Context, key string) error { + c.mu.Lock() + defer c.mu.Unlock() + c.deletedKeys = append(c.deletedKeys, key) + return c.deleteErr } func (c *grokTokenCacheForProviderTest) AcquireRefreshLock(context.Context, string, time.Duration) (bool, error) { @@ -53,9 +83,11 @@ func TestGrokTokenProviderRefreshesExpiredTokenOnRequestPath(t *testing.T) { expiredAt := time.Now().Add(-time.Minute).UTC().Format(time.RFC3339) account := &Account{ - ID: 54, - Platform: PlatformGrok, - Type: AccountTypeOAuth, + ID: 54, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, Credentials: map[string]any{ "access_token": "expired-access-token", "refresh_token": "refresh-token", @@ -95,9 +127,11 @@ func TestGrokTokenProviderRefreshesExpiredTokenOnRequestPath(t *testing.T) { func TestGrokTokenProviderRefreshFailureUnschedulesWithRedactedReason(t *testing.T) { expiredAt := time.Now().Add(-time.Minute).UTC().Format(time.RFC3339) account := &Account{ - ID: 55, - Platform: PlatformGrok, - Type: AccountTypeOAuth, + ID: 55, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, Credentials: map[string]any{ "access_token": "expired-access-token", "refresh_token": "refresh-token", @@ -108,24 +142,178 @@ func TestGrokTokenProviderRefreshFailureUnschedulesWithRedactedReason(t *testing repo := &tokenRefreshAccountRepo{} repo.accountsByID = map[int64]*Account{55: account} cache := &grokTokenCacheForProviderTest{lockResult: true} - tempCache := &tempUnschedCacheStub{} provider := NewGrokTokenProvider(repo, cache) provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{ err: errors.New("temporary refresh failure access_token=leaked-access refresh_token=leaked-refresh"), }) - provider.SetTempUnschedCache(tempCache) token, err := provider.GetAccessToken(context.Background(), account) require.Error(t, err) require.Empty(t, token) - require.Equal(t, 1, repo.setTempUnschedCalls) + require.Equal(t, 0, repo.setTempUnschedCalls) require.Equal(t, 0, repo.setErrorCalls) - require.Contains(t, repo.lastTempUnschedReason, "access_token=***") - require.Contains(t, repo.lastTempUnschedReason, "refresh_token=***") - require.NotContains(t, repo.lastTempUnschedReason, "leaked-access") - require.NotContains(t, repo.lastTempUnschedReason, "leaked-refresh") - require.Equal(t, 1, tempCache.setCalls) - require.NotNil(t, tempCache.lastState) - require.NotContains(t, tempCache.lastState.ErrorMessage, "leaked-access") - require.NotContains(t, tempCache.lastState.ErrorMessage, "leaked-refresh") +} + +func TestGrokTokenProviderLockHeldWaitsForRefreshedCacheAndNeverUsesExpiredToken(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(56) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialRaceRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: false, token: "expired-access-token"} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{}) + + go func() { + time.Sleep(40 * time.Millisecond) + refreshed := *account + refreshed.Credentials = shallowCopyMap(account.Credentials) + refreshed.Credentials["access_token"] = "refreshed-after-lock" + refreshed.Credentials["expires_at"] = time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + refreshed.Credentials["_token_version"] = time.Now().UnixMilli() + repo.setAccount(&refreshed) + cache.mu.Lock() + cache.token = "refreshed-after-lock" + cache.mu.Unlock() + }() + + startedAt := time.Now() + token, err := provider.GetAccessToken(context.Background(), account) + require.NoError(t, err) + require.Equal(t, "refreshed-after-lock", token) + require.NotEqual(t, "expired-access-token", token) + require.GreaterOrEqual(t, time.Since(startedAt), 25*time.Millisecond, + "expired account metadata must prevent returning the old cached token") +} + +func TestGrokTokenProviderLockHeldTimeoutDoesNotReturnExpiredToken(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(57) + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: account} + cache := &grokTokenCacheForProviderTest{lockResult: false} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{}) + ctx, cancel := context.WithTimeout(context.Background(), 80*time.Millisecond) + defer cancel() + + token, err := provider.GetAccessToken(ctx, account) + require.Error(t, err) + require.Empty(t, token) +} + +func TestGrokTokenProviderLockHeldRejectsChangedTokenWithoutExpiry(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(58) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialRaceRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: false, token: "expired-access-token"} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{}) + + go func() { + time.Sleep(30 * time.Millisecond) + refreshed := *account + refreshed.Credentials = shallowCopyMap(account.Credentials) + refreshed.Credentials["access_token"] = "changed-without-expiry" + delete(refreshed.Credentials, "expires_at") + refreshed.Credentials["_token_version"] = time.Now().UnixMilli() + repo.setAccount(&refreshed) + cache.mu.Lock() + cache.token = "changed-without-expiry" + cache.mu.Unlock() + }() + + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + token, err := provider.GetAccessToken(ctx, account) + + require.Error(t, err) + require.Empty(t, token, "an unbounded credential must not win the lock-held race") +} + +func TestGrokTokenProviderLockHeldUsesVersionedDBTokenAndRepairsStaleCache(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(60) + baseRepo := &tokenRefreshAccountRepo{} + baseRepo.accountsByID = map[int64]*Account{account.ID: account} + repo := &grokCredentialRaceRepo{tokenRefreshAccountRepo: baseRepo} + cache := &grokTokenCacheForProviderTest{lockResult: false, token: "expired-access-token"} + provider := NewGrokTokenProvider(repo, cache) + provider.SetRefreshAPI(NewOAuthRefreshAPI(repo, cache), &tokenRefresherStub{}) + + go func() { + time.Sleep(30 * time.Millisecond) + refreshed := *account + refreshed.Credentials = shallowCopyMap(account.Credentials) + refreshed.Credentials["access_token"] = "db-authoritative-token" + refreshed.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + refreshed.Credentials["_token_version"] = time.Now().UnixMilli() + repo.setAccount(&refreshed) + }() + + token, err := provider.GetAccessToken(context.Background(), account) + + require.NoError(t, err) + require.Equal(t, "db-authoritative-token", token) + require.Equal(t, "db-authoritative-token", cache.setToken) + require.Greater(t, cache.setTTL, time.Duration(0)) +} + +func TestGrokTokenProviderRejectsStaleDBTokenWithoutExpiry(t *testing.T) { + expiresAt := time.Now().Add(2 * grokTokenRefreshSkew).UTC().Format(time.RFC3339) + account := &Account{ + ID: 59, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Credentials: map[string]any{ + "access_token": "old-access-token", + "refresh_token": "refresh-token", + "expires_at": expiresAt, + }, + } + latest := *account + latest.Credentials = shallowCopyMap(account.Credentials) + latest.Credentials["access_token"] = "new-access-token-without-expiry" + latest.Credentials["_token_version"] = time.Now().UnixMilli() + delete(latest.Credentials, "expires_at") + repo := &tokenRefreshAccountRepo{} + repo.accountsByID = map[int64]*Account{account.ID: &latest} + cache := &grokTokenCacheForProviderTest{} + provider := NewGrokTokenProvider(repo, cache) + + token, err := provider.GetAccessToken(context.Background(), account) + + require.ErrorIs(t, err, errGrokOAuthAccessTokenExpired) + require.Empty(t, token) +} + +func TestGrokTokenProviderRejectsIneligibleSelectedAccountBeforeWarmCache(t *testing.T) { + future := time.Now().Add(time.Hour) + tests := []struct { + name string + mutate func(*Account) + }{ + {name: "disabled", mutate: func(account *Account) { account.Status = StatusDisabled }}, + {name: "not schedulable", mutate: func(account *Account) { account.Schedulable = false }}, + {name: "temporarily unschedulable", mutate: func(account *Account) { account.TempUnschedulableUntil = &future }}, + {name: "rate limited", mutate: func(account *Account) { account.RateLimitResetAt = &future }}, + {name: "overloaded", mutate: func(account *Account) { account.OverloadUntil = &future }}, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := expiredGrokOAuthAccountForCredentialTest(int64(90 + index)) + account.Credentials["access_token"] = "warm-cache-token" + account.Credentials["expires_at"] = time.Now().Add(2 * grokTokenRefreshSkew).UTC().Format(time.RFC3339) + tt.mutate(account) + cache := &grokTokenCacheForProviderTest{token: "warm-cache-token"} + provider := NewGrokTokenProvider(&tokenRefreshAccountRepo{}, cache) + + token, err := provider.GetAccessToken(context.Background(), account) + + require.ErrorIs(t, err, errOAuthRefreshAccountStateChanged) + require.Empty(t, token) + require.Zero(t, cache.getCalls, "an ineligible selected account must be rejected before cache lookup") + }) + } } diff --git a/backend/internal/service/grok_token_refresher.go b/backend/internal/service/grok_token_refresher.go index 92d88cc058..0b87fcac78 100644 --- a/backend/internal/service/grok_token_refresher.go +++ b/backend/internal/service/grok_token_refresher.go @@ -22,7 +22,8 @@ func (r *GrokTokenRefresher) CacheKey(account *Account) string { } func (r *GrokTokenRefresher) CanRefresh(account *Account) bool { - return account != nil && account.Platform == PlatformGrok && account.Type == AccountTypeOAuth + return account != nil && account.Platform == PlatformGrok && account.Type == AccountTypeOAuth && + strings.TrimSpace(account.GetGrokRefreshToken()) != "" } func (r *GrokTokenRefresher) NeedsRefresh(account *Account, refreshWindow time.Duration) bool { diff --git a/backend/internal/service/oauth_refresh_api.go b/backend/internal/service/oauth_refresh_api.go index 571e9ecdb7..b80cf84b64 100644 --- a/backend/internal/service/oauth_refresh_api.go +++ b/backend/internal/service/oauth_refresh_api.go @@ -2,6 +2,7 @@ package service import ( "context" + "errors" "fmt" "log/slog" "strconv" @@ -20,6 +21,45 @@ type OAuthRefreshExecutor interface { } const defaultRefreshLockTTL = 60 * time.Second +const oauthRefreshLockCleanupTimeout = 2 * time.Second + +var ( + errOAuthRefreshAccountRereadFailed = errors.New("oauth refresh account reread failed") + errOAuthRefreshAccountStateChanged = errors.New("oauth refresh account state changed") + errOAuthRefreshCredentialPersist = errors.New("oauth refresh credential persistence failed") +) + +type oauthRefreshRequestPathKey struct{} + +func withOAuthRefreshRequestPath(ctx context.Context) context.Context { + return context.WithValue(ctx, oauthRefreshRequestPathKey{}, true) +} + +func isOAuthRefreshRequestPath(ctx context.Context) bool { + requestPath, _ := ctx.Value(oauthRefreshRequestPathKey{}).(bool) + return requestPath +} + +type oauthRefreshLocalLock struct { + semaphore chan struct{} +} + +func newOAuthRefreshLocalLock() *oauthRefreshLocalLock { + return &oauthRefreshLocalLock{semaphore: make(chan struct{}, 1)} +} + +func (l *oauthRefreshLocalLock) Lock(ctx context.Context) error { + select { + case l.semaphore <- struct{}{}: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (l *oauthRefreshLocalLock) Unlock() { + <-l.semaphore +} // OAuthRefreshResult 统一刷新结果 type OAuthRefreshResult struct { @@ -35,7 +75,7 @@ type OAuthRefreshAPI struct { accountRepo AccountRepository tokenCache GeminiTokenCache // 可选,nil = 无分布式锁 lockTTL time.Duration - localLocks sync.Map // key: cacheKey string -> value: *sync.Mutex + localLocks sync.Map // key: cacheKey string -> value: *oauthRefreshLocalLock } // NewOAuthRefreshAPI 创建统一刷新 API @@ -53,11 +93,11 @@ func NewOAuthRefreshAPI(accountRepo AccountRepository, tokenCache GeminiTokenCac } // getLocalLock 返回指定 cacheKey 的进程内互斥锁 -func (api *OAuthRefreshAPI) getLocalLock(cacheKey string) *sync.Mutex { - actual, _ := api.localLocks.LoadOrStore(cacheKey, &sync.Mutex{}) - mu, ok := actual.(*sync.Mutex) +func (api *OAuthRefreshAPI) getLocalLock(cacheKey string) *oauthRefreshLocalLock { + actual, _ := api.localLocks.LoadOrStore(cacheKey, newOAuthRefreshLocalLock()) + mu, ok := actual.(*oauthRefreshLocalLock) if !ok { - mu = &sync.Mutex{} + mu = newOAuthRefreshLocalLock() api.localLocks.Store(cacheKey, mu) } return mu @@ -78,15 +118,25 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( executor OAuthRefreshExecutor, refreshWindow time.Duration, ) (*OAuthRefreshResult, error) { + if api == nil || api.accountRepo == nil { + return nil, errors.New("oauth refresh account repository is not configured") + } + if account == nil { + return nil, errors.New("oauth refresh account is nil") + } + if executor == nil { + return nil, errors.New("oauth refresh executor is nil") + } cacheKey := executor.CacheKey(account) // 0. 获取进程内互斥锁(防止同一进程内的并发刷新竞争) localMu := api.getLocalLock(cacheKey) - localMu.Lock() + if err := localMu.Lock(ctx); err != nil { + return nil, fmt.Errorf("oauth refresh local lock: %w", err) + } defer localMu.Unlock() // 1. 获取分布式锁 - lockAcquired := false if api.tokenCache != nil { acquired, lockErr := api.tokenCache.AcquireRefreshLock(ctx, cacheKey, api.lockTTL) if lockErr != nil { @@ -100,22 +150,38 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( // 锁被其他 worker 持有 return &OAuthRefreshResult{LockHeld: true}, nil } else { - lockAcquired = true - defer func() { _ = api.tokenCache.ReleaseRefreshLock(ctx, cacheKey) }() + defer func() { + cleanupCtx, cancel := context.WithTimeout(context.Background(), oauthRefreshLockCleanupTimeout) + defer cancel() + _ = api.tokenCache.ReleaseRefreshLock(cleanupCtx, cacheKey) + }() } } // 2. 从 DB 重读最新 account(锁保护下,确保使用最新的 refresh_token) freshAccount, err := api.accountRepo.GetByID(ctx, account.ID) if err != nil { - slog.Warn("oauth_refresh_db_reread_failed", - "account_id", account.ID, - "error", err, - ) - // 降级使用传入的 account - freshAccount = account - } else if freshAccount == nil { - freshAccount = account + return nil, fmt.Errorf("%w: %v", errOAuthRefreshAccountRereadFailed, err) + } + if freshAccount == nil { + return nil, fmt.Errorf("%w: account not found", errOAuthRefreshAccountStateChanged) + } + if freshAccount.ID != account.ID { + return nil, fmt.Errorf("%w: account identity mismatch", errOAuthRefreshAccountRereadFailed) + } + if !freshAccount.IsActive() { + return nil, fmt.Errorf("%w: account is not active", errOAuthRefreshAccountStateChanged) + } + if isOAuthRefreshRequestPath(ctx) && freshAccount.Platform == PlatformGrok { + if eligibilityErr := grokOAuthRequestAccountEligibilityError(freshAccount); eligibilityErr != nil { + return nil, withGrokCredentialFailureSnapshot(eligibilityErr, freshAccount) + } + } + if !executor.CanRefresh(freshAccount) { + if freshAccount.IsGrokOAuth() && strings.TrimSpace(freshAccount.GetGrokRefreshToken()) == "" { + return nil, withGrokCredentialFailureSnapshot(errGrokOAuthRefreshTokenMissing, freshAccount) + } + return nil, fmt.Errorf("%w: account is no longer refreshable", errOAuthRefreshAccountStateChanged) } // 3. 二次检查是否仍需刷新(另一条路径可能已刷新) @@ -127,11 +193,19 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( // 4. 执行平台特定刷新逻辑 newCredentials, refreshErr := executor.Refresh(ctx, freshAccount) + if err := ctx.Err(); err != nil { + return nil, err + } if refreshErr != nil { // 竞争恢复:invalid_grant 可能是另一个 worker 已消费了旧 refresh_token // 重新读取 DB,如果 refresh_token 已更新则说明是竞争,返回成功 if isInvalidGrantError(refreshErr) { if recoveredAccount, recovered := api.tryRecoverFromRefreshRace(ctx, freshAccount); recovered { + if isOAuthRefreshRequestPath(ctx) && recoveredAccount.Platform == PlatformGrok { + if eligibilityErr := grokOAuthRequestAccountEligibilityError(recoveredAccount); eligibilityErr != nil { + return nil, withGrokCredentialFailureSnapshot(eligibilityErr, recoveredAccount) + } + } slog.Info("oauth_refresh_race_recovered", "account_id", freshAccount.ID, "platform", freshAccount.Platform, @@ -141,7 +215,7 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( }, nil } } - return nil, refreshErr + return nil, withGrokCredentialFailureSnapshot(refreshErr, freshAccount) } // 5. 设置版本号 + 更新 DB @@ -152,16 +226,30 @@ func (api *OAuthRefreshAPI) RefreshIfNeeded( "account_id", freshAccount.ID, "error", updateErr, ) - return nil, fmt.Errorf("oauth refresh succeeded but DB update failed: %w", updateErr) + return nil, withGrokCredentialFailureSnapshot( + fmt.Errorf("%w: %v", errOAuthRefreshCredentialPersist, updateErr), freshAccount, + ) } } - - _ = lockAcquired // suppress unused warning when tokenCache is nil + resultAccount := freshAccount + if isOAuthRefreshRequestPath(ctx) && freshAccount.Platform == PlatformGrok { + latestAccount, rereadErr := api.accountRepo.GetByID(ctx, freshAccount.ID) + if rereadErr != nil { + return nil, fmt.Errorf("%w: %v", errOAuthRefreshAccountRereadFailed, rereadErr) + } + if latestAccount == nil { + return nil, fmt.Errorf("%w: account not found after refresh", errOAuthRefreshAccountStateChanged) + } + if eligibilityErr := grokOAuthRequestAccountEligibilityError(latestAccount); eligibilityErr != nil { + return nil, withGrokCredentialFailureSnapshot(eligibilityErr, latestAccount) + } + resultAccount = latestAccount + } return &OAuthRefreshResult{ Refreshed: true, NewCredentials: newCredentials, - Account: freshAccount, + Account: resultAccount, }, nil } diff --git a/backend/internal/service/oauth_refresh_api_test.go b/backend/internal/service/oauth_refresh_api_test.go index cacffddc59..adf089f0bd 100644 --- a/backend/internal/service/oauth_refresh_api_test.go +++ b/backend/internal/service/oauth_refresh_api_test.go @@ -51,13 +51,14 @@ func (r *refreshAPIAccountRepo) UpdateCredentials(_ context.Context, id int64, c // refreshAPIExecutorStub implements OAuthRefreshExecutor for tests. type refreshAPIExecutorStub struct { - needsRefresh bool - credentials map[string]any - err error - refreshCalls int + needsRefresh bool + cannotRefresh bool + credentials map[string]any + err error + refreshCalls int } -func (e *refreshAPIExecutorStub) CanRefresh(_ *Account) bool { return true } +func (e *refreshAPIExecutorStub) CanRefresh(_ *Account) bool { return !e.cannotRefresh } func (e *refreshAPIExecutorStub) NeedsRefresh(_ *Account, _ time.Duration) bool { return e.needsRefresh @@ -77,9 +78,10 @@ func (e *refreshAPIExecutorStub) CacheKey(account *Account) string { // refreshAPICacheStub implements GeminiTokenCache for OAuthRefreshAPI tests. type refreshAPICacheStub struct { - lockResult bool - lockErr error - releaseCalls int + lockResult bool + lockErr error + releaseCalls int + releaseCtxErr error } func (c *refreshAPICacheStub) GetAccessToken(context.Context, string) (string, error) { @@ -96,15 +98,16 @@ func (c *refreshAPICacheStub) AcquireRefreshLock(context.Context, string, time.D return c.lockResult, c.lockErr } -func (c *refreshAPICacheStub) ReleaseRefreshLock(context.Context, string) error { +func (c *refreshAPICacheStub) ReleaseRefreshLock(ctx context.Context, _ string) error { c.releaseCalls++ + c.releaseCtxErr = ctx.Err() return nil } // ========== RefreshIfNeeded tests ========== func TestRefreshIfNeeded_Success(t *testing.T) { - account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeOAuth} + account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockResult: true} executor := &refreshAPIExecutorStub{ @@ -132,6 +135,7 @@ func TestRefreshIfNeeded_UpdateCredentialsPreservesRateLimitState(t *testing.T) ID: 11, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, RateLimitResetAt: &resetAt, } repo := &refreshAPIAccountRepo{account: account} @@ -152,7 +156,7 @@ func TestRefreshIfNeeded_UpdateCredentialsPreservesRateLimitState(t *testing.T) } func TestRefreshIfNeeded_LockHeld(t *testing.T) { - account := &Account{ID: 2, Platform: PlatformAnthropic} + account := &Account{ID: 2, Platform: PlatformAnthropic, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockResult: false} // lock not acquired executor := &refreshAPIExecutorStub{needsRefresh: true} @@ -168,7 +172,7 @@ func TestRefreshIfNeeded_LockHeld(t *testing.T) { } func TestRefreshIfNeeded_LockErrorDegrades(t *testing.T) { - account := &Account{ID: 3, Platform: PlatformGemini, Type: AccountTypeOAuth} + account := &Account{ID: 3, Platform: PlatformGemini, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockErr: errors.New("redis down")} // lock error executor := &refreshAPIExecutorStub{ @@ -187,7 +191,7 @@ func TestRefreshIfNeeded_LockErrorDegrades(t *testing.T) { } func TestRefreshIfNeeded_NoCacheNoLock(t *testing.T) { - account := &Account{ID: 4, Platform: PlatformGemini, Type: AccountTypeOAuth} + account := &Account{ID: 4, Platform: PlatformGemini, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} executor := &refreshAPIExecutorStub{ needsRefresh: true, @@ -203,7 +207,7 @@ func TestRefreshIfNeeded_NoCacheNoLock(t *testing.T) { } func TestRefreshIfNeeded_AlreadyRefreshed(t *testing.T) { - account := &Account{ID: 5, Platform: PlatformAnthropic} + account := &Account{ID: 5, Platform: PlatformAnthropic, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockResult: true} executor := &refreshAPIExecutorStub{needsRefresh: false} // already refreshed @@ -220,7 +224,7 @@ func TestRefreshIfNeeded_AlreadyRefreshed(t *testing.T) { } func TestRefreshIfNeeded_RefreshError(t *testing.T) { - account := &Account{ID: 6, Platform: PlatformAnthropic} + account := &Account{ID: 6, Platform: PlatformAnthropic, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockResult: true} executor := &refreshAPIExecutorStub{ @@ -239,7 +243,7 @@ func TestRefreshIfNeeded_RefreshError(t *testing.T) { } func TestRefreshIfNeeded_DBUpdateError(t *testing.T) { - account := &Account{ID: 7, Platform: PlatformGemini, Type: AccountTypeOAuth} + account := &Account{ID: 7, Platform: PlatformGemini, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{ account: account, updateErr: errors.New("db connection lost"), @@ -255,12 +259,12 @@ func TestRefreshIfNeeded_DBUpdateError(t *testing.T) { require.Error(t, err) require.Nil(t, result) - require.Contains(t, err.Error(), "DB update failed") + require.ErrorIs(t, err, errOAuthRefreshCredentialPersist) require.Equal(t, 1, repo.updateCalls) // attempted } func TestRefreshIfNeeded_DBRereadFails(t *testing.T) { - account := &Account{ID: 8, Platform: PlatformAnthropic, Type: AccountTypeOAuth} + account := &Account{ID: 8, Platform: PlatformAnthropic, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{ account: nil, // GetByID returns nil getByIDErr: errors.New("db timeout"), @@ -274,13 +278,95 @@ func TestRefreshIfNeeded_DBRereadFails(t *testing.T) { api := NewOAuthRefreshAPI(repo, cache) result, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) - require.NoError(t, err) - require.True(t, result.Refreshed) - require.Equal(t, 1, executor.refreshCalls) // still refreshes using passed-in account + require.ErrorContains(t, err, "oauth refresh account reread") + require.Nil(t, result) + require.Zero(t, executor.refreshCalls, "must not refresh with the stale caller snapshot") + require.Zero(t, repo.updateCalls) + require.Equal(t, 1, cache.releaseCalls) +} + +func TestRefreshIfNeeded_DBRereadNilFailsClosed(t *testing.T) { + account := &Account{ID: 81, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive} + repo := &refreshAPIAccountRepo{} + cache := &refreshAPICacheStub{lockResult: true} + executor := &refreshAPIExecutorStub{needsRefresh: true} + + api := NewOAuthRefreshAPI(repo, cache) + result, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) + + require.ErrorIs(t, err, errOAuthRefreshAccountStateChanged) + require.Nil(t, result) + require.Zero(t, executor.refreshCalls) + require.Zero(t, repo.updateCalls) + require.Equal(t, 1, cache.releaseCalls) +} + +func TestRefreshIfNeeded_DBRereadInactiveFailsClosed(t *testing.T) { + account := &Account{ID: 82, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive} + freshAccount := &Account{ID: account.ID, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusDisabled} + repo := &refreshAPIAccountRepo{account: freshAccount} + executor := &refreshAPIExecutorStub{needsRefresh: true} + + api := NewOAuthRefreshAPI(repo, nil) + result, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) + + require.ErrorContains(t, err, "account is not active") + require.Nil(t, result) + require.Zero(t, executor.refreshCalls) + require.Zero(t, repo.updateCalls) +} + +func TestRefreshIfNeeded_DBRereadRevalidatesExecutorContract(t *testing.T) { + tests := []struct { + name string + freshPlatform string + freshType string + }{ + {name: "platform changed", freshPlatform: PlatformAnthropic, freshType: AccountTypeOAuth}, + {name: "type changed", freshPlatform: PlatformGrok, freshType: AccountTypeUpstream}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + account := &Account{ID: 83, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive} + freshAccount := &Account{ID: account.ID, Platform: tt.freshPlatform, Type: tt.freshType, Status: StatusActive} + repo := &refreshAPIAccountRepo{account: freshAccount} + executor := NewGrokTokenRefresher(nil) + + api := NewOAuthRefreshAPI(repo, nil) + result, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) + + require.ErrorContains(t, err, "no longer refreshable") + require.Nil(t, result) + require.Zero(t, repo.updateCalls) + }) + } +} + +func TestRefreshIfNeeded_DBRereadMissingGrokRefreshCredentialReturnsPermanentSignal(t *testing.T) { + account := &Account{ + ID: 84, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Credentials: map[string]any{ + "refresh_token": "caller-snapshot-refresh-token", + }, + } + freshAccount := &Account{ID: account.ID, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive} + repo := &refreshAPIAccountRepo{account: freshAccount} + executor := NewGrokTokenRefresher(nil) + + api := NewOAuthRefreshAPI(repo, nil) + result, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) + + require.ErrorIs(t, err, errGrokOAuthRefreshTokenMissing) + require.Nil(t, result) + require.Zero(t, repo.updateCalls) } func TestRefreshIfNeeded_NilCredentials(t *testing.T) { - account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeOAuth} + account := &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeOAuth, Status: StatusActive} repo := &refreshAPIAccountRepo{account: account} cache := &refreshAPICacheStub{lockResult: true} executor := &refreshAPIExecutorStub{ @@ -413,6 +499,7 @@ func TestRefreshIfNeeded_InvalidGrantRaceRecovered(t *testing.T) { ID: 10, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "old-rt", "access_token": "old-at"}, } // After race, DB has new refresh token from another worker @@ -420,6 +507,7 @@ func TestRefreshIfNeeded_InvalidGrantRaceRecovered(t *testing.T) { ID: 10, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "new-rt", "access_token": "new-at"}, } repo := &refreshAPIAccountRepoWithRace{ @@ -449,6 +537,7 @@ func TestRefreshIfNeeded_InvalidGrantGenuine(t *testing.T) { ID: 11, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "revoked-rt", "access_token": "old-at"}, } repo := &refreshAPIAccountRepoWithRace{ @@ -474,6 +563,7 @@ func TestRefreshIfNeeded_InvalidGrantDBRereadFailsOnRecovery(t *testing.T) { ID: 12, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "old-rt"}, } repo := &refreshAPIAccountRepoWithRace{ @@ -500,6 +590,7 @@ func TestRefreshIfNeeded_LocalMutexSerializesConcurrent(t *testing.T) { ID: 20, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "new-rt", "access_token": "new-at"}, } callCount := 0 @@ -507,6 +598,7 @@ func TestRefreshIfNeeded_LocalMutexSerializesConcurrent(t *testing.T) { ID: 20, Platform: PlatformAnthropic, Type: AccountTypeOAuth, + Status: StatusActive, Credentials: map[string]any{"refresh_token": "old-rt"}, }} @@ -556,6 +648,78 @@ func TestRefreshIfNeeded_LocalMutexSerializesConcurrent(t *testing.T) { mu.Unlock() } +func TestRefreshIfNeeded_LocalLockWaitHonorsContextCancellation(t *testing.T) { + account := &Account{ID: 21, Platform: PlatformGrok, Type: AccountTypeOAuth, Status: StatusActive} + repo := &refreshAPIAccountRepo{account: account} + refreshStarted := make(chan struct{}) + releaseRefresh := make(chan struct{}) + var once sync.Once + executor := &dynamicRefreshExecutor{ + canRefresh: true, + cacheKey: "test:context-lock:grok", + needsRefreshFunc: func() bool { return true }, + refreshFunc: func(context.Context, *Account) (map[string]any, error) { + once.Do(func() { close(refreshStarted) }) + <-releaseRefresh + return map[string]any{"access_token": "new-at"}, nil + }, + } + api := NewOAuthRefreshAPI(repo, nil) + firstDone := make(chan error, 1) + go func() { + _, err := api.RefreshIfNeeded(context.Background(), account, executor, 3*time.Minute) + firstDone <- err + }() + <-refreshStarted + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + startedAt := time.Now() + result, err := api.RefreshIfNeeded(ctx, account, executor, 3*time.Minute) + + require.Nil(t, result) + require.ErrorIs(t, err, context.DeadlineExceeded) + require.Less(t, time.Since(startedAt), 500*time.Millisecond) + close(releaseRefresh) + require.NoError(t, <-firstDone) +} + +func TestRefreshIfNeeded_ReleasesDistributedLockWithCleanupContext(t *testing.T) { + account := &Account{ + ID: 22, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Credentials: map[string]any{ + "access_token": "old-access", + "refresh_token": "old-refresh", + }, + } + repo := &refreshAPIAccountRepo{account: account} + cache := &refreshAPICacheStub{lockResult: true} + ctx, cancel := context.WithCancel(context.Background()) + executor := &dynamicRefreshExecutor{ + canRefresh: true, + cacheKey: "test:cleanup:grok", + needsRefreshFunc: func() bool { return true }, + refreshFunc: func(context.Context, *Account) (map[string]any, error) { + cancel() + return map[string]any{"access_token": "new-at"}, nil + }, + } + api := NewOAuthRefreshAPI(repo, cache) + + result, err := api.RefreshIfNeeded(ctx, account, executor, 3*time.Minute) + + require.ErrorIs(t, err, context.Canceled) + require.Nil(t, result) + require.Zero(t, repo.updateCalls) + require.Equal(t, "old-access", account.GetGrokAccessToken()) + require.Zero(t, account.GetCredentialAsInt64("_token_version")) + require.Equal(t, 1, cache.releaseCalls) + require.NoError(t, cache.releaseCtxErr) +} + // dynamicRefreshExecutor is a test helper with function-based NeedsRefresh and Refresh. type dynamicRefreshExecutor struct { canRefresh bool diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index a3f60fee2f..0b39ba8a2a 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -3,6 +3,7 @@ package service import ( "context" "net/http" + "sync" "time" ) @@ -96,6 +97,20 @@ func (s *OpenAIGatewayService) BlockAccountScheduling(account *Account, until ti if s == nil || !isOpenAIAccount(account) { return } + mu := s.openAIAccountRuntimeBlockLock(account.ID) + mu.Lock() + defer mu.Unlock() + _, _ = s.blockAccountSchedulingLocked(account, until, reason) +} + +func (s *OpenAIGatewayService) openAIAccountRuntimeBlockLock(accountID int64) *sync.Mutex { + actual, _ := s.openaiAccountRuntimeBlockLocks.LoadOrStore(accountID, &sync.Mutex{}) + return actual.(*sync.Mutex) +} + +func (s *OpenAIGatewayService) blockAccountSchedulingLocked(account *Account, until time.Time, _ string) (uint64, bool) { + generation := s.openaiAccountRuntimeBlockSequence.Add(1) + s.openaiAccountRuntimeBlockGeneration.Store(account.ID, generation) now := time.Now() blockUntil := until if blockUntil.IsZero() || !blockUntil.After(now) { @@ -107,7 +122,7 @@ func (s *OpenAIGatewayService) BlockAccountScheduling(account *Account, until ti if !loaded { actual, stored := s.openaiAccountRuntimeBlockUntil.LoadOrStore(account.ID, blockUntil) if !stored { - return + return generation, true } current = actual } @@ -115,15 +130,15 @@ func (s *OpenAIGatewayService) BlockAccountScheduling(account *Account, until ti currentUntil, ok := current.(time.Time) if !ok || currentUntil.IsZero() { if s.openaiAccountRuntimeBlockUntil.CompareAndSwap(account.ID, current, blockUntil) { - return + return generation, true } continue } - if currentUntil.After(blockUntil) { - return + if !blockUntil.After(currentUntil) { + return generation, false } if s.openaiAccountRuntimeBlockUntil.CompareAndSwap(account.ID, current, blockUntil) { - return + return generation, true } } } @@ -132,13 +147,20 @@ func (s *OpenAIGatewayService) ClearAccountSchedulingBlock(accountID int64) { if s == nil || accountID <= 0 { return } + mu := s.openAIAccountRuntimeBlockLock(accountID) + mu.Lock() + defer mu.Unlock() s.openaiAccountRuntimeBlockUntil.Delete(accountID) + s.openaiAccountRuntimeBlockGeneration.Store(accountID, s.openaiAccountRuntimeBlockSequence.Add(1)) } func (s *OpenAIGatewayService) isOpenAIAccountRuntimeBlocked(account *Account) bool { if s == nil || !isOpenAIAccount(account) { return false } + mu := s.openAIAccountRuntimeBlockLock(account.ID) + mu.Lock() + defer mu.Unlock() value, ok := s.openaiAccountRuntimeBlockUntil.Load(account.ID) if !ok { return false @@ -146,12 +168,14 @@ func (s *OpenAIGatewayService) isOpenAIAccountRuntimeBlocked(account *Account) b cooldownUntil, ok := value.(time.Time) if !ok || cooldownUntil.IsZero() { s.openaiAccountRuntimeBlockUntil.Delete(account.ID) + s.openaiAccountRuntimeBlockGeneration.Store(account.ID, s.openaiAccountRuntimeBlockSequence.Add(1)) return false } if time.Now().Before(cooldownUntil) { return true } s.openaiAccountRuntimeBlockUntil.Delete(account.ID) + s.openaiAccountRuntimeBlockGeneration.Store(account.ID, s.openaiAccountRuntimeBlockSequence.Add(1)) return false } diff --git a/backend/internal/service/openai_gateway_cc_pipeline.go b/backend/internal/service/openai_gateway_cc_pipeline.go index 690b9991bb..2391e25ba5 100644 --- a/backend/internal/service/openai_gateway_cc_pipeline.go +++ b/backend/internal/service/openai_gateway_cc_pipeline.go @@ -118,6 +118,7 @@ func (s *OpenAIGatewayService) failoverOpenAIUpstreamHTTPError( return &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && (account.IsPoolModeRetryableStatus(resp.StatusCode) || isOpenAITransientProcessingError(resp.StatusCode, upstreamMsg, respBody)), } } @@ -197,7 +198,9 @@ func (s *OpenAIGatewayService) sendCCUpstreamRequest( // 账号级请求头覆写(仅 openai api_key 账号启用时生效) account.ApplyHeaderOverrides(upstreamReq.Header) if account.Platform == PlatformGrok { - applyGrokCLIHeaders(upstreamReq.Header) + if account.IsGrokOAuth() { + applyGrokCLIHeaders(upstreamReq.Header) + } applyGrokCacheHeaders(upstreamReq.Header, grokCacheIdentity) } diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index 7693986b0d..095d544f89 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -109,7 +109,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( // Grok Composer does not accept image_url parts directly, but Grok Build // can describe the images first. Bridge only this exact failure mode. - token, tokenKind, err := s.GetAccessToken(ctx, account) + token, tokenKind, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, err } @@ -162,7 +162,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( } SetActualOpenAIUpstreamEndpoint(c, grokChatRawEndpoint) customUA := account.GetOpenAIUserAgent() - if customUA == "" && account.Platform == PlatformGrok { + if customUA == "" && account.IsGrokOAuth() { customUA = "sub2api-grok/1.0" } resp, err := s.sendCCUpstreamRequest(ctx, c, account, targetURL, upstreamBody, clientStream, token, customUA, grokCacheIdentity) @@ -189,6 +189,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index 8bd1d456dc..675b4bc9f9 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -54,7 +54,7 @@ func (s *OpenAIGatewayService) forwardGrokResponses( return nil, fmt.Errorf("apply grok prompt cache identity: %w", err) } - token, _, err := s.GetAccessToken(ctx, account) + token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, err } @@ -100,6 +100,7 @@ func (s *OpenAIGatewayService) forwardGrokResponses( return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } @@ -610,6 +611,7 @@ func (s *OpenAIGatewayService) describeGrokComposerImage( return "", OpenAIUsage{}, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } @@ -750,7 +752,9 @@ func buildGrokResponsesRequest(ctx context.Context, c *gin.Context, account *Acc req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json, text/event-stream") - applyGrokCLIHeaders(req.Header) + if account.IsGrokOAuth() { + applyGrokCLIHeaders(req.Header) + } applyGrokCacheHeaders(req.Header, cacheIdentity) if c != nil { if v := c.GetHeader("OpenAI-Beta"); strings.TrimSpace(v) != "" { diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge.go b/backend/internal/service/openai_gateway_grok_chat_bridge.go index fd6b426536..fe9cfb09fd 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge.go @@ -253,7 +253,7 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( } responsesBody = updatedBody - token, _, err := s.GetAccessToken(ctx, account) + token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, fmt.Errorf("get grok access token: %w", err) } @@ -294,6 +294,7 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( return nil, &UpstreamFailoverError{ StatusCode: resp.StatusCode, ResponseBody: respBody, + ResponseHeaders: resp.Header.Clone(), RetryableOnSameAccount: account.IsPoolMode() && account.IsPoolModeRetryableStatus(resp.StatusCode), } } diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge_test.go b/backend/internal/service/openai_gateway_grok_chat_bridge_test.go index 0843f1ea42..4fc31461b4 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge_test.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge_test.go @@ -284,6 +284,7 @@ func TestForwardGrokChatViaResponses429UsesGrokRateLimitPolicy(t *testing.T) { var failoverErr *UpstreamFailoverError require.True(t, errors.As(err, &failoverErr)) require.Equal(t, http.StatusTooManyRequests, failoverErr.StatusCode) + require.Equal(t, "45", failoverErr.ResponseHeaders.Get("Retry-After")) require.Equal(t, xai.DefaultCLIBaseURL+"/responses", upstream.lastReq.URL.String()) require.Equal(t, grokChatResponsesEndpoint, GetActualOpenAIUpstreamEndpoint(c)) require.Equal(t, 1, repo.rateLimitedCalls) @@ -292,6 +293,45 @@ func TestForwardGrokChatViaResponses429UsesGrokRateLimitPolicy(t *testing.T) { require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) } +func TestForwardGrokRawChat429PreservesRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + + body := []byte(`{"model":"grok","messages":[{"role":"user","content":"hi"}],"stream":false,"stop":"done"}`) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, grokChatRawEndpoint, bytes.NewReader(body)) + c.Set("api_key", &APIKey{ID: 7551}) + + account := grokChatBridgeTestAccount(755) + account.Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) + repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ + accountsByID: map[int64]*Account{account.ID: account}, + }} + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{ + "Content-Type": []string{"application/json"}, + "Retry-After": []string{"45"}, + }, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)), + }} + svc := &OpenAIGatewayService{ + httpUpstream: upstream, + grokTokenProvider: NewGrokTokenProvider(repo, nil), + accountRepo: repo, + } + + result, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + + require.Error(t, err) + require.Nil(t, result) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusTooManyRequests, failoverErr.StatusCode) + require.Equal(t, "45", failoverErr.ResponseHeaders.Get("Retry-After")) + require.Equal(t, xai.DefaultCLIBaseURL+"/chat/completions", upstream.lastReq.URL.String()) +} + func TestForwardGrokRawChatErrorRecordsActualEndpoint(t *testing.T) { gin.SetMode(gin.TestMode) @@ -329,11 +369,14 @@ func grokChatBridgeTestAccount(id int64) *Account { Name: "grok-cache-bridge", Platform: PlatformGrok, Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, + "access_token": "access-token", + "refresh_token": "refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), + "base_url": xai.DefaultCLIBaseURL, }, } } diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index 3b64cbc16b..4f7ed05edf 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -259,7 +259,7 @@ func TestBuildGrokResponsesRequestUsesAccountBaseURLAndBearerToken(t *testing.T) req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "access-token", "isolated-cache-id") require.NoError(t, err) require.Equal(t, http.MethodPost, req.Method) - require.Equal(t, "https://xai.test/v1/responses", req.URL.String()) + require.Equal(t, xai.DefaultCLIBaseURL+"/responses", req.URL.String()) require.Equal(t, "Bearer access-token", req.Header.Get("Authorization")) require.Equal(t, "application/json", req.Header.Get("Content-Type")) require.Contains(t, req.Header.Get("Accept"), "text/event-stream") @@ -284,6 +284,8 @@ func TestBuildGrokResponsesRequestAllowsPublicAPIKeyBaseURLByDefault(t *testing. require.NoError(t, err) require.Equal(t, "https://grok.example.test/v1/responses", req.URL.String()) require.Equal(t, "Bearer api-key", req.Header.Get("Authorization")) + require.Empty(t, req.Header.Get("X-Grok-Client-Version")) + require.NotEqual(t, grokUpstreamUserAgent, req.Header.Get("User-Agent")) } func TestBuildGrokResponsesRequestPinsOAuthCustomBaseURLByDefault(t *testing.T) { @@ -425,7 +427,8 @@ func TestForwardGrokMediaImagesGenerationNormalizesImagineAlias(t *testing.T) { require.Equal(t, http.MethodPost, upstream.lastReq.Method) require.Equal(t, "Bearer api-key", upstream.lastReq.Header.Get("Authorization")) require.Equal(t, "application/json", upstream.lastReq.Header.Get("Content-Type")) - require.Equal(t, grokCLIVersion, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) require.JSONEq(t, `{"model":"grok-imagine-image-quality","prompt":"draw a cat"}`, string(upstream.lastBody)) require.Equal(t, http.StatusOK, recorder.Code) require.JSONEq(t, `{"data":[]}`, recorder.Body.String()) @@ -611,7 +614,7 @@ func TestForwardGrokMediaVideoGenerationPreservesImageToVideoModel(t *testing.T) require.Equal(t, VideoBillingDefaultDurationSeconds, result.VideoDurationSeconds) } -func TestForwardGrokMediaOAuthImageToVideoUsesOfficialAPIForLargeBody(t *testing.T) { +func TestForwardGrokMediaOAuthImageToVideoKeepsCLIGatewayForLargeBody(t *testing.T) { gin.SetMode(gin.TestMode) recorder := httptest.NewRecorder() @@ -626,10 +629,14 @@ func TestForwardGrokMediaOAuthImageToVideoUsesOfficialAPIForLargeBody(t *testing Name: "grok-oauth", Platform: PlatformGrok, Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "oauth-access-token", - "base_url": xai.DefaultCLIBaseURL, + "access_token": "oauth-access-token", + "refresh_token": "oauth-refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), + "base_url": xai.DefaultCLIBaseURL, }, } upstream := &httpUpstreamRecorder{resp: &http.Response{ @@ -639,11 +646,11 @@ func TestForwardGrokMediaOAuthImageToVideoUsesOfficialAPIForLargeBody(t *testing }, Body: io.NopCloser(strings.NewReader(`{"request_id":"video-request-oauth"}`)), }} - svc := &OpenAIGatewayService{httpUpstream: upstream} + svc := &OpenAIGatewayService{httpUpstream: upstream, grokTokenProvider: NewGrokTokenProvider(nil, nil)} _, err := svc.ForwardGrokMedia(context.Background(), c, account, GrokMediaEndpointVideosGenerations, "", body, "application/json") require.NoError(t, err) - require.Equal(t, xai.DefaultBaseURL+"/videos/generations", upstream.lastReq.URL.String()) + require.Equal(t, xai.DefaultCLIBaseURL+"/videos/generations", upstream.lastReq.URL.String()) require.Equal(t, "data:image/png;base64,"+imageData, gjson.GetBytes(upstream.lastBody, "image.image_url").String()) } @@ -681,6 +688,8 @@ func TestForwardGrokMediaVideoStatusUsesGETWithoutBody(t *testing.T) { require.Equal(t, "https://xai.test/v1/videos/request-123", upstream.lastReq.URL.String()) require.Equal(t, http.MethodGet, upstream.lastReq.Method) require.Equal(t, "Bearer api-key", upstream.lastReq.Header.Get("Authorization")) + require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) require.Empty(t, upstream.lastReq.Header.Get("Content-Type")) require.Empty(t, upstream.lastBody) require.Equal(t, http.StatusOK, recorder.Code) @@ -792,6 +801,54 @@ func TestForwardGrokMedia429ReconcilesRateLimitBeforeCustomErrorBypass(t *testin require.True(t, svc.isOpenAIAccountRuntimeBlocked(account)) } +func TestGrokMedia429FailoverPreservesRetryAfter(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/generations", nil) + account := &Account{ + ID: 641, Name: "grok-oauth", Platform: PlatformGrok, Type: AccountTypeOAuth, + Status: StatusActive, Schedulable: true, + Credentials: map[string]any{ + "custom_error_codes_enabled": true, + "custom_error_codes": []any{float64(http.StatusTooManyRequests)}, + }, + } + repo := &grokQuotaAccountRepo{} + svc := &OpenAIGatewayService{accountRepo: repo} + resp := &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{"Retry-After": []string{"45"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"message":"rate limited"}}`)), + } + + result, err := svc.handleGrokMediaErrorResponse(context.Background(), resp, c, account, "request-id", "grok-imagine") + + require.Nil(t, result) + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.Equal(t, http.StatusTooManyRequests, failoverErr.StatusCode) + require.Equal(t, "45", failoverErr.ResponseHeaders.Get("Retry-After")) +} + +func healthyGrokOAuthGatewayTestAccount(id int64, token string) *Account { + return &Account{ + ID: id, + Name: "grok", + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "access_token": token, + "refresh_token": "refresh-token", + "expires_at": time.Now().Add(2 * grokTokenRefreshSkew).UTC().Format(time.RFC3339), + "base_url": xai.DefaultCLIBaseURL, + }, + } +} + func TestForwardAsChatCompletionsForGrokStopFallsBackToXAIChatCompletions(t *testing.T) { gin.SetMode(gin.TestMode) @@ -801,18 +858,7 @@ func TestForwardAsChatCompletionsForGrokStopFallsBackToXAIChatCompletions(t *tes c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) c.Set("api_key", &APIKey{ID: 5101}) - account := &Account{ - ID: 51, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(51, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{51: account}, @@ -864,18 +910,7 @@ func TestForwardGrokResponsesStreamingDefaultsEmptyModelTo45AndSnapshots(t *test c.Request.Header.Set("OpenAI-Beta", "responses=experimental") c.Set("api_key", &APIKey{ID: 5201}) - account := &Account{ - ID: 52, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(52, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{52: account}, @@ -968,12 +1003,46 @@ func TestForwardGrokResponsesAPIKeyUsesXAIResponses(t *testing.T) { require.NoError(t, err) require.Equal(t, "https://api.x.ai/v1/responses", upstream.lastReq.URL.String()) require.Equal(t, "Bearer xai-test-key", upstream.lastReq.Header.Get("Authorization")) + require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) require.Equal(t, "grok-4.5", gjson.GetBytes(upstream.lastBody, "model").String()) require.Equal(t, "resp_grok_api_key", result.ResponseID) require.Equal(t, 2, result.Usage.InputTokens) require.Equal(t, 1, result.Usage.OutputTokens) } +func TestForwardAsChatCompletionsForGrokAPIKeyUsesConfiguredRawEndpointWithoutOAuthIdentity(t *testing.T) { + gin.SetMode(gin.TestMode) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + body := []byte(`{"model":"grok","messages":[{"role":"user","content":"hi"}],"stream":false}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + account := &Account{ + ID: 706, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "third-party-key", + "base_url": "https://grok.example.test/v1", + }, + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"chatcmpl","object":"chat.completion","model":"grok-4.5","choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1}}`)), + }} + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + + _, err := svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + require.NoError(t, err) + require.Equal(t, "https://grok.example.test/v1/chat/completions", upstream.lastReq.URL.String()) + require.Equal(t, "Bearer third-party-key", upstream.lastReq.Header.Get("Authorization")) + require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.NotEqual(t, grokUpstreamUserAgent, upstream.lastReq.Header.Get("User-Agent")) +} + func TestAccountTestServiceGrokAPIKeyUsesXAIResponses(t *testing.T) { gin.SetMode(gin.TestMode) @@ -1017,18 +1086,7 @@ func TestForwardAsChatCompletionsForGrokStreamingUsesRawXAIChatCompletions(t *te c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", bytes.NewReader(body)) c.Request.Header.Set("Content-Type", "application/json") - account := &Account{ - ID: 53, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(53, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{53: account}, @@ -1085,18 +1143,7 @@ func TestForwardGrokResponsesNonStreamingUsesCacheIdentityAndCachedUsage(t *test c.Request.Header.Set("Content-Type", "application/json") c.Set("api_key", &APIKey{ID: 5202}) - account := &Account{ - ID: 56, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(56, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{56: account}, @@ -1145,18 +1192,9 @@ func TestForwardGrokResponsesFailoverKeepsCacheIdentityAcrossAccounts(t *testing c.Set("api_key", &APIKey{ID: 5203}) newAccount := func(id int64, token string) *Account { - return &Account{ - ID: id, - Name: fmt.Sprintf("grok-%d", id), - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": token, - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(id, token) + account.Name = fmt.Sprintf("grok-%d", id) + return account } firstAccount := newAccount(58, "access-token-a") secondAccount := newAccount(59, "access-token-b") @@ -1213,18 +1251,7 @@ func TestForwardAsChatCompletionsForGrokStreamingStopFallsBackToRawXAIChatComple c.Request.Header.Set(grokConversationIDHeader, "native-client-conversation") c.Set("api_key", &APIKey{ID: 5301}) - account := &Account{ - ID: 53, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(53, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{53: account}, @@ -1284,18 +1311,7 @@ func TestForwardAsChatCompletionsForGrokComposerBridgesImageInput(t *testing.T) c.Request.Header.Set("Content-Type", "application/json") c.Set("api_key", &APIKey{ID: 5501}) - account := &Account{ - ID: 55, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(55, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{55: account}, @@ -1358,18 +1374,7 @@ func TestForwardAsAnthropicForGrokUsesXAIResponses(t *testing.T) { c.Request.Header.Set("OpenAI-Beta", "grok-experimental") c.Request.Header.Set("originator", "opencode") - account := &Account{ - ID: 54, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(54, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{54: account}, @@ -1419,18 +1424,7 @@ func TestForwardAsAnthropicForGrokStreamingPreservesCacheUsage(t *testing.T) { c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) c.Set("api_key", &APIKey{ID: 5402}) - account := &Account{ - ID: 57, - Name: "grok", - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - "base_url": xai.DefaultCLIBaseURL, - }, - } + account := healthyGrokOAuthGatewayTestAccount(57, "access-token") repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{57: account}, diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 8cf62bdc65..e2add90ff2 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -258,7 +258,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( } // 5. Get access token - token, _, err := s.GetAccessToken(ctx, account) + token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, fmt.Errorf("get access token: %w", err) } diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 11a8255bfa..12c9a5bb97 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -401,6 +401,10 @@ type OpenAIGatewayService struct { openaiWSFallbackUntil sync.Map // key: int64(accountID), value: time.Time openaiAccountRuntimeBlockUntil sync.Map // key: int64(accountID), value: time.Time + openaiAccountRuntimeBlockLocks sync.Map // key: int64(accountID), value: *sync.Mutex + openaiAccountRuntimeBlockGeneration sync.Map // key: int64(accountID), value: uint64 + openaiAccountRuntimeBlockSequence atomic.Uint64 + grokCredentialMutationLocks sync.Map // key: int64(accountID), value: *sync.Mutex openaiOAuth429WindowStartUnixNano atomic.Int64 openaiOAuth429WindowCount atomic.Int64 openaiWSRetryMetrics openAIWSRetryMetrics diff --git a/backend/internal/service/ops_models.go b/backend/internal/service/ops_models.go index d95bbadbb8..411ca7595b 100644 --- a/backend/internal/service/ops_models.go +++ b/backend/internal/service/ops_models.go @@ -27,7 +27,7 @@ type OpsErrorLog struct { CreatedAt time.Time `json:"created_at"` // Standardized classification - // - phase: request|auth|routing|upstream|network|internal + // - phase: request|auth|account_auth|routing|upstream|network|internal // - owner: client|provider|platform // - source: client_request|upstream_http|gateway Phase string `json:"phase"` @@ -121,7 +121,7 @@ type OpsErrorLogFilter struct { StatusCodes []int StatusCodesOther bool - Phase string // Special: Phase=="upstream" bypasses status>=400 clause; do not set together with ErrorPhasesAny. + Phase string // Recovered provider rows bypass status>=400 only with the explicit opt-in below. Owner string Source string Resolved *bool @@ -150,14 +150,15 @@ type OpsErrorLogFilter struct { // ExcludeCountTokens drops count_tokens probe errors (is_count_tokens=true). ExcludeCountTokens bool - // IncludeRecoveredUpstream 显式豁免 status>=400 守卫(仅在 Phase=="upstream" 时生效): - // ops 专用上游错误列表需要看到 status<400 的 recovered upstream 行。 - // 请求错误语义的端点不设此开关,phase=upstream 过滤照常生效且守卫保留。 + // IncludeRecoveredUpstream explicitly exempts provider-health phases + // (upstream and account_auth) from the status>=400 guard. Ops provider + // health lists need status<400 recovered rows; request-error endpoints do + // not set this flag and retain client-error semantics. IncludeRecoveredUpstream bool // ErrorPhasesAny / ErrorTypesAny add plain ANY() filters WITHOUT touching the - // special-cased single `Phase` field (only Phase=="upstream" with - // IncludeRecoveredUpstream bypasses the status>=400 clause). + // special-cased single `Phase` field. With IncludeRecoveredUpstream, an ANY + // list containing only upstream/account_auth also bypasses status>=400. // NOTE: these ANY filters do NOT bypass status>=400; records with error_phase='upstream' // but status_code<400 (recovered upstream errors) remain excluded. // Used to map user-facing coarse categories to backend conditions. diff --git a/backend/internal/service/ops_service.go b/backend/internal/service/ops_service.go index 61f85ef904..3b27252665 100644 --- a/backend/internal/service/ops_service.go +++ b/backend/internal/service/ops_service.go @@ -222,6 +222,33 @@ func (s *OpsService) prepareErrorLogInput(ctx context.Context, entry *OpsInsertE entry.ErrorType = "api_error" } + // Credential acquisition is a gateway/account-auth stage, not an inference + // HTTP attempt. Enforce that ownership at the persistence boundary so an + // earlier inference attempt cannot leak its status or text into top-level + // auth fields even if a caller supplied stale single-value context. + for i := len(entry.UpstreamErrors) - 1; i >= 0; i-- { + last := entry.UpstreamErrors[i] + if last == nil { + continue + } + if last.Stage == string(GatewayFailureStageAccountAuth) { + entry.ErrorPhase = string(GatewayFailureStageAccountAuth) + entry.ErrorOwner = "provider" + entry.ErrorSource = "gateway" + code := 0 + entry.UpstreamStatusCode = &code + entry.UpstreamErrorMessage = nil + if message := strings.TrimSpace(last.Message); message != "" { + entry.UpstreamErrorMessage = &message + } + entry.UpstreamErrorDetail = nil + if detail := strings.TrimSpace(last.Detail); detail != "" { + entry.UpstreamErrorDetail = &detail + } + } + break + } + // Sanitize + truncate error_body to avoid storing sensitive data. if strings.TrimSpace(entry.ErrorBody) != "" { sanitized, _ := sanitizeErrorBodyForStorage(entry.ErrorBody, opsMaxStoredErrorBodyBytes) @@ -229,7 +256,7 @@ func (s *OpsService) prepareErrorLogInput(ctx context.Context, entry *OpsInsertE } // Sanitize upstream error context if provided by gateway services. - if entry.UpstreamStatusCode != nil && *entry.UpstreamStatusCode <= 0 { + if entry.UpstreamStatusCode != nil && *entry.UpstreamStatusCode <= 0 && entry.ErrorPhase != string(GatewayFailureStageAccountAuth) { entry.UpstreamStatusCode = nil } if entry.UpstreamErrorMessage != nil { diff --git a/backend/internal/service/ops_service_batch_test.go b/backend/internal/service/ops_service_batch_test.go index a9419ad7bf..a027f48737 100644 --- a/backend/internal/service/ops_service_batch_test.go +++ b/backend/internal/service/ops_service_batch_test.go @@ -97,6 +97,54 @@ func TestOpsServiceRecordErrorBatch_FallsBackToSingleInsert(t *testing.T) { require.Equal(t, 2, singleCalls) } +func TestOpsServiceRecordErrorPersistsExplicitAccountAuthStatusZero(t *testing.T) { + t.Parallel() + + var captured *OpsInsertErrorLogInput + repo := &opsRepoMock{ + InsertErrorLogFn: func(_ context.Context, input *OpsInsertErrorLogInput) (int64, error) { + captured = input + return 1, nil + }, + } + svc := NewOpsService(repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + staleStatus := 403 + staleMessage := "stale inference message" + staleDetail := "stale inference detail" + + err := svc.RecordError(context.Background(), &OpsInsertErrorLogInput{ + ErrorPhase: "upstream", + ErrorType: "upstream_error", + ErrorOwner: "provider", + ErrorSource: "upstream_http", + UpstreamStatusCode: &staleStatus, + UpstreamErrorMessage: &staleMessage, + UpstreamErrorDetail: &staleDetail, + UpstreamErrors: []*OpsUpstreamErrorEvent{ + {Stage: string(GatewayFailureStageInference), UpstreamStatusCode: 403, Message: staleMessage, Detail: staleDetail}, + { + Stage: string(GatewayFailureStageAccountAuth), Scope: string(GatewayFailureScopeAccount), + Reason: string(GrokCredentialReasonRevoked), Message: "Grok OAuth credentials require account action", + }, + }, + }) + + require.NoError(t, err) + require.NotNil(t, captured) + require.Equal(t, "account_auth", captured.ErrorPhase) + require.Equal(t, "provider", captured.ErrorOwner) + require.Equal(t, "gateway", captured.ErrorSource) + require.NotNil(t, captured.UpstreamStatusCode) + require.Zero(t, *captured.UpstreamStatusCode) + require.NotNil(t, captured.UpstreamErrorMessage) + require.Equal(t, "Grok OAuth credentials require account action", *captured.UpstreamErrorMessage) + require.Nil(t, captured.UpstreamErrorDetail) + require.Nil(t, captured.UpstreamErrors) + require.NotNil(t, captured.UpstreamErrorsJSON) + require.Contains(t, *captured.UpstreamErrorsJSON, `"upstream_status_code":403`) + require.Contains(t, *captured.UpstreamErrorsJSON, `"stage":"account_auth"`) +} + func strPtr(v string) *string { return &v } diff --git a/backend/internal/service/ops_upstream_context.go b/backend/internal/service/ops_upstream_context.go index 6389f1ecb5..2d28f1a168 100644 --- a/backend/internal/service/ops_upstream_context.go +++ b/backend/internal/service/ops_upstream_context.go @@ -188,6 +188,11 @@ type OpsUpstreamErrorEvent struct { // Kind: http_error | request_error | retry_exhausted | failover Kind string `json:"kind,omitempty"` + // Stage/Scope/Reason distinguish credential acquisition from inference + // without overloading upstream_status_code with a synthetic HTTP status. + Stage string `json:"stage,omitempty"` + Scope string `json:"scope,omitempty"` + Reason string `json:"reason,omitempty"` Message string `json:"message,omitempty"` Detail string `json:"detail,omitempty"` @@ -204,6 +209,9 @@ func appendOpsUpstreamError(c *gin.Context, ev OpsUpstreamErrorEvent) { ev.UpstreamRequestID = strings.TrimSpace(ev.UpstreamRequestID) ev.UpstreamResponseBody = strings.TrimSpace(ev.UpstreamResponseBody) ev.Kind = strings.TrimSpace(ev.Kind) + ev.Stage = strings.TrimSpace(ev.Stage) + ev.Scope = strings.TrimSpace(ev.Scope) + ev.Reason = strings.TrimSpace(ev.Reason) ev.UpstreamURL = strings.TrimSpace(ev.UpstreamURL) ev.Message = strings.TrimSpace(ev.Message) ev.Detail = strings.TrimSpace(ev.Detail) diff --git a/backend/internal/service/ops_user_error.go b/backend/internal/service/ops_user_error.go index e3055c2392..22d160bf34 100644 --- a/backend/internal/service/ops_user_error.go +++ b/backend/internal/service/ops_user_error.go @@ -44,7 +44,7 @@ func MapUserErrorCategory(phase, errType string) string { return "auth" case "routing": return "service_unavailable" - case "upstream", "network": + case "account_auth", "upstream", "network": return "upstream" case "internal": return "internal" @@ -73,7 +73,7 @@ func CategoryToFilter(category string) (phases []string, errorTypes []string) { case "service_unavailable": return []string{"routing"}, nil case "upstream": - return []string{"upstream", "network"}, nil + return []string{"account_auth", "upstream", "network"}, nil case "internal": return []string{"internal"}, nil case "rate_limit": diff --git a/backend/internal/service/ops_user_error_test.go b/backend/internal/service/ops_user_error_test.go index 9e0bc164b4..c72cf5dbfb 100644 --- a/backend/internal/service/ops_user_error_test.go +++ b/backend/internal/service/ops_user_error_test.go @@ -17,6 +17,7 @@ func TestMapUserErrorCategory(t *testing.T) { {"request", "subscription_error", "quota"}, {"request", "invalid_request_error", "invalid_request"}, {"routing", "api_error", "service_unavailable"}, + {"account_auth", "upstream_error", "upstream"}, {"upstream", "upstream_error", "upstream"}, {"network", "api_error", "upstream"}, {"internal", "api_error", "internal"}, @@ -43,7 +44,7 @@ func TestCategoryToFilter(t *testing.T) { t.Fatalf("service_unavailable => phases=%v types=%v", phases, types) } phases, types = CategoryToFilter("upstream") - if len(phases) != 2 || phases[0] != "upstream" || phases[1] != "network" || len(types) != 0 { + if len(phases) != 3 || phases[0] != "account_auth" || phases[1] != "upstream" || phases[2] != "network" || len(types) != 0 { t.Fatalf("upstream => phases=%v types=%v", phases, types) } phases, types = CategoryToFilter("internal") diff --git a/backend/internal/service/refresh_policy.go b/backend/internal/service/refresh_policy.go index 7f299be019..6b90077e3b 100644 --- a/backend/internal/service/refresh_policy.go +++ b/backend/internal/service/refresh_policy.go @@ -61,6 +61,14 @@ func AntigravityProviderRefreshPolicy() ProviderRefreshPolicy { } } +func GrokProviderRefreshPolicy() ProviderRefreshPolicy { + return ProviderRefreshPolicy{ + OnRefreshError: ProviderRefreshErrorReturn, + OnLockHeld: ProviderLockHeldWaitForCache, + FailureTTL: 0, + } +} + // BackgroundSkipAction 定义后台刷新服务在“未实际刷新”场景的计数方式。 type BackgroundSkipAction int diff --git a/backend/internal/service/token_refresh_service_test.go b/backend/internal/service/token_refresh_service_test.go index bd6a521576..c4c0b35ceb 100644 --- a/backend/internal/service/token_refresh_service_test.go +++ b/backend/internal/service/token_refresh_service_test.go @@ -26,6 +26,9 @@ type tokenRefreshAccountRepo struct { lastExtraUpdates map[string]any lastAccount *Account updateErr error + setErrorErr error + setTempUnschedErr error + beforeConditionalState func() } func (r *tokenRefreshAccountRepo) Update(ctx context.Context, account *Account) error { @@ -56,7 +59,7 @@ func (r *tokenRefreshAccountRepo) UpdateCredentials(ctx context.Context, id int6 func (r *tokenRefreshAccountRepo) SetError(ctx context.Context, id int64, errorMsg string) error { r.setErrorCalls++ r.lastErrorMessage = errorMsg - return nil + return r.setErrorErr } func (r *tokenRefreshAccountRepo) ClearTempUnschedulable(ctx context.Context, id int64) error { @@ -67,7 +70,66 @@ func (r *tokenRefreshAccountRepo) ClearTempUnschedulable(ctx context.Context, id func (r *tokenRefreshAccountRepo) SetTempUnschedulable(ctx context.Context, id int64, until time.Time, reason string) error { r.setTempUnschedCalls++ r.lastTempUnschedReason = reason - return nil + return r.setTempUnschedErr +} + +func (r *tokenRefreshAccountRepo) SetGrokCredentialErrorIfMatch( + _ context.Context, + id int64, + snapshot GrokCredentialMutationSnapshot, + errorMsg string, +) (bool, error) { + if r.beforeConditionalState != nil { + hook := r.beforeConditionalState + r.beforeConditionalState = nil + hook() + } + account := r.accountsByID[id] + if !grokCredentialSnapshotMatchesAccount(account, snapshot) || + (errorMsg == string(GrokCredentialReasonProxyInvalid) && account.Proxy != nil) { + return false, nil + } + r.setErrorCalls++ + r.lastErrorMessage = errorMsg + if r.setErrorErr != nil { + return false, r.setErrorErr + } + account.Status = StatusError + account.Schedulable = false + account.ErrorMessage = errorMsg + return true, nil +} + +func (r *tokenRefreshAccountRepo) SetGrokCredentialTempUnschedulableIfMatch( + _ context.Context, + id int64, + snapshot GrokCredentialMutationSnapshot, + until time.Time, + reason string, +) (bool, error) { + if r.beforeConditionalState != nil { + hook := r.beforeConditionalState + r.beforeConditionalState = nil + hook() + } + account := r.accountsByID[id] + if !grokCredentialSnapshotMatchesAccount(account, snapshot) { + return false, nil + } + r.setTempUnschedCalls++ + r.lastTempUnschedReason = reason + if r.setTempUnschedErr != nil { + return false, r.setTempUnschedErr + } + value := until + account.TempUnschedulableUntil = &value + return true, nil +} + +func grokCredentialSnapshotMatchesAccount(account *Account, snapshot GrokCredentialMutationSnapshot) bool { + return account != nil && account.IsGrokOAuth() && account.IsSchedulable() && + grokCredentialMutationSnapshot(account).CredentialsJSON == snapshot.CredentialsJSON && + grokCredentialProxyIDsEqual(account.ProxyID, snapshot.ProxyID) } func (r *tokenRefreshAccountRepo) UpdateExtra(ctx context.Context, id int64, updates map[string]any) error { @@ -750,6 +812,7 @@ func TestPathA_Success(t *testing.T) { ID: 100, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{} repo.accountsByID = map[int64]*Account{account.ID: account} @@ -771,6 +834,7 @@ func TestPathA_LockHeld(t *testing.T) { ID: 101, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{} invalidator := &tokenCacheInvalidatorStub{} @@ -791,6 +855,7 @@ func TestPathA_AlreadyRefreshed(t *testing.T) { ID: 102, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{} repo.accountsByID = map[int64]*Account{account.ID: account} @@ -830,6 +895,7 @@ func TestPathA_NonRetryableError(t *testing.T) { ID: 103, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{} repo.accountsByID = map[int64]*Account{account.ID: account} @@ -855,6 +921,7 @@ func TestPathA_RetryableErrorExhausted(t *testing.T) { ID: 104, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{} repo.accountsByID = map[int64]*Account{account.ID: account} @@ -888,6 +955,7 @@ func TestPathA_DBUpdateFailed(t *testing.T) { ID: 105, Platform: PlatformGemini, Type: AccountTypeOAuth, + Status: StatusActive, } repo := &tokenRefreshAccountRepo{updateErr: errors.New("db connection lost")} repo.accountsByID = map[int64]*Account{account.ID: account} @@ -898,7 +966,7 @@ func TestPathA_DBUpdateFailed(t *testing.T) { err := service.refreshWithRetry(context.Background(), account, refresher, refresher, time.Hour) require.Error(t, err) - require.Contains(t, err.Error(), "DB update failed") + require.ErrorIs(t, err, errOAuthRefreshCredentialPersist) require.Equal(t, 1, repo.updateCalls) // DB 更新被尝试 require.Equal(t, 0, invalidator.calls) // DB 失败时不应触发缓存失效 } diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index d5d9124ec2..96956b2f5d 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -186,7 +186,7 @@ func ProvideGrokTokenProvider( p := NewGrokTokenProvider(accountRepo, tokenCache) executor := NewGrokTokenRefresher(grokOAuthService) p.SetRefreshAPI(refreshAPI, executor) - p.SetRefreshPolicy(AntigravityProviderRefreshPolicy()) + p.SetRefreshPolicy(GrokProviderRefreshPolicy()) p.SetTempUnschedCache(tempUnschedCache) return p } diff --git a/frontend/src/components/admin/usage/UsageFilters.vue b/frontend/src/components/admin/usage/UsageFilters.vue index aa981ac187..d1e15d2cf4 100644 --- a/frontend/src/components/admin/usage/UsageFilters.vue +++ b/frontend/src/components/admin/usage/UsageFilters.vue @@ -277,6 +277,7 @@ const billingTypeOptions = ref([ const errorPhaseOptions = computed(() => [ { value: null, label: t('admin.usage.allTypes') }, { value: 'upstream', label: t('admin.ops.errorLog.typeUpstream') }, + { value: 'account_auth', label: t('admin.ops.errorLog.typeAccountAuth') }, { value: 'request', label: t('admin.ops.errorLog.typeRequest') }, { value: 'auth', label: t('admin.ops.errorLog.typeAuth') }, { value: 'routing', label: t('admin.ops.errorLog.typeRouting') }, diff --git a/frontend/src/i18n/locales/en/admin/ops.ts b/frontend/src/i18n/locales/en/admin/ops.ts index 588f673518..6a6d02a81c 100644 --- a/frontend/src/i18n/locales/en/admin/ops.ts +++ b/frontend/src/i18n/locales/en/admin/ops.ts @@ -266,6 +266,7 @@ export default { typeUpstream: 'Upstream', typeRequest: 'Request', typeAuth: 'Auth', + typeAccountAuth: 'Account Auth', typeRouting: 'Routing', typeInternal: 'Internal', endpoint: 'Endpoint', @@ -291,6 +292,7 @@ export default { phase: { request: 'Request', auth: 'Auth', + account_auth: 'Account Auth', routing: 'Routing', upstream: 'Upstream', network: 'Network', diff --git a/frontend/src/i18n/locales/zh/admin/ops.ts b/frontend/src/i18n/locales/zh/admin/ops.ts index 830d797a31..2816ec3240 100644 --- a/frontend/src/i18n/locales/zh/admin/ops.ts +++ b/frontend/src/i18n/locales/zh/admin/ops.ts @@ -266,6 +266,7 @@ export default { typeUpstream: '上游', typeRequest: '请求', typeAuth: '认证', + typeAccountAuth: '账号认证', typeRouting: '路由', typeInternal: '内部', endpoint: '端点', @@ -291,6 +292,7 @@ export default { phase: { request: '请求', auth: '认证', + account_auth: '账号认证', routing: '路由', upstream: '上游', network: '网络', diff --git a/frontend/src/utils/errorCategory.ts b/frontend/src/utils/errorCategory.ts index 58e97e14c4..7150c18265 100644 --- a/frontend/src/utils/errorCategory.ts +++ b/frontend/src/utils/errorCategory.ts @@ -9,6 +9,7 @@ export function mapErrorCategory(phase?: string | null, errType?: string | null) return 'auth' case 'routing': return 'service_unavailable' + case 'account_auth': case 'upstream': case 'network': return 'upstream' diff --git a/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue b/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue index 0400033e89..f04876ffae 100644 --- a/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue +++ b/frontend/src/views/admin/ops/components/OpsErrorDetailsModal.vue @@ -72,6 +72,7 @@ const phaseSelectOptions = computed(() => { { value: '', label: t('common.all') }, { value: 'request', label: t('admin.ops.errorDetails.phase.request') || 'request' }, { value: 'auth', label: t('admin.ops.errorDetails.phase.auth') || 'auth' }, + { value: 'account_auth', label: t('admin.ops.errorDetails.phase.account_auth') || 'account_auth' }, { value: 'routing', label: t('admin.ops.errorDetails.phase.routing') || 'routing' }, { value: 'upstream', label: t('admin.ops.errorDetails.phase.upstream') || 'upstream' }, { value: 'network', label: t('admin.ops.errorDetails.phase.network') || 'network' }, diff --git a/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue b/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue index 856b8810d7..6cb0bb1b4c 100644 --- a/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue +++ b/frontend/src/views/admin/ops/components/OpsErrorLogTable.vue @@ -277,6 +277,9 @@ function getTypeBadge(log: OpsErrorLog): { label: string; className: string } { if (phase === 'auth' && owner === 'client') { return { label: t('admin.ops.errorLog.typeAuth'), className: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200' } } + if (phase === 'account_auth') { + return { label: t('admin.ops.errorLog.typeAccountAuth'), className: 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200' } + } if (phase === 'routing' && owner === 'platform') { return { label: t('admin.ops.errorLog.typeRouting'), className: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200' } } From 91ae671a583abd1d331a020ba7421c8e726015c5 Mon Sep 17 00:00:00 2001 From: Heatherm Huang Date: Tue, 14 Jul 2026 01:02:16 +0800 Subject: [PATCH 02/83] fix(grok): satisfy lint checks --- backend/internal/service/account.go | 31 ------------------- .../service/grok_credential_failure.go | 7 ++++- .../internal/service/grok_token_provider.go | 1 - .../openai_account_runtime_block_fastpath.go | 7 ++++- 4 files changed, 12 insertions(+), 34 deletions(-) diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 539c92741d..5214518fb5 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -6,7 +6,6 @@ import ( "errors" "hash/fnv" "log/slog" - "net/url" "reflect" "sort" "strconv" @@ -1296,36 +1295,6 @@ func (a *Account) GetGrokMediaBaseURL() string { return a.GetGrokBaseURL() } -func isOfficialGrokAPIBaseURL(raw string) bool { - return isOfficialGrokBaseURL(raw, xai.DefaultBaseURL) -} - -func isOfficialGrokCLIBaseURL(raw string) bool { - return isOfficialGrokBaseURL(raw, xai.DefaultCLIBaseURL) -} - -func isOfficialGrokBaseURL(raw, expected string) bool { - parsed, err := url.Parse(strings.TrimSpace(raw)) - if err != nil || parsed == nil || parsed.Opaque != "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" { - return false - } - defaultURL, err := url.Parse(expected) - if err != nil { - return false - } - if !strings.EqualFold(parsed.Scheme, defaultURL.Scheme) || !strings.EqualFold(parsed.Hostname(), defaultURL.Hostname()) { - return false - } - if port := parsed.Port(); port != "" { - portNumber, err := strconv.Atoi(port) - if err != nil || portNumber != 443 { - return false - } - } - path := strings.TrimRight(parsed.Path, "/") - return path == "" || path == strings.TrimRight(defaultURL.Path, "/") -} - func (a *Account) GetGrokAccessToken() string { if !a.IsGrok() { return "" diff --git a/backend/internal/service/grok_credential_failure.go b/backend/internal/service/grok_credential_failure.go index 8886855f12..65dd844072 100644 --- a/backend/internal/service/grok_credential_failure.go +++ b/backend/internal/service/grok_credential_failure.go @@ -497,7 +497,12 @@ func (s *OpenAIGatewayService) validateCurrentGrokCredentialFailure( func (s *OpenAIGatewayService) grokCredentialMutationLock(accountID int64) *oauthRefreshLocalLock { actual, _ := s.grokCredentialMutationLocks.LoadOrStore(accountID, newOAuthRefreshLocalLock()) - return actual.(*oauthRefreshLocalLock) + mu, ok := actual.(*oauthRefreshLocalLock) + if !ok { + mu = newOAuthRefreshLocalLock() + s.grokCredentialMutationLocks.Store(accountID, mu) + } + return mu } func (s *OpenAIGatewayService) grokCredentialMutationCommitted(accountID int64, class grokCredentialFailureClass, until time.Time) bool { diff --git a/backend/internal/service/grok_token_provider.go b/backend/internal/service/grok_token_provider.go index c4dc4d4b12..ae57cdc59e 100644 --- a/backend/internal/service/grok_token_provider.go +++ b/backend/internal/service/grok_token_provider.go @@ -22,7 +22,6 @@ var ( errGrokOAuthAccessTokenMissing = errors.New("grok oauth access token is missing") errGrokOAuthAccessTokenExpired = errors.New("grok oauth access token is expired") errGrokOAuthConfiguredProxyMiss = errors.New("grok oauth configured proxy is missing") - errGrokOAuthRefreshLockTimeout = errors.New("grok oauth refresh lock wait timed out") ) type GrokTokenCache = GeminiTokenCache diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index 0b39ba8a2a..978b740a56 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -105,7 +105,12 @@ func (s *OpenAIGatewayService) BlockAccountScheduling(account *Account, until ti func (s *OpenAIGatewayService) openAIAccountRuntimeBlockLock(accountID int64) *sync.Mutex { actual, _ := s.openaiAccountRuntimeBlockLocks.LoadOrStore(accountID, &sync.Mutex{}) - return actual.(*sync.Mutex) + mu, ok := actual.(*sync.Mutex) + if !ok { + mu = &sync.Mutex{} + s.openaiAccountRuntimeBlockLocks.Store(accountID, mu) + } + return mu } func (s *OpenAIGatewayService) blockAccountSchedulingLocked(account *Account, until time.Time, _ string) (uint64, bool) { From b32b815e46fe97901179d776387f23d6ba7df0c7 Mon Sep 17 00:00:00 2001 From: Heatherm Huang Date: Tue, 14 Jul 2026 09:43:56 +0800 Subject: [PATCH 03/83] fix(grok): harden OAuth pool recovery --- backend/internal/handler/grok_media.go | 5 + .../internal/handler/openai_alpha_search.go | 3 +- .../handler/openai_chat_completions.go | 3 +- ...i_gateway_credential_failover_loop_test.go | 196 +++++++++++++++- .../handler/openai_gateway_handler.go | 9 +- backend/internal/handler/openai_images.go | 3 +- backend/internal/pkg/xai/oauth.go | 78 ++++++- backend/internal/pkg/xai/oauth_test.go | 39 ++++ backend/internal/repository/account_repo.go | 29 +++ .../account_repo_integration_test.go | 50 +++++ .../internal/service/account_test_service.go | 8 +- backend/internal/service/grok_media.go | 24 +- .../internal/service/grok_quota_service.go | 6 +- .../service/grok_quota_service_test.go | 19 ++ backend/internal/service/grok_upstream_url.go | 90 ++++++++ .../service/grok_upstream_url_test.go | 122 ++++++++++ .../openai_account_runtime_block_fastpath.go | 29 ++- ...nai_account_runtime_block_fastpath_test.go | 39 +++- .../openai_gateway_chat_completions_raw.go | 5 +- .../internal/service/openai_gateway_grok.go | 97 +++++++- .../openai_gateway_grok_chat_bridge.go | 5 +- .../service/openai_gateway_grok_test.go | 211 +++++++++++++++++- .../service/openai_gateway_messages.go | 5 +- .../internal/service/openai_ws_http_bridge.go | 5 +- 24 files changed, 1001 insertions(+), 79 deletions(-) create mode 100644 backend/internal/service/grok_upstream_url.go create mode 100644 backend/internal/service/grok_upstream_url_test.go diff --git a/backend/internal/handler/grok_media.go b/backend/internal/handler/grok_media.go index 408020f0a6..6b10f7bcbe 100644 --- a/backend/internal/handler/grok_media.go +++ b/backend/internal/handler/grok_media.go @@ -166,6 +166,7 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. failedAccountIDs := make(map[int64]struct{}) sameAccountRetryCount := make(map[int64]int) var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState switchCount := 0 maxAccountSwitches := h.maxAccountSwitches if maxAccountSwitches <= 0 { @@ -300,6 +301,10 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service. return } switchCount++ + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { + h.handleFailoverExhausted(c, failoverErr, false) + return + } reqLog.Warn("grok_media.upstream_failover_switching", zap.Int64("account_id", account.ID), zap.Int("upstream_status", failoverErr.StatusCode), diff --git a/backend/internal/handler/openai_alpha_search.go b/backend/internal/handler/openai_alpha_search.go index a808145235..4f5c07d8c5 100644 --- a/backend/internal/handler/openai_alpha_search.go +++ b/backend/internal/handler/openai_alpha_search.go @@ -106,6 +106,7 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { failedAccountIDs := make(map[int64]struct{}) var lastFailoverErr *service.UpstreamFailoverError switchCount := 0 + var oauth429FailoverState service.OpenAIOAuth429FailoverState routingStart := time.Now() for { @@ -188,7 +189,7 @@ func (h *OpenAIGatewayHandler) AlphaSearch(c *gin.Context) { return } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { h.handleFailoverExhausted(c, failoverErr, false) return } diff --git a/backend/internal/handler/openai_chat_completions.go b/backend/internal/handler/openai_chat_completions.go index fc58b3a25a..004aff2bb7 100644 --- a/backend/internal/handler/openai_chat_completions.go +++ b/backend/internal/handler/openai_chat_completions.go @@ -133,6 +133,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { failedAccountIDs := make(map[int64]struct{}) sameAccountRetryCount := make(map[int64]int) var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState for { if c.Request.Context().Err() != nil { @@ -275,7 +276,7 @@ func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) { return } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } diff --git a/backend/internal/handler/openai_gateway_credential_failover_loop_test.go b/backend/internal/handler/openai_gateway_credential_failover_loop_test.go index e7030d9d2f..42a6bf6cd3 100644 --- a/backend/internal/handler/openai_gateway_credential_failover_loop_test.go +++ b/backend/internal/handler/openai_gateway_credential_failover_loop_test.go @@ -31,6 +31,7 @@ type grokCredentialHandlerRepo struct { accounts []service.Account setErrorIDs []int64 setTempIDs []int64 + rateLimitIDs []int64 updateExtraIDs []int64 selectionCalls int setErrorErr error @@ -108,6 +109,34 @@ func (r *grokCredentialHandlerRepo) SetTempUnschedulable(_ context.Context, id i return nil } +func (r *grokCredentialHandlerRepo) SetRateLimited(_ context.Context, id int64, resetAt time.Time) error { + r.mu.Lock() + defer r.mu.Unlock() + r.rateLimitIDs = append(r.rateLimitIDs, id) + for i := range r.accounts { + if r.accounts[i].ID != id { + continue + } + now := time.Now() + r.accounts[i].RateLimitedAt = &now + value := resetAt + r.accounts[i].RateLimitResetAt = &value + } + return nil +} + +func (r *grokCredentialHandlerRepo) SetRateLimitedIfLater(ctx context.Context, id int64, resetAt time.Time) error { + r.mu.Lock() + for i := range r.accounts { + if r.accounts[i].ID == id && r.accounts[i].RateLimitResetAt != nil && !resetAt.After(*r.accounts[i].RateLimitResetAt) { + r.mu.Unlock() + return nil + } + } + r.mu.Unlock() + return r.SetRateLimited(ctx, id, resetAt) +} + func (r *grokCredentialHandlerRepo) SetGrokCredentialErrorIfMatch( _ context.Context, id int64, @@ -204,6 +233,12 @@ func (r *grokCredentialHandlerRepo) selectorCalls() int { return r.selectionCalls } +func (r *grokCredentialHandlerRepo) rateLimitedAccountIDs() []int64 { + r.mu.Lock() + defer r.mu.Unlock() + return append([]int64(nil), r.rateLimitIDs...) +} + type grokCredentialHandlerTokenCache struct { service.GrokTokenCache mu sync.Mutex @@ -282,6 +317,8 @@ type grokCredentialHandlerUpstream struct { requestURLs []string authorization []string failAccountID int64 + rateLimitIDs map[int64]bool + failureStatus map[int64]int cancelRequest context.CancelFunc } @@ -295,8 +332,27 @@ func (u *grokCredentialHandlerUpstream) Do(req *http.Request, _ string, accountI u.requestURLs = append(u.requestURLs, req.URL.String()) u.authorization = append(u.authorization, req.Header.Get("Authorization")) failAccountID := u.failAccountID + rateLimited := u.rateLimitIDs[accountID] + failureStatus := u.failureStatus[accountID] cancelRequest := u.cancelRequest u.mu.Unlock() + if rateLimited { + return &http.Response{ + StatusCode: http.StatusTooManyRequests, + Header: http.Header{ + "Content-Type": []string{"application/json"}, + "Retry-After": []string{"60"}, + }, + Body: io.NopCloser(bytes.NewBufferString(`{"error":{"message":"rate limited"}}`)), + }, nil + } + if failureStatus > 0 { + return &http.Response{ + StatusCode: failureStatus, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(bytes.NewBufferString(`{"error":{"message":"upstream unavailable"}}`)), + }, nil + } if accountID == failAccountID { if cancelRequest != nil { cancelRequest() @@ -502,6 +558,115 @@ func TestResponsesCredentialFailoverLoop(t *testing.T) { }) } +func TestResponsesGrok429FailoverIsBounded(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("first rate limited account selects healthy account", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "first_429") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Contains(t, recorder.Body.String(), "resp_healthy") + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + require.Equal(t, []int64{801}, repo.rateLimitedAccountIDs()) + }) + + t.Run("two rate limited accounts stop without sweeping the pool", func(t *testing.T) { + _, repo, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "all_429") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + require.Equal(t, []int64{801, 802}, repo.rateLimitedAccountIDs()) + require.NotContains(t, recorder.Body.String(), "expired") + require.NotContains(t, recorder.Body.String(), "healthy-access") + require.NotContains(t, recorder.Body.String(), "rate limited") + }) +} + +func TestResponsesGrok429FailoverHandlesMixedStatuses(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("429 then 500 stops after the bounded followup", func(t *testing.T) { + _, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "mixed_429_500") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusBadGateway, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + require.NotContains(t, recorder.Body.String(), "upstream unavailable") + }) + + t.Run("500 then 429 permits one healthy followup", func(t *testing.T) { + _, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "mixed_500_429") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802, 803}, upstream.accountHits()) + }) + + t.Run("OAuth 429 then API-key failure cannot bypass the bound", func(t *testing.T) { + _, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "oauth_429_apikey_500") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/openai/v1/responses", bytes.NewBufferString(`{"model":"grok","input":"hello","stream":false}`)) + req.Header.Set("Content-Type", "application/json") + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusBadGateway, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + }) +} + +func TestGrokMedia429FailoverIsBounded(t *testing.T) { + gin.SetMode(gin.TestMode) + + t.Run("first 429 selects one healthy followup", func(t *testing.T) { + _, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "first_429") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/openai/v1/videos/request-1", nil) + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + }) + + t.Run("second 429 stops without sweeping a third account", func(t *testing.T) { + _, _, upstream, router, cleanup := newGrokCredentialFailoverHandler(t, "all_429") + defer cleanup() + recorder := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/openai/v1/videos/request-1", nil) + + router.ServeHTTP(recorder, req) + + require.Equal(t, http.StatusTooManyRequests, recorder.Code, recorder.Body.String()) + require.Equal(t, []int64{801, 802}, upstream.accountHits()) + require.NotContains(t, recorder.Body.String(), "rate limited") + }) +} + func TestGrokOAuthCredentialFailoverAcrossHTTPHandlers(t *testing.T) { gin.SetMode(gin.TestMode) endpoints := []struct { @@ -667,9 +832,23 @@ func newGrokCredentialFailoverHandler(t *testing.T, mode string) (*OpenAIGateway }, }, } - if mode == "postmap_cancel" { + if mode == "postmap_cancel" || mode == "first_429" || mode == "all_429" || mode == "mixed_429_500" || mode == "mixed_500_429" || mode == "oauth_429_apikey_500" { accounts[0].Credentials["expires_at"] = time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339) } + if mode == "all_429" || mode == "mixed_429_500" || mode == "mixed_500_429" || mode == "oauth_429_apikey_500" { + accounts = append(accounts, service.Account{ + ID: 803, Name: "untried-healthy", Platform: service.PlatformGrok, Type: service.AccountTypeOAuth, + Status: service.StatusActive, Schedulable: true, Concurrency: 1, Priority: 3, + Credentials: map[string]any{ + "access_token": "untried-healthy-access", "refresh_token": "untried-healthy-refresh", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), + }, + }) + } + if mode == "oauth_429_apikey_500" { + accounts[1].Type = service.AccountTypeAPIKey + accounts[1].Credentials = map[string]any{"api_key": "third-party-key"} + } if mode == "all_revoked" { accounts[1].Credentials["expires_at"] = time.Now().Add(-time.Minute).UTC().Format(time.RFC3339) } @@ -694,6 +873,21 @@ func newGrokCredentialFailoverHandler(t *testing.T, mode string) (*OpenAIGateway provider.SetRefreshAPI(service.NewOAuthRefreshAPI(repo, tokenCache), refresher) } upstream := &grokCredentialHandlerUpstream{} + switch mode { + case "first_429": + upstream.rateLimitIDs = map[int64]bool{801: true} + case "all_429": + upstream.rateLimitIDs = map[int64]bool{801: true, 802: true} + case "mixed_429_500": + upstream.rateLimitIDs = map[int64]bool{801: true} + upstream.failureStatus = map[int64]int{802: http.StatusInternalServerError} + case "mixed_500_429": + upstream.failureStatus = map[int64]int{801: http.StatusInternalServerError} + upstream.rateLimitIDs = map[int64]bool{802: true} + case "oauth_429_apikey_500": + upstream.rateLimitIDs = map[int64]bool{801: true} + upstream.failureStatus = map[int64]int{802: http.StatusInternalServerError} + } cfg := &config.Config{RunMode: config.RunModeSimple} cfg.Gateway.MaxAccountSwitches = 3 billingCache := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil) diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 6db72c270b..33bef42cef 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -332,6 +332,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { failedAccountIDs := make(map[int64]struct{}) sameAccountRetryCount := make(map[int64]int) var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState for { if c.Request.Context().Err() != nil { @@ -487,7 +488,7 @@ func (h *OpenAIGatewayHandler) Responses(c *gin.Context) { return } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } @@ -844,6 +845,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { failedAccountIDs := make(map[int64]struct{}) sameAccountRetryCount := make(map[int64]int) var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState effectiveMappedModel := preferredMappedModel for { @@ -991,7 +993,7 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) { return } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { h.handleAnthropicFailoverExhausted(c, failoverErr, streamStarted) return } @@ -1496,6 +1498,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { switchCount := 0 failedAccountIDs := make(map[int64]struct{}) var lastFailoverErr *service.UpstreamFailoverError + var oauth429FailoverState service.OpenAIOAuth429FailoverState handleWSFailover := func(account *service.Account, failoverErr *service.UpstreamFailoverError) bool { if ctx.Err() != nil { return false @@ -1519,7 +1522,7 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { return false } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { closeOpenAIWSFailoverExhausted(wsConn, failoverErr) return false } diff --git a/backend/internal/handler/openai_images.go b/backend/internal/handler/openai_images.go index c5982fb7d1..d18af28966 100644 --- a/backend/internal/handler/openai_images.go +++ b/backend/internal/handler/openai_images.go @@ -145,6 +145,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { stopJSONKeepalive := func() {} jsonKeepaliveStarted := false defer func() { stopJSONKeepalive() }() + var oauth429FailoverState service.OpenAIOAuth429FailoverState for { reqLog.Debug("openai.images.account_selecting", zap.Int("excluded_account_count", len(failedAccountIDs))) @@ -299,7 +300,7 @@ func (h *OpenAIGatewayHandler) Images(c *gin.Context) { return } switchCount++ - if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount) { + if h.gatewayService.ShouldStopOpenAIOAuth429Failover(account, failoverErr.StatusCode, switchCount, &oauth429FailoverState) { h.handleFailoverExhausted(c, failoverErr, streamStarted) return } diff --git a/backend/internal/pkg/xai/oauth.go b/backend/internal/pkg/xai/oauth.go index a8a549c9dc..ea837fd78a 100644 --- a/backend/internal/pkg/xai/oauth.go +++ b/backend/internal/pkg/xai/oauth.go @@ -5,6 +5,7 @@ import ( "crypto/sha256" "encoding/base64" "encoding/hex" + "errors" "fmt" "net/url" "os" @@ -164,6 +165,24 @@ func ValidatedBaseURL(override string) (string, error) { return ValidateBaseURL(EffectiveBaseURL(override)) } +// BaseURLValidator applies the caller's outbound URL trust policy before xAI +// endpoint paths are appended. The service layer uses this for API-key accounts +// so the global security.url_allowlist policy remains the single source of +// truth; OAuth callers keep using the strict trusted-host validator. +type BaseURLValidator func(string) (string, error) + +func validatedBaseURLWithValidator(override string, validator BaseURLValidator) (string, error) { + if validator == nil { + return ValidatedBaseURL(override) + } + raw := EffectiveBaseURL(override) + validated, err := validator(raw) + if err != nil { + return "", err + } + return normalizeKnownBaseURLPath(validated) +} + type RuntimeSanityCheck struct { Value string `json:"value"` Valid bool `json:"valid"` @@ -282,7 +301,16 @@ func ValidateTrustedBaseURL(raw string) (string, error) { func normalizeKnownBaseURLPath(raw string) (string, error) { parsed, err := url.Parse(raw) if err != nil || parsed.Scheme == "" || parsed.Host == "" { - return "", fmt.Errorf("invalid url: %s", raw) + return "", errors.New("invalid base URL") + } + if parsed.User != nil { + return "", errors.New("base URL must not include userinfo") + } + if parsed.RawQuery != "" { + return "", errors.New("base URL must not include a query") + } + if parsed.Fragment != "" { + return "", errors.New("base URL must not include a fragment") } path := strings.TrimRight(parsed.Path, "/") if path == "" { @@ -435,7 +463,11 @@ func ParseAuthorizationInput(raw string) AuthorizationInput { } func BuildResponsesURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildResponsesURLWithValidator(baseURL, nil) +} + +func BuildResponsesURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -443,7 +475,11 @@ func BuildResponsesURL(baseURL string) (string, error) { } func BuildChatCompletionsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildChatCompletionsURLWithValidator(baseURL, nil) +} + +func BuildChatCompletionsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -451,7 +487,11 @@ func BuildChatCompletionsURL(baseURL string) (string, error) { } func BuildImagesGenerationsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildImagesGenerationsURLWithValidator(baseURL, nil) +} + +func BuildImagesGenerationsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -459,7 +499,11 @@ func BuildImagesGenerationsURL(baseURL string) (string, error) { } func BuildImagesEditsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildImagesEditsURLWithValidator(baseURL, nil) +} + +func BuildImagesEditsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -467,7 +511,11 @@ func BuildImagesEditsURL(baseURL string) (string, error) { } func BuildVideosGenerationsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildVideosGenerationsURLWithValidator(baseURL, nil) +} + +func BuildVideosGenerationsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -475,7 +523,11 @@ func BuildVideosGenerationsURL(baseURL string) (string, error) { } func BuildVideosEditsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildVideosEditsURLWithValidator(baseURL, nil) +} + +func BuildVideosEditsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -483,7 +535,11 @@ func BuildVideosEditsURL(baseURL string) (string, error) { } func BuildVideosExtensionsURL(baseURL string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildVideosExtensionsURLWithValidator(baseURL, nil) +} + +func BuildVideosExtensionsURLWithValidator(baseURL string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } @@ -491,7 +547,11 @@ func BuildVideosExtensionsURL(baseURL string) (string, error) { } func BuildVideoURL(baseURL, requestID string) (string, error) { - validatedBaseURL, err := ValidatedBaseURL(baseURL) + return BuildVideoURLWithValidator(baseURL, requestID, nil) +} + +func BuildVideoURLWithValidator(baseURL, requestID string, validator BaseURLValidator) (string, error) { + validatedBaseURL, err := validatedBaseURLWithValidator(baseURL, validator) if err != nil { return "", fmt.Errorf("invalid base url: %w", err) } diff --git a/backend/internal/pkg/xai/oauth_test.go b/backend/internal/pkg/xai/oauth_test.go index 39200ffc39..a82a26e299 100644 --- a/backend/internal/pkg/xai/oauth_test.go +++ b/backend/internal/pkg/xai/oauth_test.go @@ -6,6 +6,7 @@ import ( "net/url" "testing" + "github.com/Wei-Shaw/sub2api/internal/util/urlvalidator" "github.com/stretchr/testify/require" ) @@ -165,6 +166,44 @@ func TestValidateBaseURLAllowsPublicThirdPartyGrokAPI(t *testing.T) { require.Error(t, err) } +func TestBuildResponsesURLWithValidatorUsesCallerPolicy(t *testing.T) { + validator := func(raw string) (string, error) { + return urlvalidator.ValidateURLFormat(raw, true) + } + + target, err := BuildResponsesURLWithValidator("http://grok.example.test/v1/", validator) + require.NoError(t, err) + require.Equal(t, "http://grok.example.test/v1/responses", target) +} + +func TestBuildResponsesURLPreservesUnsafeOverrideCustomPath(t *testing.T) { + t.Setenv(EnvAllowUnsafeURLOverrides, "true") + + target, err := BuildResponsesURL("http://localhost:8080/custom") + require.NoError(t, err) + require.Equal(t, "http://localhost:8080/custom/responses", target) +} + +func TestBuildResponsesURLWithValidatorRejectsBaseURLComponents(t *testing.T) { + permissive := func(raw string) (string, error) { return raw, nil } + tests := []struct { + name string + raw string + }{ + {name: "userinfo", raw: "https://user:secret@grok.example.test/v1"}, + {name: "query", raw: "https://grok.example.test/v1?token=secret"}, + {name: "fragment", raw: "https://grok.example.test/v1#secret"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + _, err := BuildResponsesURLWithValidator(tt.raw, permissive) + require.Error(t, err) + require.NotContains(t, err.Error(), "secret") + }) + } +} + func TestValidateXAIURLsAllowUnsafeDevOverride(t *testing.T) { t.Setenv(EnvAllowUnsafeURLOverrides, "true") diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index a3eba2eaa9..8527b7010d 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -1377,6 +1377,35 @@ func (r *accountRepository) SetRateLimitedIfLater(ctx context.Context, id int64, return nil } +// ClearRateLimitIfObserved clears exactly the Grok rate-limit generation seen +// by a successful request. Matching both timestamps prevents a stale success +// from erasing a later clear/re-arm generation with an equal or shorter reset. +func (r *accountRepository) ClearRateLimitIfObserved(ctx context.Context, id int64, observedLimitedAt, observedResetAt time.Time) (bool, error) { + updated, err := r.client.Account.Update(). + Where( + dbaccount.IDEQ(id), + dbaccount.PlatformEQ(service.PlatformGrok), + dbaccount.TypeEQ(service.AccountTypeOAuth), + dbaccount.RateLimitedAtEQ(observedLimitedAt), + dbaccount.RateLimitResetAtEQ(observedResetAt), + ). + ClearRateLimitedAt(). + ClearRateLimitResetAt(). + Save(ctx) + if err != nil { + return false, err + } + if updated == 0 { + r.syncSchedulerAccountSnapshot(ctx, id) + return false, nil + } + if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventAccountChanged, &id, nil, nil); err != nil { + logger.LegacyPrintf("repository.account", "[SchedulerOutbox] enqueue observed rate-limit clear failed: account=%d err=%v", id, err) + } + r.syncSchedulerAccountSnapshot(ctx, id) + return true, nil +} + func (r *accountRepository) SetModelRateLimit(ctx context.Context, id int64, scope string, resetAt time.Time, reason ...string) error { if scope == "" { return nil diff --git a/backend/internal/repository/account_repo_integration_test.go b/backend/internal/repository/account_repo_integration_test.go index f82ad4ca28..ae519f3df4 100644 --- a/backend/internal/repository/account_repo_integration_test.go +++ b/backend/internal/repository/account_repo_integration_test.go @@ -722,6 +722,56 @@ func (s *AccountRepoSuite) TestSetRateLimitedIfLaterDoesNotShortenReset() { s.Require().WithinDuration(later, *cacheRecorder.setAccounts[1].RateLimitResetAt, time.Second) } +func (s *AccountRepoSuite) TestClearRateLimitIfObservedProtectsRearmed429Generation() { + account := mustCreateAccount(s.T(), s.client, &service.Account{ + Name: "acc-rl-conditional-clear", + Platform: service.PlatformGrok, + Type: service.AccountTypeOAuth, + }) + firstReset := time.Now().Add(30 * time.Minute).UTC().Truncate(time.Second) + rearmedReset := time.Now().Add(5 * time.Minute).UTC().Truncate(time.Second) + + s.Require().NoError(s.repo.SetRateLimitedIfLater(s.ctx, account.ID, firstReset)) + staleGeneration, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().NotNil(staleGeneration.RateLimitedAt) + s.Require().NotNil(staleGeneration.RateLimitResetAt) + cleared, err := s.repo.ClearRateLimitIfObserved(s.ctx, account.ID, *staleGeneration.RateLimitedAt, *staleGeneration.RateLimitResetAt) + s.Require().NoError(err) + s.Require().True(cleared) + + // A newer generation may legitimately re-arm a shorter boundary after the + // first generation was cleared. The stale success must not erase it. + s.Require().NoError(s.repo.SetRateLimitedIfLater(s.ctx, account.ID, rearmedReset)) + cleared, err = s.repo.ClearRateLimitIfObserved(s.ctx, account.ID, *staleGeneration.RateLimitedAt, *staleGeneration.RateLimitResetAt) + s.Require().NoError(err) + s.Require().False(cleared) + + got, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().NotNil(got.RateLimitedAt) + s.Require().NotNil(got.RateLimitResetAt) + s.Require().WithinDuration(rearmedReset, *got.RateLimitResetAt, time.Second) + + // An admin can retype the row while the successful OAuth request is still + // in flight. The stale OAuth recovery must not cross into API-key state even + // when both observed timestamps still match. + _, err = s.client.Account.UpdateOneID(account.ID). + SetType(service.AccountTypeAPIKey). + Save(s.ctx) + s.Require().NoError(err) + cleared, err = s.repo.ClearRateLimitIfObserved(s.ctx, account.ID, *got.RateLimitedAt, *got.RateLimitResetAt) + s.Require().NoError(err) + s.Require().False(cleared) + + retyped, err := s.repo.GetByID(s.ctx, account.ID) + s.Require().NoError(err) + s.Require().Equal(service.AccountTypeAPIKey, retyped.Type) + s.Require().NotNil(retyped.RateLimitedAt) + s.Require().NotNil(retyped.RateLimitResetAt) + s.Require().WithinDuration(rearmedReset, *retyped.RateLimitResetAt, time.Second) +} + func (s *AccountRepoSuite) TestClearRateLimit() { account := mustCreateAccount(s.T(), s.client, &service.Account{Name: "acc-clear"}) until := time.Now().Add(1 * time.Hour) diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index a9eef998e4..a739bcc120 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -695,7 +695,7 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account * return s.sendErrorAndEnd(c, fmt.Sprintf("Unsupported Grok account type: %s", account.Type)) } - apiURL, err := xai.BuildResponsesURL(account.GetGrokBaseURL()) + apiURL, err := buildGrokResponsesURL(account, s.cfg) if err != nil { return s.sendErrorAndEnd(c, fmt.Sprintf("Invalid Grok base URL: %s", err.Error())) } @@ -742,7 +742,7 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account * now := time.Now() snapshot := parseGrokQuotaSnapshot(resp.Header, resp.StatusCode, now) if snapshot != nil && s.accountRepo != nil { - resetAt, limited := grokRateLimitResetAt(snapshot, now) + resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, now) if limited { normalizeGrokExhaustedWindowResets(snapshot, resetAt, now) } @@ -751,7 +751,11 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account * }) if limited { persistGrokRateLimit(ctx, s.accountRepo, account, resetAt) + } else if isSuccessfulGrokRateLimitRecovery(account, snapshot) { + clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) } + } else if s.accountRepo != nil && isSuccessfulGrokRateLimitRecovery(account, &xai.QuotaSnapshot{StatusCode: resp.StatusCode}) { + clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) } if resp.StatusCode != http.StatusOK { diff --git a/backend/internal/service/grok_media.go b/backend/internal/service/grok_media.go index 5cc8e2d05e..f7c6bd8153 100644 --- a/backend/internal/service/grok_media.go +++ b/backend/internal/service/grok_media.go @@ -13,7 +13,6 @@ import ( "strings" "time" - "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" @@ -268,25 +267,6 @@ func (s *OpenAIGatewayService) BindGrokMediaVideoRequestAccount(ctx context.Cont return s.BindStickySession(ctx, groupID, GrokMediaVideoRequestSessionHash(requestID), accountID) } -func (e GrokMediaEndpoint) upstreamURL(baseURL, requestID string) (string, error) { - switch e { - case GrokMediaEndpointImagesGenerations: - return xai.BuildImagesGenerationsURL(baseURL) - case GrokMediaEndpointImagesEdits: - return xai.BuildImagesEditsURL(baseURL) - case GrokMediaEndpointVideosGenerations: - return xai.BuildVideosGenerationsURL(baseURL) - case GrokMediaEndpointVideosEdits: - return xai.BuildVideosEditsURL(baseURL) - case GrokMediaEndpointVideosExtensions: - return xai.BuildVideosExtensionsURL(baseURL) - case GrokMediaEndpointVideoStatus: - return xai.BuildVideoURL(baseURL, requestID) - default: - return "", fmt.Errorf("unsupported grok media endpoint: %s", e) - } -} - func (s *OpenAIGatewayService) ForwardGrokMedia( ctx context.Context, c *gin.Context, @@ -308,7 +288,7 @@ func (s *OpenAIGatewayService) ForwardGrokMedia( if err != nil { return nil, err } - targetURL, err := endpoint.upstreamURL(account.GetGrokMediaBaseURL(), requestID) + targetURL, err := buildGrokMediaURL(account, s.cfg, endpoint, requestID) if err != nil { return nil, err } @@ -368,7 +348,7 @@ func (s *OpenAIGatewayService) ForwardGrokMedia( return s.handleGrokMediaErrorResponse(ctx, resp, c, account, requestIDHeader, requestModel) } - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) respBody, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, openAITooLargeError) if err != nil { return nil, err diff --git a/backend/internal/service/grok_quota_service.go b/backend/internal/service/grok_quota_service.go index ef8e3e4c03..a95b778707 100644 --- a/backend/internal/service/grok_quota_service.go +++ b/backend/internal/service/grok_quota_service.go @@ -135,7 +135,7 @@ func (s *GrokQuotaService) probeUsage(ctx context.Context, accountID int64) (*Gr if err != nil { return nil, infraerrors.Newf(http.StatusBadRequest, "GROK_QUOTA_PROBE_BODY_ERROR", "failed to build probe body: %v", err) } - targetURL, err := xai.BuildResponsesURL(account.GetGrokBaseURL()) + targetURL, err := buildGrokResponsesURL(account, nil) if err != nil { return nil, infraerrors.Newf(http.StatusBadRequest, "GROK_QUOTA_BASE_URL_INVALID", "invalid Grok base_url: %v", err) } @@ -160,7 +160,7 @@ func (s *GrokQuotaService) probeUsage(ctx context.Context, accountID int64) (*Gr defer func() { _ = resp.Body.Close() }() snapshot := xai.ObserveQuotaHeaders(resp.Header, resp.StatusCode, "active_probe") - resetAt, limited := grokRateLimitResetAt(snapshot, time.Now()) + resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, time.Now()) if limited { normalizeGrokExhaustedWindowResets(snapshot, resetAt, time.Now()) } @@ -169,6 +169,8 @@ func (s *GrokQuotaService) probeUsage(ctx context.Context, accountID int64) (*Gr }) if limited { persistGrokRateLimit(ctx, s.accountRepo, account, resetAt) + } else if isSuccessfulGrokRateLimitRecovery(account, snapshot) { + clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) } result := &GrokQuotaProbeResult{ diff --git a/backend/internal/service/grok_quota_service_test.go b/backend/internal/service/grok_quota_service_test.go index 4e06fe156c..ad3c85ba19 100644 --- a/backend/internal/service/grok_quota_service_test.go +++ b/backend/internal/service/grok_quota_service_test.go @@ -32,6 +32,10 @@ type grokQuotaAccountRepo struct { lastTempUnschedID int64 lastTempUnschedUntil time.Time lastTempUnschedReason string + recoveryClearCalls int + recoveryObservedAt time.Time + recoveryObservedReset time.Time + recoveryClearResult bool } func (r *grokQuotaAccountRepo) UpdateExtra(_ context.Context, id int64, updates map[string]any) error { @@ -54,6 +58,13 @@ func (r *grokQuotaAccountRepo) SetRateLimitedIfLater(ctx context.Context, id int return r.SetRateLimited(ctx, id, resetAt) } +func (r *grokQuotaAccountRepo) ClearRateLimitIfObserved(_ context.Context, _ int64, observedLimitedAt, observedResetAt time.Time) (bool, error) { + r.recoveryClearCalls++ + r.recoveryObservedAt = observedLimitedAt + r.recoveryObservedReset = observedResetAt + return r.recoveryClearResult, nil +} + func (r *grokQuotaAccountRepo) SetTempUnschedulable(_ context.Context, id int64, until time.Time, reason string) error { r.tempUnschedCalls++ r.lastTempUnschedID = id @@ -375,10 +386,15 @@ func TestGrokQuotaServiceProbeUsageStoresNoHeadersState(t *testing.T) { t.Parallel() account := healthyGrokQuotaOAuthAccount(45) + observedResetAt := time.Now().Add(-time.Second).UTC().Truncate(time.Second) + observedLimitedAt := observedResetAt.Add(-grokRateLimitRepeatCooldown) + account.RateLimitedAt = &observedLimitedAt + account.RateLimitResetAt = &observedResetAt repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{45: account}, }, + recoveryClearResult: true, } upstream := &httpUpstreamRecorder{resp: &http.Response{ StatusCode: http.StatusOK, @@ -401,6 +417,9 @@ func TestGrokQuotaServiceProbeUsageStoresNoHeadersState(t *testing.T) { require.True(t, ok) require.False(t, stored.HeadersObserved) require.Equal(t, http.StatusOK, stored.StatusCode) + require.Equal(t, 1, repo.recoveryClearCalls) + require.Equal(t, observedLimitedAt, repo.recoveryObservedAt) + require.Equal(t, observedResetAt, repo.recoveryObservedReset) } func TestGrokQuotaServiceProbeUsageReturnsRateLimitedSnapshot(t *testing.T) { diff --git a/backend/internal/service/grok_upstream_url.go b/backend/internal/service/grok_upstream_url.go new file mode 100644 index 0000000000..ca2ba6b64d --- /dev/null +++ b/backend/internal/service/grok_upstream_url.go @@ -0,0 +1,90 @@ +package service + +import ( + "errors" + "fmt" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + "github.com/Wei-Shaw/sub2api/internal/util/urlvalidator" +) + +func grokBaseURLValidator(account *Account, cfg *config.Config) (xai.BaseURLValidator, error) { + if account == nil || !account.IsGrok() { + return nil, fmt.Errorf("grok account is required") + } + switch account.Type { + case AccountTypeOAuth: + // Subscription credentials are never governed by the operator's API-key + // URL policy. They stay pinned to the supported CLI gateway. + return redactedGrokBaseURLValidator(xai.ValidateTrustedBaseURL), nil + case AccountTypeAPIKey: + if cfg == nil { + return redactedGrokBaseURLValidator(xai.ValidateBaseURL), nil + } + if !cfg.Security.URLAllowlist.Enabled { + return redactedGrokBaseURLValidator(func(raw string) (string, error) { + return urlvalidator.ValidateURLFormat(raw, cfg.Security.URLAllowlist.AllowInsecureHTTP) + }), nil + } + return redactedGrokBaseURLValidator(func(raw string) (string, error) { + return urlvalidator.ValidateHTTPSURL(raw, urlvalidator.ValidationOptions{ + AllowedHosts: cfg.Security.URLAllowlist.UpstreamHosts, + RequireAllowlist: true, + AllowPrivate: cfg.Security.URLAllowlist.AllowPrivateHosts, + }) + }), nil + default: + return nil, fmt.Errorf("unsupported grok account type: %s", account.Type) + } +} + +func redactedGrokBaseURLValidator(validator xai.BaseURLValidator) xai.BaseURLValidator { + return func(raw string) (string, error) { + validated, err := validator(raw) + if err != nil { + return "", errors.New("base URL rejected by URL security policy") + } + return validated, nil + } +} + +func buildGrokResponsesURL(account *Account, cfg *config.Config) (string, error) { + validator, err := grokBaseURLValidator(account, cfg) + if err != nil { + return "", err + } + return xai.BuildResponsesURLWithValidator(account.GetGrokBaseURL(), validator) +} + +func buildGrokChatCompletionsURL(account *Account, cfg *config.Config) (string, error) { + validator, err := grokBaseURLValidator(account, cfg) + if err != nil { + return "", err + } + return xai.BuildChatCompletionsURLWithValidator(account.GetGrokBaseURL(), validator) +} + +func buildGrokMediaURL(account *Account, cfg *config.Config, endpoint GrokMediaEndpoint, requestID string) (string, error) { + validator, err := grokBaseURLValidator(account, cfg) + if err != nil { + return "", err + } + baseURL := account.GetGrokMediaBaseURL() + switch endpoint { + case GrokMediaEndpointImagesGenerations: + return xai.BuildImagesGenerationsURLWithValidator(baseURL, validator) + case GrokMediaEndpointImagesEdits: + return xai.BuildImagesEditsURLWithValidator(baseURL, validator) + case GrokMediaEndpointVideosGenerations: + return xai.BuildVideosGenerationsURLWithValidator(baseURL, validator) + case GrokMediaEndpointVideosEdits: + return xai.BuildVideosEditsURLWithValidator(baseURL, validator) + case GrokMediaEndpointVideosExtensions: + return xai.BuildVideosExtensionsURLWithValidator(baseURL, validator) + case GrokMediaEndpointVideoStatus: + return xai.BuildVideoURLWithValidator(baseURL, requestID, validator) + default: + return "", fmt.Errorf("unsupported grok media endpoint: %s", endpoint) + } +} diff --git a/backend/internal/service/grok_upstream_url_test.go b/backend/internal/service/grok_upstream_url_test.go new file mode 100644 index 0000000000..7919e47202 --- /dev/null +++ b/backend/internal/service/grok_upstream_url_test.go @@ -0,0 +1,122 @@ +//go:build unit + +package service + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/xai" + "github.com/stretchr/testify/require" +) + +func TestGrokAPIKeyURLPolicyFollowsGlobalSecurityConfig(t *testing.T) { + account := &Account{ + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "base_url": "http://grok.example.test/v1", + }, + } + + t.Run("insecure HTTP enabled with allowlist disabled", func(t *testing.T) { + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + + responsesURL, err := buildGrokResponsesURL(account, cfg) + require.NoError(t, err) + require.Equal(t, "http://grok.example.test/v1/responses", responsesURL) + + chatURL, err := buildGrokChatCompletionsURL(account, cfg) + require.NoError(t, err) + require.Equal(t, "http://grok.example.test/v1/chat/completions", chatURL) + + mediaURL, err := buildGrokMediaURL(account, cfg, GrokMediaEndpointImagesGenerations, "") + require.NoError(t, err) + require.Equal(t, "http://grok.example.test/v1/images/generations", mediaURL) + }) + + t.Run("insecure HTTP disabled", func(t *testing.T) { + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = false + + _, err := buildGrokResponsesURL(account, cfg) + require.EqualError(t, err, "invalid base url: base URL rejected by URL security policy") + }) + + t.Run("enabled allowlist remains HTTPS only", func(t *testing.T) { + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = true + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Security.URLAllowlist.UpstreamHosts = []string{"grok.example.test"} + + _, err := buildGrokResponsesURL(account, cfg) + require.EqualError(t, err, "invalid base url: base URL rejected by URL security policy") + }) +} + +func TestGrokAPIKeyURLPolicyAppliesAllowlistAndPrivateHostControls(t *testing.T) { + account := &Account{ + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "base_url": "https://grok.example.test/v1", + }, + } + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = true + cfg.Security.URLAllowlist.UpstreamHosts = []string{"grok.example.test"} + + target, err := buildGrokResponsesURL(account, cfg) + require.NoError(t, err) + require.Equal(t, "https://grok.example.test/v1/responses", target) + + cfg.Security.URLAllowlist.UpstreamHosts = []string{"other.example.test"} + _, err = buildGrokResponsesURL(account, cfg) + require.EqualError(t, err, "invalid base url: base URL rejected by URL security policy") + + account.Credentials["base_url"] = "https://127.0.0.1/v1" + cfg.Security.URLAllowlist.UpstreamHosts = []string{"127.0.0.1"} + _, err = buildGrokResponsesURL(account, cfg) + require.EqualError(t, err, "invalid base url: base URL rejected by URL security policy") + + cfg.Security.URLAllowlist.AllowPrivateHosts = true + target, err = buildGrokResponsesURL(account, cfg) + require.NoError(t, err) + require.Equal(t, "https://127.0.0.1/v1/responses", target) +} + +func TestGrokAPIKeyURLPolicyRedactsMalformedConfiguredURL(t *testing.T) { + account := &Account{ + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "base_url": "https://%zz:secret@grok.example.test/v1", + }, + } + cfg := &config.Config{} + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + + _, err := buildGrokResponsesURL(account, cfg) + require.EqualError(t, err, "invalid base url: base URL rejected by URL security policy") + require.NotContains(t, err.Error(), "secret") +} + +func TestGrokOAuthURLPolicyIgnoresAPIKeyOverrides(t *testing.T) { + account := &Account{ + Platform: PlatformGrok, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "base_url": "http://attacker.example.test/v1", + }, + } + cfg := &config.Config{} + cfg.Security.URLAllowlist.Enabled = false + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + + target, err := buildGrokResponsesURL(account, cfg) + require.NoError(t, err) + require.Equal(t, xai.DefaultCLIBaseURL+"/responses", target) +} diff --git a/backend/internal/service/openai_account_runtime_block_fastpath.go b/backend/internal/service/openai_account_runtime_block_fastpath.go index 978b740a56..00d971ba22 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath.go @@ -16,6 +16,13 @@ const ( openAIOAuth429StormMaxAccountSwitches = 1 ) +// OpenAIOAuth429FailoverState tracks the request-local follow-up budget after +// the first Grok OAuth 429. Once that 429 occurs, exactly one different account +// may be attempted; any failure from that follow-up account ends failover. +type OpenAIOAuth429FailoverState struct { + grokOAuth429FollowupPending bool +} + func openAIAccountStateContext(ctx context.Context) (context.Context, context.CancelFunc) { base := context.Background() if ctx != nil { @@ -210,14 +217,28 @@ func (s *OpenAIGatewayService) isOpenAIOAuth429Storm() bool { return s.openaiOAuth429WindowCount.Load() >= openAIOAuth429StormThreshold } -func (s *OpenAIGatewayService) ShouldStopOpenAIOAuth429Failover(account *Account, statusCode int, failedSwitches int) bool { - if statusCode != http.StatusTooManyRequests || failedSwitches < openAIOAuth429StormMaxAccountSwitches { +func (s *OpenAIGatewayService) ShouldStopOpenAIOAuth429Failover(account *Account, statusCode int, failedSwitches int, state *OpenAIOAuth429FailoverState) bool { + if failedSwitches < openAIOAuth429StormMaxAccountSwitches { return false } - if isGrokOAuthAccount(account) { + if state != nil && state.grokOAuth429FollowupPending { + // The follow-up budget was armed by a Grok OAuth 429. Consume it on + // any failing follow-up account, even if a mixed pool selected an API-key + // account next. return true } - if !isOpenAIOAuthAccount(account) { + if isGrokOAuthAccount(account) { + if state == nil { + // Preserve the old threshold for callers that have not adopted the + // request-local state contract yet. + return statusCode == http.StatusTooManyRequests && failedSwitches >= 2 + } + if statusCode == http.StatusTooManyRequests { + state.grokOAuth429FollowupPending = true + } + return false + } + if statusCode != http.StatusTooManyRequests || !isOpenAIOAuthAccount(account) { return false } return s.isOpenAIOAuth429Storm() diff --git a/backend/internal/service/openai_account_runtime_block_fastpath_test.go b/backend/internal/service/openai_account_runtime_block_fastpath_test.go index a51c13c531..7d7cfbda50 100644 --- a/backend/internal/service/openai_account_runtime_block_fastpath_test.go +++ b/backend/internal/service/openai_account_runtime_block_fastpath_test.go @@ -135,26 +135,45 @@ func TestShouldStopOpenAIOAuth429Failover_OnlyDuringStorm(t *testing.T) { svc := &OpenAIGatewayService{} account := &Account{ID: 42, Platform: PlatformOpenAI, Type: AccountTypeOAuth} apiKeyAccount := &Account{ID: 43, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + var state OpenAIOAuth429FailoverState - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1, &state)) for i := 0; i < openAIOAuth429StormThreshold; i++ { svc.recordOpenAIOAuth429() } - require.True(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(apiKeyAccount, http.StatusTooManyRequests, 1)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusInternalServerError, 1)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 0)) + require.True(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1, &state)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(apiKeyAccount, http.StatusTooManyRequests, 1, &state)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusInternalServerError, 1, &state)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 0, &state)) } -func TestShouldStopOpenAIOAuth429Failover_StopsGrokAfterFirst429Switch(t *testing.T) { +func TestShouldStopOpenAIOAuth429Failover_TracksOneGrokFollowupAttempt(t *testing.T) { svc := &OpenAIGatewayService{} account := &Account{ID: 44, Platform: PlatformGrok, Type: AccountTypeOAuth} apiKeyAccount := &Account{ID: 45, Platform: PlatformGrok, Type: AccountTypeAPIKey} - require.True(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 0)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(apiKeyAccount, http.StatusTooManyRequests, 1)) - require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusInternalServerError, 1)) + t.Run("429 then 500 stops after one followup", func(t *testing.T) { + var state OpenAIOAuth429FailoverState + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1, &state)) + require.True(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusInternalServerError, 2, &state)) + }) + + t.Run("500 then 429 still allows one followup", func(t *testing.T) { + var state OpenAIOAuth429FailoverState + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusInternalServerError, 1, &state)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 2, &state)) + require.True(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusBadGateway, 3, &state)) + }) + + t.Run("OAuth 429 then API-key failure consumes the same followup", func(t *testing.T) { + var state OpenAIOAuth429FailoverState + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 1, &state)) + require.True(t, svc.ShouldStopOpenAIOAuth429Failover(apiKeyAccount, http.StatusInternalServerError, 2, &state)) + }) + + var state OpenAIOAuth429FailoverState + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(account, http.StatusTooManyRequests, 0, &state)) + require.False(t, svc.ShouldStopOpenAIOAuth429Failover(apiKeyAccount, http.StatusTooManyRequests, 2, &state)) } diff --git a/backend/internal/service/openai_gateway_chat_completions_raw.go b/backend/internal/service/openai_gateway_chat_completions_raw.go index 095d544f89..800d53be32 100644 --- a/backend/internal/service/openai_gateway_chat_completions_raw.go +++ b/backend/internal/service/openai_gateway_chat_completions_raw.go @@ -9,7 +9,6 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" - "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" @@ -202,7 +201,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( } if account.Platform == PlatformGrok { - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) } // 8. Forward response @@ -222,7 +221,7 @@ func (s *OpenAIGatewayService) forwardAsRawChatCompletions( func (s *OpenAIGatewayService) rawChatCompletionsURL(account *Account) (string, error) { if account.Platform == PlatformGrok { - targetURL, err := xai.BuildChatCompletionsURL(account.GetGrokBaseURL()) + targetURL, err := buildGrokChatCompletionsURL(account, s.cfg) if err != nil { return "", fmt.Errorf("invalid grok base_url: %w", err) } diff --git a/backend/internal/service/openai_gateway_grok.go b/backend/internal/service/openai_gateway_grok.go index 675b4bc9f9..92cf2910c6 100644 --- a/backend/internal/service/openai_gateway_grok.go +++ b/backend/internal/service/openai_gateway_grok.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/gin-gonic/gin" @@ -25,6 +26,10 @@ const ( grokCLIVersion = "0.2.93" grokDefaultResponsesModel = "grok-4.5" grokRateLimitFallbackCooldown = 2 * time.Minute + grokRateLimitRepeatCooldown = 10 * time.Minute + grokRateLimitSustainedCooldown = 30 * time.Minute + grokRateLimitMaxAdaptiveCooldown = time.Hour + grokRateLimitBackoffQuietPeriod = time.Hour ) func (s *OpenAIGatewayService) forwardGrokResponses( @@ -61,7 +66,7 @@ func (s *OpenAIGatewayService) forwardGrokResponses( upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) defer releaseUpstreamCtx() - upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, patchedBody, token, cacheIdentity) + upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, patchedBody, token, cacheIdentity, s.cfg) if err != nil { return nil, err } @@ -107,7 +112,7 @@ func (s *OpenAIGatewayService) forwardGrokResponses( return s.handleErrorResponse(ctx, resp, c, account, patchedBody, upstreamModel) } - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) var usage *OpenAIUsage var firstTokenMs *int @@ -574,7 +579,7 @@ func (s *OpenAIGatewayService) describeGrokComposerImage( upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) // Image-description probes are auxiliary requests, not conversation turns. // Do not bind them to the caller's Grok prompt-cache identity. - upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, body, token, "") + upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, body, token, "", s.cfg) releaseUpstreamCtx() if err != nil { return "", OpenAIUsage{}, fmt.Errorf("build grok composer image bridge request: %w", err) @@ -618,7 +623,7 @@ func (s *OpenAIGatewayService) describeGrokComposerImage( return "", OpenAIUsage{}, fmt.Errorf("grok composer image bridge upstream error: %s", upstreamMsg) } - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) respBody, err := ReadUpstreamResponseBody(resp.Body, s.cfg, c, nil) if err != nil { return "", OpenAIUsage{}, fmt.Errorf("read grok composer image bridge response: %w", err) @@ -740,8 +745,8 @@ func addOpenAIUsage(dst *OpenAIUsage, usage OpenAIUsage) { dst.ImageOutputTokens += usage.ImageOutputTokens } -func buildGrokResponsesRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token, cacheIdentity string) (*http.Request, error) { - targetURL, err := xai.BuildResponsesURL(account.GetGrokBaseURL()) +func buildGrokResponsesRequest(ctx context.Context, c *gin.Context, account *Account, body []byte, token, cacheIdentity string, cfg *config.Config) (*http.Request, error) { + targetURL, err := buildGrokResponsesURL(account, cfg) if err != nil { return nil, err } @@ -780,11 +785,12 @@ func (s *OpenAIGatewayService) updateGrokUsageSnapshot(ctx context.Context, acco } accountID := account.ID now := time.Now() - resetAt, hasActiveLimit := grokRateLimitResetAt(snapshot, now) + resetAt, hasActiveLimit := grokRateLimitResetAtForAccount(account, snapshot, now) if hasActiveLimit { normalizeGrokExhaustedWindowResets(snapshot, resetAt, now) } - critical := snapshot.StatusCode == http.StatusTooManyRequests || hasActiveLimit + recovery := isSuccessfulGrokRateLimitRecovery(account, snapshot) + critical := snapshot.StatusCode == http.StatusTooManyRequests || hasActiveLimit || recovery if s.codexSnapshotThrottle != nil { allowed := s.codexSnapshotThrottle.Allow(accountID, now) if !critical && !allowed { @@ -810,6 +816,23 @@ func (s *OpenAIGatewayService) updateGrokUsageSnapshot(ctx context.Context, acco // on the passive snapshot scheduler check. if hasActiveLimit { s.rateLimitGrok(stateCtx, account, resetAt) + } else if recovery { + clearGrokRateLimitAfterRecovery(stateCtx, s.accountRepo, account) + } +} + +func (s *OpenAIGatewayService) updateGrokUsageFromResponse(ctx context.Context, account *Account, headers http.Header, statusCode int) { + snapshot := parseGrokQuotaSnapshot(headers, statusCode, time.Now()) + if snapshot != nil { + s.updateGrokUsageSnapshot(ctx, account, snapshot) + return + } + // Successful responses are recovery evidence even when the upstream omits + // optional quota headers. Do not replace an informative stored snapshot with + // an empty one; only clear the exact observed cooldown generation. + recoverySnapshot := &xai.QuotaSnapshot{StatusCode: statusCode} + if isSuccessfulGrokRateLimitRecovery(account, recoverySnapshot) { + clearGrokRateLimitAfterRecovery(ctx, s.accountRepo, account) } } @@ -900,6 +923,37 @@ func grokRateLimitResetAt(snapshot *xai.QuotaSnapshot, now time.Time) (time.Time return time.Time{}, false } +func grokRateLimitResetAtForAccount(account *Account, snapshot *xai.QuotaSnapshot, now time.Time) (time.Time, bool) { + resetAt, limited := grokRateLimitResetAt(snapshot, now) + if !limited || !isGrokOAuthAccount(account) || snapshot == nil || snapshot.StatusCode != http.StatusTooManyRequests { + return resetAt, limited + } + if account.RateLimitedAt == nil || account.RateLimitResetAt == nil { + return resetAt, true + } + previousResetAt := *account.RateLimitResetAt + if previousResetAt.After(now) || now.Sub(previousResetAt) > grokRateLimitBackoffQuietPeriod { + return resetAt, true + } + previousCooldown := previousResetAt.Sub(*account.RateLimitedAt) + if previousCooldown <= 0 { + return resetAt, true + } + + adaptiveCooldown := grokRateLimitRepeatCooldown + switch { + case previousCooldown >= grokRateLimitSustainedCooldown: + adaptiveCooldown = grokRateLimitMaxAdaptiveCooldown + case previousCooldown >= grokRateLimitRepeatCooldown: + adaptiveCooldown = grokRateLimitSustainedCooldown + } + adaptiveResetAt := now.Add(adaptiveCooldown) + if adaptiveResetAt.After(resetAt) { + resetAt = adaptiveResetAt + } + return resetAt, true +} + func normalizeGrokRateLimitResetAt(account *Account, resetAt, now time.Time) time.Time { if !resetAt.After(now) { resetAt = now.Add(grokRateLimitFallbackCooldown) @@ -914,6 +968,33 @@ type grokRateLimitExtendingRepository interface { SetRateLimitedIfLater(ctx context.Context, id int64, resetAt time.Time) error } +type grokRateLimitRecoveryRepository interface { + ClearRateLimitIfObserved(ctx context.Context, id int64, observedLimitedAt, observedResetAt time.Time) (bool, error) +} + +func isSuccessfulGrokRateLimitRecovery(account *Account, snapshot *xai.QuotaSnapshot) bool { + return isGrokOAuthAccount(account) && + account.RateLimitedAt != nil && + account.RateLimitResetAt != nil && + snapshot != nil && + snapshot.StatusCode >= http.StatusOK && + snapshot.StatusCode < http.StatusMultipleChoices +} + +func clearGrokRateLimitAfterRecovery(ctx context.Context, repo AccountRepository, account *Account) { + if repo == nil || account == nil || account.RateLimitedAt == nil || account.RateLimitResetAt == nil || ctx.Err() != nil { + return + } + recoveryRepo, ok := repo.(grokRateLimitRecoveryRepository) + if !ok { + return + } + _, err := recoveryRepo.ClearRateLimitIfObserved(ctx, account.ID, *account.RateLimitedAt, *account.RateLimitResetAt) + if err != nil { + slog.Warn("grok_rate_limit_recovery_clear_failed", "account_id", account.ID, "error", err) + } +} + func persistGrokRateLimit(ctx context.Context, repo AccountRepository, account *Account, resetAt time.Time) { if repo == nil || account == nil || account.ID <= 0 { return diff --git a/backend/internal/service/openai_gateway_grok_chat_bridge.go b/backend/internal/service/openai_gateway_grok_chat_bridge.go index fe9cfb09fd..6fd58b2db1 100644 --- a/backend/internal/service/openai_gateway_grok_chat_bridge.go +++ b/backend/internal/service/openai_gateway_grok_chat_bridge.go @@ -10,7 +10,6 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" - "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/gin-gonic/gin" ) @@ -258,7 +257,7 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( return nil, fmt.Errorf("get grok access token: %w", err) } upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) - upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, responsesBody, token, cacheIdentity) + upstreamReq, err := buildGrokResponsesRequest(upstreamCtx, c, account, responsesBody, token, cacheIdentity, s.cfg) releaseUpstreamCtx() if err != nil { return nil, fmt.Errorf("build grok responses bridge request: %w", err) @@ -301,7 +300,7 @@ func (s *OpenAIGatewayService) forwardGrokChatCompletionsViaResponses( return s.handleChatCompletionsErrorResponse(resp, c, account, billingModel) } - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) var result *OpenAIForwardResult if clientStream { diff --git a/backend/internal/service/openai_gateway_grok_test.go b/backend/internal/service/openai_gateway_grok_test.go index 4f7ed05edf..d93415b2e0 100644 --- a/backend/internal/service/openai_gateway_grok_test.go +++ b/backend/internal/service/openai_gateway_grok_test.go @@ -256,7 +256,7 @@ func TestBuildGrokResponsesRequestUsesAccountBaseURLAndBearerToken(t *testing.T) }, } - req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "access-token", "isolated-cache-id") + req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "access-token", "isolated-cache-id", nil) require.NoError(t, err) require.Equal(t, http.MethodPost, req.Method) require.Equal(t, xai.DefaultCLIBaseURL+"/responses", req.URL.String()) @@ -280,7 +280,7 @@ func TestBuildGrokResponsesRequestAllowsPublicAPIKeyBaseURLByDefault(t *testing. }, } - req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "api-key", "") + req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "api-key", "", nil) require.NoError(t, err) require.Equal(t, "https://grok.example.test/v1/responses", req.URL.String()) require.Equal(t, "Bearer api-key", req.Header.Get("Authorization")) @@ -299,7 +299,7 @@ func TestBuildGrokResponsesRequestPinsOAuthCustomBaseURLByDefault(t *testing.T) }, } - req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "access-token", "") + req, err := buildGrokResponsesRequest(context.Background(), nil, account, []byte(`{"model":"grok-4.3"}`), "access-token", "", nil) require.NoError(t, err) require.Equal(t, xai.DefaultCLIBaseURL+"/responses", req.URL.String()) } @@ -1077,6 +1077,41 @@ func TestAccountTestServiceGrokAPIKeyUsesXAIResponses(t *testing.T) { require.Contains(t, recorder.Body.String(), `"type":"test_complete"`) } +func TestAccountTestServiceGrokAPIKeyAllowsConfiguredHTTPWhenGlobalPolicyDoes(t *testing.T) { + gin.SetMode(gin.TestMode) + + account := &Account{ + ID: 55, + Name: "grok-api-key-http", + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + Concurrency: 1, + Credentials: map[string]any{ + "api_key": "third-party-key", + "base_url": "http://grok.example.test/v1", + }, + } + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader( + "data: {\"type\":\"response.output_text.delta\",\"delta\":\"ok\"}\n\n" + + "data: {\"type\":\"response.completed\"}\n\n", + )), + }} + svc := &AccountTestService{cfg: rawChatCompletionsTestConfig(), httpUpstream: upstream} + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/55/test", nil) + + err := svc.testGrokAccountConnection(c, account, "grok") + require.NoError(t, err) + require.Equal(t, "http://grok.example.test/v1/responses", upstream.lastReq.URL.String()) + require.Equal(t, "Bearer third-party-key", upstream.lastReq.Header.Get("Authorization")) + require.Empty(t, upstream.lastReq.Header.Get("X-Grok-Client-Version")) + require.Contains(t, recorder.Body.String(), `"type":"test_complete"`) +} + func TestForwardAsChatCompletionsForGrokStreamingUsesRawXAIChatCompletions(t *testing.T) { gin.SetMode(gin.TestMode) @@ -1144,10 +1179,15 @@ func TestForwardGrokResponsesNonStreamingUsesCacheIdentityAndCachedUsage(t *test c.Set("api_key", &APIKey{ID: 5202}) account := healthyGrokOAuthGatewayTestAccount(56, "access-token") + observedResetAt := time.Now().Add(-time.Second).UTC().Truncate(time.Second) + observedLimitedAt := observedResetAt.Add(-grokRateLimitRepeatCooldown) + account.RateLimitedAt = &observedLimitedAt + account.RateLimitResetAt = &observedResetAt repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{56: account}, }, + recoveryClearResult: true, } upstream := &httpUpstreamRecorder{resp: &http.Response{ StatusCode: http.StatusOK, @@ -1180,6 +1220,9 @@ func TestForwardGrokResponsesNonStreamingUsesCacheIdentityAndCachedUsage(t *test require.False(t, gjson.GetBytes(upstream.lastBody, "tools").Exists()) require.False(t, gjson.GetBytes(upstream.lastBody, "tool_choice").Exists()) require.Equal(t, "resp_grok_non_stream", gjson.Get(recorder.Body.String(), "id").String()) + require.Equal(t, 1, repo.recoveryClearCalls) + require.Equal(t, observedLimitedAt, repo.recoveryObservedAt) + require.Equal(t, observedResetAt, repo.recoveryObservedReset) } func TestForwardGrokResponsesFailoverKeepsCacheIdentityAcrossAccounts(t *testing.T) { @@ -1565,6 +1608,102 @@ func TestHandleGrokAccountUpstreamError429UsesFallbackReset(t *testing.T) { require.Zero(t, repo.tempUnschedCalls) } +func TestGrokRateLimitResetAtForAccountEscalatesRepeated429s(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + retryAfter := 45 + snapshot := &xai.QuotaSnapshot{ + StatusCode: http.StatusTooManyRequests, + RetryAfterSeconds: &retryAfter, + UpdatedAt: now.Format(time.RFC3339), + } + tests := []struct { + name string + previousCooldown time.Duration + wantCooldown time.Duration + }{ + {name: "repeat after short boundary", previousCooldown: 45 * time.Second, wantCooldown: grokRateLimitRepeatCooldown}, + {name: "sustained repeat", previousCooldown: grokRateLimitRepeatCooldown, wantCooldown: grokRateLimitSustainedCooldown}, + {name: "capped repeat", previousCooldown: grokRateLimitSustainedCooldown, wantCooldown: grokRateLimitMaxAdaptiveCooldown}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + previousReset := now.Add(-time.Second) + previousLimited := previousReset.Add(-tt.previousCooldown) + account := &Account{ + ID: 630, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + RateLimitedAt: &previousLimited, + RateLimitResetAt: &previousReset, + } + + resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, now) + + require.True(t, limited) + require.WithinDuration(t, now.Add(tt.wantCooldown), resetAt, time.Second) + }) + } +} + +func TestGrokRateLimitResetAtForAccountPreservesAuthoritativeAndQuietRecovery(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + retryAfter := 45 + previousReset := now.Add(-grokRateLimitBackoffQuietPeriod - time.Second) + previousLimited := previousReset.Add(-grokRateLimitSustainedCooldown) + account := &Account{ + ID: 631, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + RateLimitedAt: &previousLimited, + RateLimitResetAt: &previousReset, + } + snapshot := &xai.QuotaSnapshot{ + StatusCode: http.StatusTooManyRequests, + RetryAfterSeconds: &retryAfter, + UpdatedAt: now.Format(time.RFC3339), + } + + resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, now) + require.True(t, limited) + require.WithinDuration(t, now.Add(45*time.Second), resetAt, time.Second) + + authoritativeReset := now.Add(2 * time.Hour) + remaining := int64(0) + snapshot.Requests = &xai.QuotaWindow{Remaining: &remaining, ResetUnix: grokInt64PtrForTest(authoritativeReset.Unix())} + recentReset := now.Add(-time.Second) + recentLimited := recentReset.Add(-grokRateLimitSustainedCooldown) + account.RateLimitResetAt = &recentReset + account.RateLimitedAt = &recentLimited + + resetAt, limited = grokRateLimitResetAtForAccount(account, snapshot, now) + require.True(t, limited) + require.WithinDuration(t, authoritativeReset, resetAt, time.Second) +} + +func TestGrokRateLimitResetAtForAccountLeavesAPIKey429PolicyUnchanged(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + retryAfter := 45 + previousReset := now.Add(-time.Second) + previousLimited := previousReset.Add(-grokRateLimitSustainedCooldown) + account := &Account{ + ID: 632, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + RateLimitedAt: &previousLimited, + RateLimitResetAt: &previousReset, + } + snapshot := &xai.QuotaSnapshot{ + StatusCode: http.StatusTooManyRequests, + RetryAfterSeconds: &retryAfter, + UpdatedAt: now.Format(time.RFC3339), + } + + resetAt, limited := grokRateLimitResetAtForAccount(account, snapshot, now) + require.True(t, limited) + require.WithinDuration(t, now.Add(45*time.Second), resetAt, time.Second) +} + func TestGrokRateLimitResetAtUsesFutureWindowAfterRetryAfterExpires(t *testing.T) { now := time.Now().UTC().Truncate(time.Second) observedAt := now.Add(-2 * time.Minute) @@ -1666,6 +1805,72 @@ func TestUpdateGrokUsageSnapshotAvailableSuccessDoesNotSetRateLimited(t *testing require.Zero(t, repo.rateLimitedCalls) } +func TestUpdateGrokUsageFromResponseHeaderlessSuccessClearsObservedCooldown(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + limitedAt := now.Add(-grokRateLimitRepeatCooldown) + observedResetAt := now.Add(-time.Second) + account := &Account{ + ID: 660, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + RateLimitedAt: &limitedAt, + RateLimitResetAt: &observedResetAt, + } + repo := &grokQuotaAccountRepo{recoveryClearResult: true} + svc := &OpenAIGatewayService{ + accountRepo: repo, + codexSnapshotThrottle: newAccountWriteThrottle(time.Hour), + } + + svc.updateGrokUsageFromResponse(context.Background(), account, nil, http.StatusOK) + + require.Zero(t, repo.updateCalls, "headerless success must not overwrite an informative quota snapshot") + require.Equal(t, 1, repo.recoveryClearCalls) + require.Equal(t, limitedAt, repo.recoveryObservedAt) + require.Equal(t, observedResetAt, repo.recoveryObservedReset) + require.Same(t, &observedResetAt, account.RateLimitResetAt, "shared account snapshots must not be mutated in place") +} + +func TestUpdateGrokUsageFromResponseRecoveryRespectsCancellationAndAPIKeyBoundary(t *testing.T) { + now := time.Now().UTC().Truncate(time.Second) + observedResetAt := now.Add(-time.Second) + observedLimitedAt := observedResetAt.Add(-grokRateLimitRepeatCooldown) + + t.Run("parent cancellation does not mutate account state", func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + cancel() + account := &Account{ + ID: 661, + Platform: PlatformGrok, + Type: AccountTypeOAuth, + RateLimitedAt: &observedLimitedAt, + RateLimitResetAt: &observedResetAt, + } + repo := &grokQuotaAccountRepo{recoveryClearResult: true} + svc := &OpenAIGatewayService{accountRepo: repo} + + svc.updateGrokUsageFromResponse(ctx, account, nil, http.StatusOK) + + require.Zero(t, repo.recoveryClearCalls) + }) + + t.Run("API key success does not alter OAuth cooldown state", func(t *testing.T) { + account := &Account{ + ID: 662, + Platform: PlatformGrok, + Type: AccountTypeAPIKey, + RateLimitedAt: &observedLimitedAt, + RateLimitResetAt: &observedResetAt, + } + repo := &grokQuotaAccountRepo{recoveryClearResult: true} + svc := &OpenAIGatewayService{accountRepo: repo} + + svc.updateGrokUsageFromResponse(context.Background(), account, nil, http.StatusOK) + + require.Zero(t, repo.recoveryClearCalls) + }) +} + func TestUpdateGrokUsageSnapshotExhaustedSuccessWithoutResetUsesFallback(t *testing.T) { repo := &grokQuotaAccountRepo{} svc := &OpenAIGatewayService{accountRepo: repo} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index e2add90ff2..067d458b89 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -14,7 +14,6 @@ import ( "github.com/Wei-Shaw/sub2api/internal/pkg/claude" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/Wei-Shaw/sub2api/internal/pkg/openai_compat" - "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/Wei-Shaw/sub2api/internal/util/responseheaders" "github.com/gin-gonic/gin" "go.uber.org/zap" @@ -273,7 +272,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) var upstreamReq *http.Request if account.Platform == PlatformGrok { - upstreamReq, err = buildGrokResponsesRequest(upstreamCtx, c, account, responsesBody, token, grokCacheIdentity) + upstreamReq, err = buildGrokResponsesRequest(upstreamCtx, c, account, responsesBody, token, grokCacheIdentity, s.cfg) } else { upstreamReq, err = s.buildUpstreamRequest(upstreamCtx, c, account, responsesBody, token, isStream, promptCacheKey, false) } @@ -344,7 +343,7 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( return s.handleAnthropicErrorResponse(resp, c, account, billingModel) } if account.Platform == PlatformGrok && account.Type == AccountTypeOAuth && !account.IsShadow() { - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) } if account.Type == AccountTypeOAuth && promptCacheKey != "" { diff --git a/backend/internal/service/openai_ws_http_bridge.go b/backend/internal/service/openai_ws_http_bridge.go index dbc24c850a..77a5e59329 100644 --- a/backend/internal/service/openai_ws_http_bridge.go +++ b/backend/internal/service/openai_ws_http_bridge.go @@ -12,7 +12,6 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" - "github.com/Wei-Shaw/sub2api/internal/pkg/xai" "github.com/gin-gonic/gin" "github.com/tidwall/gjson" ) @@ -193,7 +192,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( releaseUpstreamCtx() return nil, fmt.Errorf("apply grok prompt cache identity: %w", err) } - upstreamReq, err = buildGrokResponsesRequest(upstreamCtx, c, account, body, token, grokCacheIdentity) + upstreamReq, err = buildGrokResponsesRequest(upstreamCtx, c, account, body, token, grokCacheIdentity, s.cfg) } else { upstreamReq, err = s.buildUpstreamRequestOpenAIPassthrough(upstreamCtx, c, account, body, token) } @@ -236,7 +235,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn( return nil, fmt.Errorf("upstream http bridge error: status=%d message=%s", resp.StatusCode, upstreamMsg) } if account.Platform == PlatformGrok { - s.updateGrokUsageSnapshot(ctx, account, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) + s.updateGrokUsageFromResponse(ctx, account, resp.Header, resp.StatusCode) } responseID := "" From 81b8b78378f026b88181d30bda4bea468add6109 Mon Sep 17 00:00:00 2001 From: Heatherm Huang Date: Tue, 14 Jul 2026 14:00:00 +0800 Subject: [PATCH 04/83] fix(grok): resolve upstream OAuth imports --- backend/internal/service/grok_oauth_service.go | 2 -- 1 file changed, 2 deletions(-) diff --git a/backend/internal/service/grok_oauth_service.go b/backend/internal/service/grok_oauth_service.go index 49e77bcfd7..92f3937967 100644 --- a/backend/internal/service/grok_oauth_service.go +++ b/backend/internal/service/grok_oauth_service.go @@ -3,8 +3,6 @@ package service import ( "context" "crypto/subtle" - "encoding/base64" - "encoding/json" "errors" "net/http" "strings" From cb7dfea5a9e54f9ddfb9dac55bdd7cc56485b9f5 Mon Sep 17 00:00:00 2001 From: Heatherm Huang Date: Tue, 14 Jul 2026 14:11:05 +0800 Subject: [PATCH 05/83] test(grok): update default model fixture --- backend/internal/service/account_test_service_grok_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/internal/service/account_test_service_grok_test.go b/backend/internal/service/account_test_service_grok_test.go index f311402874..72f995a0c7 100644 --- a/backend/internal/service/account_test_service_grok_test.go +++ b/backend/internal/service/account_test_service_grok_test.go @@ -93,8 +93,9 @@ func TestAccountTestService_TestAccountConnection_GrokDefaultsEmptyModelTo45(t * Schedulable: true, Concurrency: 1, Credentials: map[string]any{ - "access_token": "grok-access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), + "access_token": "grok-access-token", + "refresh_token": "grok-refresh-token", + "expires_at": time.Now().Add(2 * time.Hour).UTC().Format(time.RFC3339), }, } repo := &mockAccountRepoForGemini{accountsByID: map[int64]*Account{account.ID: account}} From 4c764d3fc97e895355799ebf2ffb8a166b68d5d1 Mon Sep 17 00:00:00 2001 From: Heatherm Huang Date: Tue, 14 Jul 2026 14:56:49 +0800 Subject: [PATCH 06/83] test(grok): use healthy quota account fixture --- .../service/grok_quota_service_test.go | 67 +++---------------- 1 file changed, 8 insertions(+), 59 deletions(-) diff --git a/backend/internal/service/grok_quota_service_test.go b/backend/internal/service/grok_quota_service_test.go index ad3c85ba19..52def9f101 100644 --- a/backend/internal/service/grok_quota_service_test.go +++ b/backend/internal/service/grok_quota_service_test.go @@ -302,16 +302,7 @@ func TestGrokQuotaServiceProbeUsageReportsProbeModelOnUpstreamError(t *testing.T func TestGrokQuotaServiceProbeUsageRedactsUpstreamErrorBodyFromErrorAndLogs(t *testing.T) { const upstreamSecret = "upstream-secret-refresh-token" - account := &Account{ - ID: 49, - Platform: PlatformGrok, - Type: AccountTypeOAuth, - Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(49) repo := &grokQuotaAccountRepo{ mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{49: account}, @@ -453,13 +444,7 @@ func TestGrokQuotaServiceProbeUsageReturnsRateLimitedSnapshot(t *testing.T) { func TestGrokQuotaServiceQueryQuotaFreeFallsBackToGrok45(t *testing.T) { t.Parallel() - account := &Account{ - ID: 51, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(51) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -500,13 +485,7 @@ func TestGrokQuotaServiceQueryQuotaFreeFallsBackToGrok45(t *testing.T) { func TestGrokQuotaServiceQueryQuotaPaidBillingSkipsActiveProbe(t *testing.T) { t.Parallel() - account := &Account{ - ID: 52, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(52) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -534,13 +513,7 @@ func TestGrokQuotaServiceQueryQuotaPaidBillingSkipsActiveProbe(t *testing.T) { func TestGrokQuotaServiceQueryQuotaCustomPaidMonthlyLimitSkipsActiveProbe(t *testing.T) { t.Parallel() - account := &Account{ - ID: 57, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(57) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -673,13 +646,7 @@ func TestGrokLocalUsageForBillingOnlyReturnsAvailableWindows(t *testing.T) { func TestAccountUsageServiceGrokRefreshUsesBillingOnly(t *testing.T) { t.Parallel() - account := &Account{ - ID: 54, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(54) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -714,13 +681,7 @@ func TestAccountUsageServiceGrokRefreshUsesBillingOnly(t *testing.T) { func TestGrokQuotaServiceProbeFlightsDeduplicateBillingAndSeparateActive(t *testing.T) { t.Parallel() - account := &Account{ - ID: 55, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(55) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -776,13 +737,7 @@ func TestGrokQuotaServiceProbeFlightsDeduplicateBillingAndSeparateActive(t *test func TestGrokQuotaServiceBilling429DoesNotPauseModelScheduling(t *testing.T) { t.Parallel() - account := &Account{ - ID: 56, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(56) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} @@ -802,13 +757,7 @@ func TestGrokQuotaServiceBilling429DoesNotPauseModelScheduling(t *testing.T) { func TestGrokQuotaServiceQueryQuotaFree429PersistsLimitAndKeepsBilling(t *testing.T) { t.Parallel() - account := &Account{ - ID: 53, Platform: PlatformGrok, Type: AccountTypeOAuth, Concurrency: 1, - Credentials: map[string]any{ - "access_token": "access-token", - "expires_at": time.Now().Add(time.Hour).UTC().Format(time.RFC3339), - }, - } + account := healthyGrokQuotaOAuthAccount(53) repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{ accountsByID: map[int64]*Account{account.ID: account}, }} From 7c717365ef728e53cdcf6d639a4dd68226db03b2 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Tue, 14 Jul 2026 07:08:08 +0000 Subject: [PATCH 07/83] chore: sync VERSION to 0.1.155 [skip ci] --- backend/cmd/server/VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/cmd/server/VERSION b/backend/cmd/server/VERSION index c64f02bbc3..7a29ae6cd9 100644 --- a/backend/cmd/server/VERSION +++ b/backend/cmd/server/VERSION @@ -1 +1 @@ -0.1.153 +0.1.155 From a8afc209690eb007c745662f488202dc747ab69d Mon Sep 17 00:00:00 2001 From: jjaw Date: Tue, 14 Jul 2026 15:18:47 +0800 Subject: [PATCH 08/83] =?UTF-8?q?=E4=BC=98=E5=8C=96=20Ops=20=E9=98=9F?= =?UTF-8?q?=E5=88=97=E6=B7=B1=E5=BA=A6=E8=B4=A6=E5=8F=B7=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/repository/account_repo.go | 45 ++++-- ...schedulable_projection_integration_test.go | 107 +++++++++++++++ ...ccount_repo_schedulable_projection_test.go | 82 +++++++++++ .../internal/service/ops_metrics_collector.go | 47 ++++--- .../ops_metrics_collector_projection_test.go | 128 ++++++++++++++++++ 5 files changed, 383 insertions(+), 26 deletions(-) create mode 100644 backend/internal/repository/account_repo_schedulable_projection_integration_test.go create mode 100644 backend/internal/repository/account_repo_schedulable_projection_test.go create mode 100644 backend/internal/service/ops_metrics_collector_projection_test.go diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 8eb819aeab..d1949299af 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -1050,8 +1050,42 @@ func (r *accountRepository) BindGroups(ctx context.Context, accountID int64, gro } func (r *accountRepository) ListSchedulable(ctx context.Context) ([]service.Account, error) { - now := time.Now() - accounts, err := r.client.Account.Query(). + accounts, err := r.schedulableAccountsQuery(time.Now()).All(ctx) + if err != nil { + return nil, err + } + return r.accountsToService(ctx, accounts) +} + +func (r *accountRepository) ListSchedulableAccountLoads(ctx context.Context) ([]service.AccountWithConcurrency, error) { + accounts, err := r.schedulableAccountsQuery(time.Now()). + Select( + dbaccount.FieldID, + dbaccount.FieldConcurrency, + dbaccount.FieldLoadFactor, + ). + All(ctx) + if err != nil { + return nil, err + } + + loads := make([]service.AccountWithConcurrency, 0, len(accounts)) + for _, account := range accounts { + projection := service.Account{ + ID: account.ID, + Concurrency: account.Concurrency, + LoadFactor: account.LoadFactor, + } + loads = append(loads, service.AccountWithConcurrency{ + ID: account.ID, + MaxConcurrency: projection.EffectiveLoadFactor(), + }) + } + return loads, nil +} + +func (r *accountRepository) schedulableAccountsQuery(now time.Time) *dbent.AccountQuery { + return r.client.Account.Query(). Where( dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true), @@ -1060,12 +1094,7 @@ func (r *accountRepository) ListSchedulable(ctx context.Context) ([]service.Acco dbaccount.Or(dbaccount.OverloadUntilIsNil(), dbaccount.OverloadUntilLTE(now)), dbaccount.Or(dbaccount.RateLimitResetAtIsNil(), dbaccount.RateLimitResetAtLTE(now)), ). - Order(dbent.Asc(dbaccount.FieldPriority)). - All(ctx) - if err != nil { - return nil, err - } - return r.accountsToService(ctx, accounts) + Order(dbent.Asc(dbaccount.FieldPriority)) } func (r *accountRepository) ListSchedulableByGroupID(ctx context.Context, groupID int64) ([]service.Account, error) { diff --git a/backend/internal/repository/account_repo_schedulable_projection_integration_test.go b/backend/internal/repository/account_repo_schedulable_projection_integration_test.go new file mode 100644 index 0000000000..82d62a1448 --- /dev/null +++ b/backend/internal/repository/account_repo_schedulable_projection_integration_test.go @@ -0,0 +1,107 @@ +//go:build integration + +package repository + +import ( + "context" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestListSchedulableAccountLoadsMatchesListSchedulable(t *testing.T) { + ctx := context.Background() + tx := testEntTx(t) + client := tx.Client() + repo := newAccountRepositoryWithSQL(client, tx, nil) + now := time.Now() + past := now.Add(-time.Hour) + future := now.Add(time.Hour) + + create := func(name string) *service.Account { + return mustCreateAccount(t, client, &service.Account{Name: name, Schedulable: true}) + } + + positiveLoad := create("projection-positive-load") + _, err := client.Account.UpdateOneID(positiveLoad.ID).SetConcurrency(2).SetLoadFactor(9).SetPriority(30).Save(ctx) + require.NoError(t, err) + concurrencyFallback := create("projection-concurrency-fallback") + _, err = client.Account.UpdateOneID(concurrencyFallback.ID).SetConcurrency(4).SetPriority(10).Save(ctx) + require.NoError(t, err) + zeroFallback := create("projection-zero-fallback") + _, err = client.Account.UpdateOneID(zeroFallback.ID).SetConcurrency(0).SetLoadFactor(0).SetPriority(20).Save(ctx) + require.NoError(t, err) + + disabled := create("projection-disabled") + _, err = client.Account.UpdateOneID(disabled.ID).SetStatus(service.StatusDisabled).Save(ctx) + require.NoError(t, err) + unschedulable := create("projection-unschedulable") + _, err = client.Account.UpdateOneID(unschedulable.ID).SetSchedulable(false).Save(ctx) + require.NoError(t, err) + expired := create("projection-expired") + _, err = client.Account.UpdateOneID(expired.ID).SetExpiresAt(past).SetAutoPauseOnExpired(true).Save(ctx) + require.NoError(t, err) + expiredAllowed := create("projection-expired-allowed") + _, err = client.Account.UpdateOneID(expiredAllowed.ID).SetExpiresAt(past).SetAutoPauseOnExpired(false).Save(ctx) + require.NoError(t, err) + overloaded := create("projection-overloaded") + _, err = client.Account.UpdateOneID(overloaded.ID).SetOverloadUntil(future).Save(ctx) + require.NoError(t, err) + overloadCleared := create("projection-overload-cleared") + _, err = client.Account.UpdateOneID(overloadCleared.ID).SetOverloadUntil(past).Save(ctx) + require.NoError(t, err) + rateLimited := create("projection-rate-limited") + _, err = client.Account.UpdateOneID(rateLimited.ID).SetRateLimitResetAt(future).Save(ctx) + require.NoError(t, err) + rateLimitCleared := create("projection-rate-limit-cleared") + _, err = client.Account.UpdateOneID(rateLimitCleared.ID).SetRateLimitResetAt(past).Save(ctx) + require.NoError(t, err) + tempBlocked := create("projection-temp-blocked") + _, err = client.Account.UpdateOneID(tempBlocked.ID).SetTempUnschedulableUntil(future).Save(ctx) + require.NoError(t, err) + tempCleared := create("projection-temp-cleared") + _, err = client.Account.UpdateOneID(tempCleared.ID).SetTempUnschedulableUntil(past).Save(ctx) + require.NoError(t, err) + + accounts, err := repo.ListSchedulable(ctx) + require.NoError(t, err) + loads, err := repo.ListSchedulableAccountLoads(ctx) + require.NoError(t, err) + + accountIDs := make([]int64, 0, len(accounts)) + wantByID := make(map[int64]int, len(accounts)) + for i := range accounts { + accountIDs = append(accountIDs, accounts[i].ID) + wantByID[accounts[i].ID] = accounts[i].EffectiveLoadFactor() + } + + loadIDs := make([]int64, 0, len(loads)) + byID := make(map[int64]int, len(loads)) + for _, load := range loads { + loadIDs = append(loadIDs, load.ID) + byID[load.ID] = load.MaxConcurrency + } + require.Equal(t, accountIDs, loadIDs) + targetIDs := map[int64]struct{}{ + positiveLoad.ID: {}, concurrencyFallback.ID: {}, zeroFallback.ID: {}, + } + targetOrder := make([]int64, 0, len(targetIDs)) + for _, id := range loadIDs { + if _, ok := targetIDs[id]; ok { + targetOrder = append(targetOrder, id) + } + } + require.Equal(t, []int64{concurrencyFallback.ID, zeroFallback.ID, positiveLoad.ID}, targetOrder) + require.Equal(t, wantByID, byID) + require.Equal(t, 9, byID[positiveLoad.ID]) + require.Equal(t, 4, byID[concurrencyFallback.ID]) + require.Equal(t, 1, byID[zeroFallback.ID]) + for _, included := range []*service.Account{expiredAllowed, overloadCleared, rateLimitCleared, tempCleared} { + require.Contains(t, byID, included.ID) + } + for _, excluded := range []*service.Account{disabled, unschedulable, expired, overloaded, rateLimited, tempBlocked} { + require.NotContains(t, byID, excluded.ID) + } +} diff --git a/backend/internal/repository/account_repo_schedulable_projection_test.go b/backend/internal/repository/account_repo_schedulable_projection_test.go new file mode 100644 index 0000000000..76d7e0bdc5 --- /dev/null +++ b/backend/internal/repository/account_repo_schedulable_projection_test.go @@ -0,0 +1,82 @@ +package repository + +import ( + "context" + "fmt" + "strings" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + _ "github.com/Wei-Shaw/sub2api/ent/runtime" + "github.com/stretchr/testify/require" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" +) + +type captureEntQueryMatcher struct { + actual *string +} + +func (m captureEntQueryMatcher) Match(_, actual string) error { + if m.actual == nil { + return fmt.Errorf("query capture target is nil") + } + *m.actual = actual + return nil +} + +func TestListSchedulableAccountLoadsUsesSingleProjectionQuery(t *testing.T) { + var capturedSQL string + db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(captureEntQueryMatcher{actual: &capturedSQL})) + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + + driver := entsql.OpenDB(dialect.Postgres, db) + client := dbent.NewClient(dbent.Driver(driver)) + t.Cleanup(func() { _ = client.Close() }) + repo := newAccountRepositoryWithSQL(client, db, nil) + + mock.ExpectQuery("schedulable account load projection"). + WillReturnRows(sqlmock.NewRows([]string{"id", "concurrency", "load_factor"}). + AddRow(int64(11), 3, nil). + AddRow(int64(12), 2, 7)) + + loads, err := repo.ListSchedulableAccountLoads(context.Background()) + require.NoError(t, err) + require.Len(t, loads, 2) + require.Equal(t, int64(11), loads[0].ID) + require.Equal(t, 3, loads[0].MaxConcurrency) + require.Equal(t, int64(12), loads[1].ID) + require.Equal(t, 7, loads[1].MaxConcurrency) + require.NoError(t, mock.ExpectationsWereMet(), "projection path must execute exactly one query") + + normalized := normalizeSQLWhitespace(capturedSQL) + selectClause, _, found := strings.Cut(normalized, " FROM ") + require.True(t, found, "unexpected projection SQL: %s", normalized) + require.Equal(t, 2, strings.Count(selectClause, ","), "projection must select exactly three columns: %s", selectClause) + require.Contains(t, selectClause, `"id"`) + require.Contains(t, selectClause, `"concurrency"`) + require.Contains(t, selectClause, `"load_factor"`) + require.NotContains(t, selectClause, "credentials") + require.NotContains(t, selectClause, "extra") + require.NotContains(t, selectClause, "proxy_id") + require.NotContains(t, normalized, "account_groups") + require.NotContains(t, normalized, "proxies") + for _, predicateColumn := range []string{ + "status", + "schedulable", + "temp_unschedulable_until", + "expires_at", + "auto_pause_on_expired", + "overload_until", + "rate_limit_reset_at", + "deleted_at", + } { + require.Contains(t, normalized, predicateColumn) + } + _, orderClause, hasOrder := strings.Cut(normalized, " ORDER BY ") + require.True(t, hasOrder, "projection query must preserve schedulable account order: %s", normalized) + require.Contains(t, orderClause, `"priority" ASC`) +} diff --git a/backend/internal/service/ops_metrics_collector.go b/backend/internal/service/ops_metrics_collector.go index b654190cfb..d4f5c32929 100644 --- a/backend/internal/service/ops_metrics_collector.go +++ b/backend/internal/service/ops_metrics_collector.go @@ -39,6 +39,10 @@ const ( var opsMetricsCollectorAdvisoryLockID = hashAdvisoryLockID(opsMetricsCollectorLeaderLockKey) +type opsSchedulableAccountLoadRepository interface { + ListSchedulableAccountLoads(ctx context.Context) ([]AccountWithConcurrency, error) +} + type OpsMetricsCollector struct { opsRepo OpsRepository settingRepo SettingRepository @@ -375,31 +379,16 @@ func (c *OpsMetricsCollector) collectConcurrencyQueueDepth(parentCtx context.Con ctx, cancel := context.WithTimeout(parentCtx, 2*time.Second) defer cancel() - accounts, err := c.accountRepo.ListSchedulable(ctx) + accountLoads, err := c.listSchedulableAccountLoads(ctx) if err != nil { return nil } - if len(accounts) == 0 { + if len(accountLoads) == 0 { zero := 0 return &zero } - batch := make([]AccountWithConcurrency, 0, len(accounts)) - for _, acc := range accounts { - if acc.ID <= 0 { - continue - } - batch = append(batch, AccountWithConcurrency{ - ID: acc.ID, - MaxConcurrency: acc.EffectiveLoadFactor(), - }) - } - if len(batch) == 0 { - zero := 0 - return &zero - } - - loadMap, err := c.concurrencyService.GetAccountsLoadBatch(ctx, batch) + loadMap, err := c.concurrencyService.GetAccountsLoadBatch(ctx, accountLoads) if err != nil { return nil } @@ -423,6 +412,28 @@ func (c *OpsMetricsCollector) collectConcurrencyQueueDepth(parentCtx context.Con return &v } +func (c *OpsMetricsCollector) listSchedulableAccountLoads(ctx context.Context) ([]AccountWithConcurrency, error) { + if repo, ok := c.accountRepo.(opsSchedulableAccountLoadRepository); ok { + return repo.ListSchedulableAccountLoads(ctx) + } + + accounts, err := c.accountRepo.ListSchedulable(ctx) + if err != nil { + return nil, err + } + loads := make([]AccountWithConcurrency, 0, len(accounts)) + for _, account := range accounts { + if account.ID <= 0 { + continue + } + loads = append(loads, AccountWithConcurrency{ + ID: account.ID, + MaxConcurrency: account.EffectiveLoadFactor(), + }) + } + return loads, nil +} + type opsCollectedPercentiles struct { p50 *int p90 *int diff --git a/backend/internal/service/ops_metrics_collector_projection_test.go b/backend/internal/service/ops_metrics_collector_projection_test.go new file mode 100644 index 0000000000..e0d1da774d --- /dev/null +++ b/backend/internal/service/ops_metrics_collector_projection_test.go @@ -0,0 +1,128 @@ +package service + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +type opsMetricsProjectionRepo struct { + AccountRepository + accounts []Account + accountLoads []AccountWithConcurrency + listCalls int + projectionCalls int +} + +func (r *opsMetricsProjectionRepo) ListSchedulable(context.Context) ([]Account, error) { + r.listCalls++ + return r.accounts, nil +} + +func (r *opsMetricsProjectionRepo) ListSchedulableAccountLoads(context.Context) ([]AccountWithConcurrency, error) { + r.projectionCalls++ + return r.accountLoads, nil +} + +type opsMetricsFallbackRepo struct { + AccountRepository + accounts []Account + listCalls int +} + +func (r *opsMetricsFallbackRepo) ListSchedulable(context.Context) ([]Account, error) { + r.listCalls++ + return r.accounts, nil +} + +type opsMetricsLoadCache struct { + ConcurrencyCache + loads map[int64]*AccountLoadInfo + got []AccountWithConcurrency +} + +func (c *opsMetricsLoadCache) GetAccountsLoadBatch(_ context.Context, accounts []AccountWithConcurrency) (map[int64]*AccountLoadInfo, error) { + c.got = accounts + return c.loads, nil +} + +func TestCollectConcurrencyQueueDepthUsesProjectionAndPreservesFallbackResult(t *testing.T) { + loadFactor := 7 + accounts := []Account{ + {ID: 11, Concurrency: 2, LoadFactor: &loadFactor}, + {ID: 12, Concurrency: 3}, + {ID: 13}, + } + accountLoads := []AccountWithConcurrency{ + {ID: 11, MaxConcurrency: 7}, + {ID: 12, MaxConcurrency: 3}, + {ID: 13, MaxConcurrency: 1}, + } + loads := map[int64]*AccountLoadInfo{ + 11: {AccountID: 11, WaitingCount: 2}, + 12: {AccountID: 12, WaitingCount: 3}, + 13: {AccountID: 13, WaitingCount: 0}, + } + + projectionRepo := &opsMetricsProjectionRepo{accounts: accounts, accountLoads: accountLoads} + projectionCache := &opsMetricsLoadCache{loads: loads} + projectionConcurrency := NewConcurrencyService(projectionCache) + projectionConcurrency.SetAccountLoadBatchCacheTTL(0) + projectionCollector := &OpsMetricsCollector{ + accountRepo: projectionRepo, + concurrencyService: projectionConcurrency, + } + + fallbackRepo := &opsMetricsFallbackRepo{accounts: accounts} + fallbackCache := &opsMetricsLoadCache{loads: loads} + fallbackConcurrency := NewConcurrencyService(fallbackCache) + fallbackConcurrency.SetAccountLoadBatchCacheTTL(0) + fallbackCollector := &OpsMetricsCollector{ + accountRepo: fallbackRepo, + concurrencyService: fallbackConcurrency, + } + + projectionDepth := projectionCollector.collectConcurrencyQueueDepth(context.Background()) + fallbackDepth := fallbackCollector.collectConcurrencyQueueDepth(context.Background()) + + require.NotNil(t, projectionDepth) + require.NotNil(t, fallbackDepth) + require.Equal(t, 5, *projectionDepth) + require.Equal(t, *fallbackDepth, *projectionDepth) + require.Equal(t, 1, projectionRepo.projectionCalls) + require.Zero(t, projectionRepo.listCalls) + require.Equal(t, 1, fallbackRepo.listCalls) + require.Equal(t, accountLoads, projectionCache.got) + require.Equal(t, fallbackCache.got, projectionCache.got) +} + +func BenchmarkOpsMetricsCollectorCollectConcurrencyQueueDepth(b *testing.B) { + const accountCount = 1000 + loadFactor := 8 + accounts := make([]Account, accountCount) + accountLoads := make([]AccountWithConcurrency, accountCount) + for i := range accountCount { + id := int64(i + 1) + accounts[i] = Account{ + ID: id, + Concurrency: 4, + LoadFactor: &loadFactor, + } + accountLoads[i] = AccountWithConcurrency{ID: id, MaxConcurrency: loadFactor} + } + + repo := &opsMetricsProjectionRepo{accounts: accounts, accountLoads: accountLoads} + cache := &opsMetricsLoadCache{loads: map[int64]*AccountLoadInfo{}} + concurrency := NewConcurrencyService(cache) + concurrency.SetAccountLoadBatchCacheTTL(0) + collector := &OpsMetricsCollector{accountRepo: repo, concurrencyService: concurrency} + + b.ReportAllocs() + b.ResetTimer() + for range b.N { + if depth := collector.collectConcurrencyQueueDepth(context.Background()); depth == nil || *depth != 0 { + b.Fatalf("unexpected queue depth: %v", depth) + } + } +} From 23f93a9348766026cb003e75ab212daeee4c7c29 Mon Sep 17 00:00:00 2001 From: jjaw Date: Tue, 14 Jul 2026 16:17:17 +0800 Subject: [PATCH 09/83] =?UTF-8?q?=E4=BC=98=E5=8C=96=20Responses=20?= =?UTF-8?q?=E6=B5=81=E5=BC=8F=E4=BA=8B=E4=BB=B6=E8=BE=B9=E7=95=8C=E5=88=B7?= =?UTF-8?q?=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../openai_gateway_response_flush_test.go | 473 ++++++++++++++++++ .../openai_gateway_response_handling.go | 101 ++-- 2 files changed, 531 insertions(+), 43 deletions(-) create mode 100644 backend/internal/service/openai_gateway_response_flush_test.go diff --git a/backend/internal/service/openai_gateway_response_flush_test.go b/backend/internal/service/openai_gateway_response_flush_test.go new file mode 100644 index 0000000000..3494824d6c --- /dev/null +++ b/backend/internal/service/openai_gateway_response_flush_test.go @@ -0,0 +1,473 @@ +package service + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type openAIResponseFlushRecorder struct { + header http.Header + mu sync.Mutex + body bytes.Buffer + status int + writes int + failAfterWrites int + flushSnapshots []string + flushEvents chan int + blockFlush int + flushBlocked chan struct{} + releaseFlush <-chan struct{} +} + +func newOpenAIResponseFlushRecorder() *openAIResponseFlushRecorder { + return &openAIResponseFlushRecorder{ + header: make(http.Header), + failAfterWrites: -1, + flushEvents: make(chan int, 16), + } +} + +func (w *openAIResponseFlushRecorder) Header() http.Header { + return w.header +} + +func (w *openAIResponseFlushRecorder) WriteHeader(statusCode int) { + w.mu.Lock() + defer w.mu.Unlock() + if w.status == 0 { + w.status = statusCode + } +} + +func (w *openAIResponseFlushRecorder) Write(data []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + if w.failAfterWrites >= 0 && w.writes >= w.failAfterWrites { + return 0, errors.New("client disconnected") + } + w.writes++ + if w.status == 0 { + w.status = http.StatusOK + } + return w.body.Write(data) +} + +func (w *openAIResponseFlushRecorder) Flush() { + w.mu.Lock() + w.flushSnapshots = append(w.flushSnapshots, w.body.String()) + count := len(w.flushSnapshots) + w.mu.Unlock() + w.flushEvents <- count + if count == w.blockFlush { + close(w.flushBlocked) + <-w.releaseFlush + } +} + +func (w *openAIResponseFlushRecorder) snapshot() (string, []string) { + w.mu.Lock() + defer w.mu.Unlock() + return w.body.String(), append([]string(nil), w.flushSnapshots...) +} + +type stagedOpenAISSEReadCloser struct { + segments [][]byte + gates []<-chan struct{} + waiting []chan struct{} + eofReached chan struct{} + current []byte + index int +} + +func (r *stagedOpenAISSEReadCloser) Read(data []byte) (int, error) { + if len(r.current) == 0 { + if r.index >= len(r.segments) { + if r.eofReached != nil { + close(r.eofReached) + r.eofReached = nil + } + return 0, io.EOF + } + index := r.index + r.index++ + if index < len(r.waiting) && r.waiting[index] != nil { + close(r.waiting[index]) + } + if index < len(r.gates) && r.gates[index] != nil { + <-r.gates[index] + } + r.current = r.segments[index] + } + n := copy(data, r.current) + r.current = r.current[n:] + return n, nil +} + +func (r *stagedOpenAISSEReadCloser) Close() error { return nil } + +type openAIResponseFlushReadError struct { + payload []byte + err error + sent bool +} + +func (r *openAIResponseFlushReadError) Read(data []byte) (int, error) { + if !r.sent { + r.sent = true + return copy(data, r.payload), nil + } + if r.err != nil { + return 0, r.err + } + return 0, io.ErrUnexpectedEOF +} + +func (r *openAIResponseFlushReadError) Close() error { return nil } + +func TestOpenAIResponseFlush_SlowEventsFlushOnceAtBoundaries(t *testing.T) { + events := []string{ + `data: {"type":"response.output_text.delta","delta":"a"}`, + `data: {"type":"response.output_text.delta","delta":"b"}`, + `data: {"type":"response.output_text.delta","delta":"c"}`, + `data: [DONE]`, + } + body := strings.Join(events, "\n\n") + "\n\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Len(t, flushes, len(events)) + for _, flushed := range flushes { + require.True(t, strings.HasSuffix(flushed, "\n\n"), "flush must occur after a complete SSE event") + } +} + +func TestOpenAIResponseFlush_DataQueuedButBlankDrainsFlushesOnce(t *testing.T) { + first := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"first\"}\n\n" + second := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"second\"}\n\n" + terminal := "data: [DONE]\n\n" + allowSecond := make(chan struct{}) + allowTerminal := make(chan struct{}) + terminalWaiting := make(chan struct{}) + reader := &stagedOpenAISSEReadCloser{ + segments: [][]byte{[]byte(first), []byte(second), []byte(terminal)}, + gates: []<-chan struct{}{nil, allowSecond, allowTerminal}, + waiting: []chan struct{}{nil, nil, terminalWaiting}, + } + releaseFirstFlush := make(chan struct{}) + recorder := newOpenAIResponseFlushRecorder() + recorder.blockFlush = 1 + recorder.flushBlocked = make(chan struct{}) + recorder.releaseFlush = releaseFirstFlush + resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamDataIntervalTimeout: 30}) + + waitOpenAIResponseFlushSignal(t, recorder.flushBlocked) + close(allowSecond) + waitOpenAIResponseFlushSignal(t, terminalWaiting) + close(releaseFirstFlush) + waitOpenAIResponseFlushCount(t, recorder, 2) + close(allowTerminal) + + require.NoError(t, <-errCh) + require.NotNil(t, <-resultCh) + gotBody, flushes := recorder.snapshot() + require.Equal(t, first+second+terminal, gotBody) + require.Len(t, flushes, 3) + require.Equal(t, first, flushes[0]) + require.Equal(t, first+second, flushes[1], "blank line that drains the queue must flush the complete event exactly once") +} + +func TestOpenAIResponseFlush_BurstDoesNotIncreaseFlushes(t *testing.T) { + first := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"first\"}\n\n" + burst := strings.Join([]string{ + `data: {"type":"response.output_text.delta","delta":"second"}`, + `data: {"type":"response.output_text.delta","delta":"third"}`, + `data: [DONE]`, + }, "\n\n") + "\n\n" + allowBurst := make(chan struct{}) + eofReached := make(chan struct{}) + reader := &stagedOpenAISSEReadCloser{ + segments: [][]byte{[]byte(first), []byte(burst)}, + gates: []<-chan struct{}{nil, allowBurst}, + eofReached: eofReached, + } + releaseFirstFlush := make(chan struct{}) + recorder := newOpenAIResponseFlushRecorder() + recorder.blockFlush = 1 + recorder.flushBlocked = make(chan struct{}) + recorder.releaseFlush = releaseFirstFlush + resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamDataIntervalTimeout: 30}) + + waitOpenAIResponseFlushSignal(t, recorder.flushBlocked) + close(allowBurst) + waitOpenAIResponseFlushSignal(t, eofReached) + close(releaseFirstFlush) + + require.NoError(t, <-errCh) + require.NotNil(t, <-resultCh) + gotBody, flushes := recorder.snapshot() + require.Equal(t, first+burst, gotBody) + require.Len(t, flushes, 2, "queued burst must remain batched until its drained event boundary") + require.Equal(t, first, flushes[0]) + require.Equal(t, first+burst, flushes[1]) +} + +func TestOpenAIResponseFlush_CommentAndEOFOnlyFlushCompleteResidual(t *testing.T) { + body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" + + ": upstream-comment\n\n" + + "data: [DONE]\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Len(t, flushes, 3) + require.True(t, strings.HasSuffix(flushes[0], "\n\n")) + require.True(t, strings.HasSuffix(flushes[1], "\n\n")) + require.True(t, strings.HasSuffix(flushes[2], "data: [DONE]\n"), "EOF must flush only the remaining bytes") +} + +func TestOpenAIResponseFlush_TerminalReadErrorFlushesResidual(t *testing.T) { + body := "data: [DONE]\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, &openAIResponseFlushReadError{payload: []byte(body)}, config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Equal(t, []string{body}, flushes) +} + +func TestOpenAIResponseFlush_OutputWithoutTerminalFlushesResidualWithoutFailover(t *testing.T) { + body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"partial\"}\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.ErrorContains(t, err, "missing terminal event") + var failoverErr *UpstreamFailoverError + require.False(t, errors.As(err, &failoverErr)) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Equal(t, []string{body}, flushes) +} + +func TestOpenAIResponseFlush_PreambleWithoutTerminalRemainsBufferedForFailover(t *testing.T) { + body := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_1\"}}\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + var failoverErr *UpstreamFailoverError + require.ErrorAs(t, err, &failoverErr) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Empty(t, gotBody) + require.Empty(t, flushes) +} + +func TestOpenAIResponseFlush_CanceledAfterOutputFlushesResidualWithoutErrorEvent(t *testing.T) { + body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"partial\"}\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, &openAIResponseFlushReadError{payload: []byte(body), err: context.Canceled}, config.GatewayConfig{}) + + require.ErrorIs(t, err, context.Canceled) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Equal(t, []string{body}, flushes) + require.NotContains(t, gotBody, "stream_read_error") +} + +func TestOpenAIResponseFlush_KeepaliveFlushesImmediately(t *testing.T) { + recorder := newOpenAIResponseFlushRecorder() + reader, writer := io.Pipe() + resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamKeepaliveInterval: 1}) + + waitOpenAIResponseFlushCount(t, recorder, 1) + _, flushes := recorder.snapshot() + require.Equal(t, ":\n\n", flushes[0]) + _, err := writer.Write([]byte("data: [DONE]\n\n")) + require.NoError(t, err) + require.NoError(t, writer.Close()) + + require.NoError(t, <-errCh) + require.NotNil(t, <-resultCh) + gotBody, flushes := recorder.snapshot() + require.Equal(t, ":\n\ndata: [DONE]\n\n", gotBody) + require.Len(t, flushes, 2) +} + +func TestOpenAIResponseFlush_KeepaliveDoesNotSplitOpenEvent(t *testing.T) { + const dataLine = `data: {"type":"response.output_text.delta","delta":"a"}` + // Filling the 16-slot scan queue proves the main loop processed data before the reader reaches the gated blank. + dataLines := make([]string, 17) + for i := range dataLines { + dataLines[i] = dataLine + } + partialEvent := strings.Join(dataLines, "\n") + "\n" + completeEvent := partialEvent + "\n" + terminal := "data: [DONE]\n\n" + allowBlank := make(chan struct{}) + allowTerminal := make(chan struct{}) + blankWaiting := make(chan struct{}) + terminalWaiting := make(chan struct{}) + reader := &stagedOpenAISSEReadCloser{ + segments: [][]byte{[]byte(partialEvent), []byte("\n"), []byte(terminal)}, + gates: []<-chan struct{}{nil, allowBlank, allowTerminal}, + waiting: []chan struct{}{nil, blankWaiting, terminalWaiting}, + } + recorder := newOpenAIResponseFlushRecorder() + resultCh, errCh := runOpenAIResponseFlushTestAsync(recorder, reader, config.GatewayConfig{StreamKeepaliveInterval: 1}) + + waitOpenAIResponseFlushSignal(t, blankWaiting) + timer := time.NewTimer(1250 * time.Millisecond) + select { + case count := <-recorder.flushEvents: + timer.Stop() + t.Fatalf("keepalive flushed open event before its blank boundary: flush %d", count) + case <-timer.C: + } + + close(allowBlank) + waitOpenAIResponseFlushSignal(t, terminalWaiting) + waitOpenAIResponseFlushCount(t, recorder, 1) + gotBody, flushes := recorder.snapshot() + require.Equal(t, completeEvent, gotBody) + require.Equal(t, []string{completeEvent}, flushes) + + close(allowTerminal) + require.NoError(t, <-errCh) + require.NotNil(t, <-resultCh) + gotBody, flushes = recorder.snapshot() + require.Equal(t, completeEvent+terminal, gotBody) + require.Len(t, flushes, 2) + require.Equal(t, completeEvent+terminal, flushes[1]) +} + +func TestOpenAIResponseFlush_FailedAndErrorEventsFlushAtBoundaries(t *testing.T) { + t.Run("failed at EOF", func(t *testing.T) { + body := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" + + "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"},\"usage\":{\"input_tokens\":3,\"output_tokens\":1}}}\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.Error(t, err) + require.NotNil(t, result) + require.Equal(t, 3, result.usage.InputTokens) + gotBody, flushes := recorder.snapshot() + expectedBody := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" + + "data: {\"type\":\"response.failed\",\"response\":{\"error\":{\"code\":\"safety_error\",\"message\":\"blocked\"}}}\n" + require.Equal(t, expectedBody, gotBody) + require.Len(t, flushes, 2) + require.Contains(t, flushes[1], "response.failed") + }) + + t.Run("error event", func(t *testing.T) { + body := "data: {\"type\":\"error\",\"error\":{\"message\":\"failed\"}}\n\n" + + "data: [DONE]\n\n" + recorder := newOpenAIResponseFlushRecorder() + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(body)), config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + gotBody, flushes := recorder.snapshot() + require.Equal(t, body, gotBody) + require.Len(t, flushes, 2) + }) +} + +func TestOpenAIResponseFlush_ClientDisconnectStillDrainsUsage(t *testing.T) { + first := "data: {\"type\":\"response.output_text.delta\",\"delta\":\"a\"}\n\n" + terminal := "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":7,\"output_tokens\":5,\"input_tokens_details\":{\"cached_tokens\":2}}}}\n\n" + recorder := newOpenAIResponseFlushRecorder() + recorder.failAfterWrites = 1 + + result, err := runOpenAIResponseFlushTest(recorder, io.NopCloser(strings.NewReader(first+terminal)), config.GatewayConfig{}) + + require.NoError(t, err) + require.NotNil(t, result) + require.Equal(t, 7, result.usage.InputTokens) + require.Equal(t, 5, result.usage.OutputTokens) + require.Equal(t, 2, result.usage.CacheReadInputTokens) + gotBody, flushes := recorder.snapshot() + require.Equal(t, first, gotBody) + require.Len(t, flushes, 1) +} + +func runOpenAIResponseFlushTest(recorder *openAIResponseFlushRecorder, body io.ReadCloser, gatewayCfg config.GatewayConfig) (*openaiStreamingResult, error) { + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil) + svc := &OpenAIGatewayService{ + cfg: &config.Config{Gateway: gatewayCfg}, + toolCorrector: NewCodexToolCorrector(), + } + resp := &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: body, + } + return svc.handleStreamingResponse(context.Background(), resp, c, &Account{ID: 1, Platform: PlatformOpenAI}, time.Now(), "gpt-5", "gpt-5") +} + +func runOpenAIResponseFlushTestAsync(recorder *openAIResponseFlushRecorder, body io.ReadCloser, gatewayCfg config.GatewayConfig) (<-chan *openaiStreamingResult, <-chan error) { + resultCh := make(chan *openaiStreamingResult, 1) + errCh := make(chan error, 1) + go func() { + result, err := runOpenAIResponseFlushTest(recorder, body, gatewayCfg) + resultCh <- result + errCh <- err + }() + return resultCh, errCh +} + +func waitOpenAIResponseFlushCount(t *testing.T, recorder *openAIResponseFlushRecorder, want int) { + t.Helper() + timer := time.NewTimer(3 * time.Second) + defer timer.Stop() + for { + select { + case count := <-recorder.flushEvents: + if count >= want { + return + } + case <-timer.C: + t.Fatalf("timed out waiting for flush %d", want) + } + } +} + +func waitOpenAIResponseFlushSignal(t *testing.T, signal <-chan struct{}) { + t.Helper() + select { + case <-signal: + case <-time.After(3 * time.Second): + t.Fatal("timed out waiting for stream signal") + } +} diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 845428b641..11da6d52de 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -125,6 +125,8 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp clientOutputStarted := false upstreamRequestID := strings.TrimSpace(resp.Header.Get("x-request-id")) var streamEarlyErr error + eventShouldFlush := false + eventInProgress := false sendErrorEvent := func(reason string) { if errorEventSent || clientDisconnected { return @@ -160,49 +162,55 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp imageOutputSizes: imageCounter.Sizes(), } } + flushPending := func(disconnectMessage string) { + if clientDisconnected || bufferedWriter.Buffered() == 0 { + return + } + if err := flushBuffered(); err != nil { + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "%s", disconnectMessage) + return + } + clientOutputStarted = true + lastDownstreamWriteAt = time.Now() + } finalizeStream := func() (*openaiStreamingResult, error) { + if !sawTerminalEvent && !openAIStreamClientOutputStarted(c, clientOutputStarted) && !eventShouldFlush { + return resultWithUsage(), s.newOpenAIStreamFailoverError( + c, + account, + false, + upstreamRequestID, + nil, + "OpenAI stream ended before a terminal event", + ) + } + flushPending("Client disconnected during final flush, returning collected usage") if !sawTerminalEvent { - if !openAIStreamClientOutputStarted(c, clientOutputStarted) { - return resultWithUsage(), s.newOpenAIStreamFailoverError( - c, - account, - false, - upstreamRequestID, - nil, - "OpenAI stream ended before a terminal event", - ) - } return resultWithUsage(), fmt.Errorf("stream usage incomplete: missing terminal event") } if sawFailedEvent { return resultWithUsage(), fmt.Errorf("upstream response failed: %s", failedMessage) } - if !clientDisconnected { - hadBufferedData := bufferedWriter.Buffered() > 0 - if err := flushBuffered(); err != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "Client disconnected during final flush, returning collected usage") - } else if hadBufferedData { - clientOutputStarted = true - lastDownstreamWriteAt = time.Now() - } - } return resultWithUsage(), nil } handleScanErr := func(scanErr error) (*openaiStreamingResult, error, bool) { if scanErr == nil { return nil, nil, false } - if sawTerminalEvent && !sawFailedEvent { - logger.LegacyPrintf("service.openai_gateway", "Upstream scan ended after terminal event: %v", scanErr) - return resultWithUsage(), nil, true - } - if sawFailedEvent { - return resultWithUsage(), fmt.Errorf("upstream response failed: %s", failedMessage), true + if sawTerminalEvent { + if !sawFailedEvent { + logger.LegacyPrintf("service.openai_gateway", "Upstream scan ended after terminal event: %v", scanErr) + } + result, err := finalizeStream() + return result, err, true } // 客户端断开/取消请求时,上游读取往往会返回 context canceled。 // /v1/responses 的 SSE 事件必须符合 OpenAI 协议;这里不注入自定义 error event,避免下游 SDK 解析失败。 if errors.Is(scanErr, context.Canceled) || errors.Is(scanErr, context.DeadlineExceeded) { + if eventShouldFlush { + flushPending("Client disconnected during canceled stream flush, returning collected usage") + } return resultWithUsage(), fmt.Errorf("stream usage incomplete: %w", scanErr), true } if errors.Is(scanErr, bufio.ErrTooLong) { @@ -210,7 +218,7 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp sendErrorEvent("response_too_large") return resultWithUsage(), scanErr, true } - if !openAIStreamClientOutputStarted(c, clientOutputStarted) { + if !openAIStreamClientOutputStarted(c, clientOutputStarted) && !eventShouldFlush { msg := "OpenAI stream disconnected before completion" if errText := strings.TrimSpace(scanErr.Error()); errText != "" { msg += ": " + errText @@ -333,20 +341,15 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp // 保证首个 token 事件尽快出站,避免影响 TTFT。 shouldFlush = true } + eventShouldFlush = eventShouldFlush || shouldFlush if _, err := bufferedWriter.WriteString(line); err != nil { clientDisconnected = true logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") } else if _, err := bufferedWriter.WriteString("\n"); err != nil { clientDisconnected = true logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") - } else if shouldFlush { - if err := flushBuffered(); err != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming flush, continuing to drain upstream for billing") - } else { - clientOutputStarted = true - lastDownstreamWriteAt = time.Now() - } + } else { + eventInProgress = true } } @@ -359,7 +362,13 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp return } - // Forward non-data lines as-is + // Forward non-data lines as-is. Flush only after the blank line that + // completes the SSE event, never after a partial data line. + shouldFlush := false + if line == "" { + shouldFlush = eventShouldFlush || (queueDrained && clientOutputStarted) + eventShouldFlush = false + } if !clientDisconnected { if _, err := bufferedWriter.WriteString(line); err != nil { clientDisconnected = true @@ -367,13 +376,16 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp } else if _, err := bufferedWriter.WriteString("\n"); err != nil { clientDisconnected = true logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming, continuing to drain upstream for billing") - } else if queueDrained && clientOutputStarted { - if err := flushBuffered(); err != nil { - clientDisconnected = true - logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming flush, continuing to drain upstream for billing") - } else { - clientOutputStarted = true - lastDownstreamWriteAt = time.Now() + } else { + eventInProgress = line != "" + if shouldFlush { + if err := flushBuffered(); err != nil { + clientDisconnected = true + logger.LegacyPrintf("service.openai_gateway", "Client disconnected during streaming flush, continuing to drain upstream for billing") + } else { + clientOutputStarted = true + lastDownstreamWriteAt = time.Now() + } } } } @@ -460,6 +472,9 @@ func (s *OpenAIGatewayService) handleStreamingResponse(ctx context.Context, resp if clientDisconnected { continue } + if eventInProgress { + continue + } if time.Since(lastDownstreamWriteAt) < keepaliveInterval { continue } From e2028a814e74d09f847919c30dde5cf894d2b815 Mon Sep 17 00:00:00 2001 From: haruka <1628615876@qq.com> Date: Tue, 14 Jul 2026 16:41:33 +0800 Subject: [PATCH 10/83] fix(frontend): update Codex API key snippets --- frontend/src/components/keys/UseKeyModal.vue | 45 +++++++-------- .../keys/__tests__/UseKeyModal.spec.ts | 55 +++++++++++++++++-- .../src/i18n/locales/en/admin/channels.ts | 2 +- frontend/src/i18n/locales/en/dashboard.ts | 10 ++-- .../src/i18n/locales/zh/admin/channels.ts | 2 +- frontend/src/i18n/locales/zh/dashboard.ts | 10 ++-- 6 files changed, 86 insertions(+), 38 deletions(-) diff --git a/frontend/src/components/keys/UseKeyModal.vue b/frontend/src/components/keys/UseKeyModal.vue index e6bce556da..87983f94cc 100644 --- a/frontend/src/components/keys/UseKeyModal.vue +++ b/frontend/src/components/keys/UseKeyModal.vue @@ -562,29 +562,36 @@ windows_wsl_setup_acknowledged = true name = "OpenAI" base_url = "${baseUrl}" wire_api = "responses" -requires_openai_auth = true +requires_openai_auth = false +env_key = "SUB2API_API_KEY" +http_headers = { "x-openai-actor-authorization" = "local-image-extension" } [features] +image_generation = true goals = true` - // auth.json content - const authContent = `{ - "OPENAI_API_KEY": "${apiKey}" -}` - return [ { path: `${configDir}/config.toml`, content: configContent, hint: t('keys.useKeyModal.openai.configTomlHint') }, - { - path: `${configDir}/auth.json`, - content: authContent - } + generateCodexAPIKeyEnvironment(apiKey, isWindows) ] } +function generateCodexAPIKeyEnvironment(apiKey: string, isWindows: boolean): FileConfig { + return isWindows + ? { + path: 'PowerShell', + content: `$env:SUB2API_API_KEY="${apiKey}"` + } + : { + path: 'Terminal', + content: `export SUB2API_API_KEY="${apiKey}"` + } +} + function generateGrokFiles(baseUrl: string, apiKey: string): FileConfig[] { const isWindows = activeTab.value === 'windows' const configDir = isWindows ? '%userprofile%\\.grok' : '~/.grok' @@ -613,7 +620,7 @@ function generateOpenAIWsFiles(baseUrl: string, apiKey: string): FileConfig[] { const isWindows = activeTab.value === 'windows' const configDir = isWindows ? '%userprofile%\\.codex' : '~/.codex' - // config.toml content with WebSocket v2 + // config.toml content with the Responses WebSocket transport enabled const configContent = `model_provider = "OpenAI" model = "gpt-5.5" review_model = "gpt-5.5" @@ -627,27 +634,21 @@ name = "OpenAI" base_url = "${baseUrl}" wire_api = "responses" supports_websockets = true -requires_openai_auth = true +requires_openai_auth = false +env_key = "SUB2API_API_KEY" +http_headers = { "x-openai-actor-authorization" = "local-image-extension" } [features] -responses_websockets_v2 = true +image_generation = true goals = true` - // auth.json content - const authContent = `{ - "OPENAI_API_KEY": "${apiKey}" -}` - return [ { path: `${configDir}/config.toml`, content: configContent, hint: t('keys.useKeyModal.openai.configTomlHint') }, - { - path: `${configDir}/auth.json`, - content: authContent - } + generateCodexAPIKeyEnvironment(apiKey, isWindows) ] } diff --git a/frontend/src/components/keys/__tests__/UseKeyModal.spec.ts b/frontend/src/components/keys/__tests__/UseKeyModal.spec.ts index 24581d9f6b..4e216de8da 100644 --- a/frontend/src/components/keys/__tests__/UseKeyModal.spec.ts +++ b/frontend/src/components/keys/__tests__/UseKeyModal.spec.ts @@ -78,7 +78,7 @@ describe('UseKeyModal', () => { expect(parsed.provider.grok.models['gpt-5.6']).toBeUndefined() }) - it('renders GPT-5.5 and goals feature in OpenAI Codex config', () => { + it('renders API key mode and local image generation in OpenAI Codex config', () => { const wrapper = mount(UseKeyModal, { props: { show: true, @@ -107,10 +107,17 @@ describe('UseKeyModal', () => { expect(configToml).not.toContain('model = "gpt-5.4"') expect(configToml).not.toContain('model_context_window') expect(configToml).not.toContain('model_auto_compact_token_limit') - expect(configToml).toContain('[features]\ngoals = true') + expect(configToml).toContain('requires_openai_auth = false') + expect(configToml).toContain('env_key = "SUB2API_API_KEY"') + expect(configToml).toContain('http_headers = { "x-openai-actor-authorization" = "local-image-extension" }') + expect(configToml).not.toContain('supports_websockets') + expect(configToml).not.toContain('responses_websockets_v2') + expect(configToml).toContain('[features]\nimage_generation = true\ngoals = true') + expect(codeBlocks).toContain('export SUB2API_API_KEY="sk-test"') + expect(wrapper.text()).not.toContain('auth.json') }) - it('renders GPT-5.5 and goals feature in OpenAI Codex WebSocket config', async () => { + it('renders API key mode and current WebSocket settings in OpenAI Codex config', async () => { const wrapper = mount(UseKeyModal, { props: { show: true, @@ -147,7 +154,47 @@ describe('UseKeyModal', () => { expect(configToml).not.toContain('model = "gpt-5.4"') expect(configToml).not.toContain('model_context_window') expect(configToml).not.toContain('model_auto_compact_token_limit') - expect(configToml).toContain('[features]\nresponses_websockets_v2 = true\ngoals = true') + expect(configToml).toContain('requires_openai_auth = false') + expect(configToml).toContain('env_key = "SUB2API_API_KEY"') + expect(configToml).toContain('http_headers = { "x-openai-actor-authorization" = "local-image-extension" }') + expect(configToml).toContain('supports_websockets = true') + expect(configToml).not.toContain('responses_websockets_v2') + expect(configToml).toContain('[features]\nimage_generation = true\ngoals = true') + expect(codeBlocks).toContain('export SUB2API_API_KEY="sk-test"') + expect(wrapper.text()).not.toContain('auth.json') + }) + + it('renders a PowerShell API key command for Codex on Windows', async () => { + const wrapper = mount(UseKeyModal, { + props: { + show: true, + apiKey: 'sk-test', + baseUrl: 'https://example.com/v1', + platform: 'openai' + }, + global: { + stubs: { + BaseDialog: { + template: '
' + }, + Icon: { + template: '' + } + } + } + }) + + const windowsTab = wrapper.findAll('button').find( + (button) => button.text().trim() === 'Windows' + ) + + expect(windowsTab).toBeDefined() + await windowsTab!.trigger('click') + await nextTick() + + const codeBlocks = wrapper.findAll('pre code').map((code) => code.text()) + expect(codeBlocks).toContain('$env:SUB2API_API_KEY="sk-test"') + expect(wrapper.text()).not.toContain('auth.json') }) it('renders GPT-5.4 mini entry in OpenCode config', async () => { diff --git a/frontend/src/i18n/locales/en/admin/channels.ts b/frontend/src/i18n/locales/en/admin/channels.ts index 07a24d0fd5..eaeacc73b4 100644 --- a/frontend/src/i18n/locales/en/admin/channels.ts +++ b/frontend/src/i18n/locales/en/admin/channels.ts @@ -155,7 +155,7 @@ export default { webSearchEmulationHint: '⚠️ When enabled, all accounts in this channel\'s Anthropic groups will intercept web_search requests. Use with caution.', webSearchEmulationGlobalDisabled: 'Please enable the global switch first in Settings → Gateway → Web Search Emulation', codexImageGenerationBridge: 'Codex Image Generation Bridge', - codexImageGenerationBridgeHint: 'When enabled, Codex /responses text requests in OpenAI groups may be automatically given the image_generation tool. Keep off unless the routed accounts support image generation.', + codexImageGenerationBridgeHint: 'Hosted image bridge for non-Responses Lite requests only. It may inject the image_generation tool into Codex /responses text requests; Responses Lite uses the client-side image executor instead.', bedrockCCCompat: 'Bedrock CC Compatibility', bedrockCCCompatHint: '⚠️ When enabled, requests to Bedrock accounts in this channel will be transformed for Claude Code compatibility (thinking type conversion, tool_use ID sanitization).', basicSettings: 'Basic Settings', diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts index 816f6bd440..3d70935a05 100644 --- a/frontend/src/i18n/locales/en/dashboard.ts +++ b/frontend/src/i18n/locales/en/dashboard.ts @@ -136,16 +136,16 @@ export default { noGroupTitle: 'Please assign a group first', noGroupDescription: 'This API key has not been assigned to a group. Please click the group column in the key list to assign one before viewing the configuration.', openai: { - description: 'Add the following configuration files to your Codex CLI config directory.', + description: 'Set SUB2API_API_KEY before starting Codex, then add the config.toml settings below. Responses Lite image generation uses Codex\'s local image executor; hosted force injection applies only to non-Responses Lite requests.', configTomlHint: 'Make sure the following content is at the beginning of the config.toml file', - note: 'Make sure the config directory exists. macOS/Linux users can run mkdir -p ~/.codex to create it.', - noteWindows: 'Press Win+R and enter %userprofile%\\.codex to open the config directory. Create it manually if it does not exist.', + note: 'Make sure ~/.codex exists, set the environment variable before Codex/Desktop starts, then fully restart the client and create a new thread so the image tool is registered.', + noteWindows: 'Make sure %userprofile%\\.codex exists, set the environment variable before Codex/Desktop starts, then fully restart the client and create a new thread so the image tool is registered.', }, cliTabs: { claudeCode: 'Claude Code', geminiCli: 'Gemini CLI', - codexCli: 'Codex CLI', - codexCliWs: 'Codex CLI (WebSocket)', + codexCli: 'Codex (API Key Mode)', + codexCliWs: 'Codex (API Key Mode, WebSocket)', grokCli: 'Grok CLI', opencode: 'OpenCode', }, diff --git a/frontend/src/i18n/locales/zh/admin/channels.ts b/frontend/src/i18n/locales/zh/admin/channels.ts index 93890e25b0..b0b3717f64 100644 --- a/frontend/src/i18n/locales/zh/admin/channels.ts +++ b/frontend/src/i18n/locales/zh/admin/channels.ts @@ -155,7 +155,7 @@ export default { webSearchEmulationHint: '⚠️ 开启后该渠道下所有 Anthropic 分组的账号将自动拦截 web_search 请求,请谨慎操作', webSearchEmulationGlobalDisabled: '请先在系统设置 → 网关 → Web Search 模拟中启用全局开关', codexImageGenerationBridge: 'Codex 图片生成桥接', - codexImageGenerationBridgeHint: '开启后,OpenAI 分组的 Codex /responses 文本请求可能会被自动注入 image_generation 工具。仅在路由账号支持图片生成时开启。', + codexImageGenerationBridgeHint: '仅用于非 Responses Lite 请求的服务端图片桥接,可向 Codex /responses 文本请求注入 image_generation 工具;Responses Lite 改用客户端图片执行器。', bedrockCCCompat: 'Bedrock CC 兼容', bedrockCCCompatHint: '⚠️ 开启后,该渠道下 Bedrock 账号的请求将进行 Claude Code 兼容处理(thinking 类型转换、tool_use ID 清理)', basicSettings: '基础设置', diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts index a268919612..7472ec781c 100644 --- a/frontend/src/i18n/locales/zh/dashboard.ts +++ b/frontend/src/i18n/locales/zh/dashboard.ts @@ -136,17 +136,17 @@ export default { noGroupDescription: '此 API 密钥尚未分配分组,请先在密钥列表中点击分组列进行分配,然后才能查看使用配置。', openai: { - description: '将以下配置文件添加到 Codex CLI 配置目录中。', + description: '启动 Codex 前先设置 SUB2API_API_KEY,再添加以下 config.toml 配置。Responses Lite 生图使用 Codex 本地图片执行器;服务端强制注入仅用于非 Responses Lite 请求。', configTomlHint: '请确保以下内容位于 config.toml 文件的开头部分', - note: '请确保配置目录存在。macOS/Linux 用户可运行 mkdir -p ~/.codex 创建目录。', + note: '请确保 ~/.codex 目录存在,并在 Codex/Desktop 启动前设置环境变量;随后完全重启客户端并新建会话,以重新注册图片工具。', noteWindows: - '按 Win+R,输入 %userprofile%\\.codex 打开配置目录。如目录不存在,请先手动创建。' + '请确保 %userprofile%\\.codex 目录存在,并在 Codex/Desktop 启动前设置环境变量;随后完全重启客户端并新建会话,以重新注册图片工具。' }, cliTabs: { claudeCode: 'Claude Code', geminiCli: 'Gemini CLI', - codexCli: 'Codex CLI', - codexCliWs: 'Codex CLI (WebSocket)', + codexCli: 'Codex(API Key 模式)', + codexCliWs: 'Codex(API Key 模式,WebSocket)', grokCli: 'Grok CLI', opencode: 'OpenCode' }, From 86800a8cd0740b6305ab74112c6106469f93c9b6 Mon Sep 17 00:00:00 2001 From: jjaw Date: Tue, 14 Jul 2026 15:39:06 +0800 Subject: [PATCH 11/83] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=86=85=E5=AE=B9?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E7=A7=8D=E5=AD=90=E5=AD=97=E6=AE=B5=E6=89=AB?= =?UTF-8?q?=E6=8F=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/openai_content_session_seed.go | 78 +++++++- ...nai_content_session_seed_benchmark_test.go | 29 +++ .../openai_content_session_seed_test.go | 181 ++++++++++++++++++ 3 files changed, 282 insertions(+), 6 deletions(-) create mode 100644 backend/internal/service/openai_content_session_seed_benchmark_test.go diff --git a/backend/internal/service/openai_content_session_seed.go b/backend/internal/service/openai_content_session_seed.go index fce85f11bd..5f8f1872e8 100644 --- a/backend/internal/service/openai_content_session_seed.go +++ b/backend/internal/service/openai_content_session_seed.go @@ -1,6 +1,7 @@ package service import ( + "bytes" "encoding/json" "strings" @@ -25,31 +26,96 @@ func deriveOpenAIContentSessionSeed(body []byte) string { return "" } + const ( + modelField = iota + toolsField + functionsField + instructionsField + messagesField + inputField + contentSessionSeedFieldCount + allContentSessionSeedFields = 1< len(root) { + return false + } + // Result.ForEach can continue after the root '}' on malformed input. + // The separator range excludes braces inside the preceding parsed value. + if bytes.IndexByte(root[nextKeyOffset:key.Index], '}') >= 0 { + return false + } + nextKeyOffset = value.Index + len(value.Raw) + + field := -1 + switch key.Str { + case "model": + field = modelField + case "tools": + field = toolsField + case "functions": + field = functionsField + case "instructions": + field = instructionsField + case "messages": + field = messagesField + case "input": + field = inputField + } + if field < 0 { + return true + } + mask := uint8(1 << field) + if seen&mask == 0 { + fields[field] = value + seen |= mask + } + return seen != allContentSessionSeedFields + }) + var b strings.Builder - if model := gjson.GetBytes(body, "model").String(); model != "" { + if model := fields[modelField].String(); model != "" { _, _ = b.WriteString("model=") _, _ = b.WriteString(model) } - if tools := gjson.GetBytes(body, "tools"); tools.Exists() && tools.IsArray() && tools.Raw != "[]" { + if tools := fields[toolsField]; tools.Exists() && tools.IsArray() && tools.Raw != "[]" { _, _ = b.WriteString("|tools=") _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(tools.Raw))) } - if funcs := gjson.GetBytes(body, "functions"); funcs.Exists() && funcs.IsArray() && funcs.Raw != "[]" { + if funcs := fields[functionsField]; funcs.Exists() && funcs.IsArray() && funcs.Raw != "[]" { _, _ = b.WriteString("|functions=") _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(funcs.Raw))) } - if instr := gjson.GetBytes(body, "instructions").String(); instr != "" { + if instr := fields[instructionsField].String(); instr != "" { _, _ = b.WriteString("|instructions=") _, _ = b.WriteString(instr) } firstUserCaptured := false - msgs := gjson.GetBytes(body, "messages") + msgs := fields[messagesField] if msgs.Exists() && msgs.IsArray() { msgs.ForEach(func(_, msg gjson.Result) bool { role := msg.Get("role").String() @@ -70,7 +136,7 @@ func deriveOpenAIContentSessionSeed(body []byte) string { } return true }) - } else if inp := gjson.GetBytes(body, "input"); inp.Exists() { + } else if inp := fields[inputField]; inp.Exists() { if inp.Type == gjson.String { _, _ = b.WriteString("|input=") _, _ = b.WriteString(inp.String()) diff --git a/backend/internal/service/openai_content_session_seed_benchmark_test.go b/backend/internal/service/openai_content_session_seed_benchmark_test.go new file mode 100644 index 0000000000..eda9deaa82 --- /dev/null +++ b/backend/internal/service/openai_content_session_seed_benchmark_test.go @@ -0,0 +1,29 @@ +package service + +import ( + "strings" + "testing" +) + +var benchmarkOpenAIContentSessionSeed string + +func BenchmarkDeriveOpenAIContentSessionSeedLargeBody(b *testing.B) { + largeHistory := strings.Repeat("payload", 1<<17) + tests := []struct { + name string + body []byte + }{ + {name: "ChatCompletions", body: []byte(`{"model":"gpt-5.4","tools":[{"type":"function","function":{"name":"lookup"}}],"messages":[{"role":"system","content":"Be concise."},{"role":"user","content":"Hello"},{"role":"assistant","content":"` + largeHistory + `"},{"role":"user","content":"Follow-up"}]}`)}, + {name: "Responses", body: []byte(`{"model":"gpt-5.4","instructions":"Be concise.","tools":[{"type":"function","name":"lookup"}],"input":[{"role":"system","content":"System prompt"},{"role":"user","content":"Hello"},{"role":"assistant","content":"` + largeHistory + `"}]}`)}, + } + + for _, test := range tests { + b.Run(test.name, func(b *testing.B) { + b.ReportAllocs() + b.SetBytes(int64(len(test.body))) + for range b.N { + benchmarkOpenAIContentSessionSeed = deriveOpenAIContentSessionSeed(test.body) + } + }) + } +} diff --git a/backend/internal/service/openai_content_session_seed_test.go b/backend/internal/service/openai_content_session_seed_test.go index 6dadc5cf53..0c6c63335c 100644 --- a/backend/internal/service/openai_content_session_seed_test.go +++ b/backend/internal/service/openai_content_session_seed_test.go @@ -1,9 +1,12 @@ package service import ( + "encoding/json" + "strings" "testing" "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" ) func TestDeriveOpenAIContentSessionSeed_EmptyInputs(t *testing.T) { @@ -197,6 +200,184 @@ func TestDeriveOpenAIContentSessionSeed_JSONCanonicalisation(t *testing.T) { require.Equal(t, s1, s2, "different formatting of identical JSON should produce the same seed") } +func TestDeriveOpenAIContentSessionSeed_SingleScanMatchesLegacyBytes(t *testing.T) { + largeValue := strings.Repeat("payload", 1<<17) + tests := []struct { + name string + body []byte + }{ + { + name: "large chat completions", + body: []byte(`{"metadata":"` + largeValue + `","model":"gpt-5.4","tools":[{"type":"function","function":{"name":"lookup"}}],"functions":[{"name":"legacy_lookup"}],"messages":[{"role":"system","content":"System prompt"},{"role":"developer","content":[{"type":"text","text":"Developer prompt"}]},{"role":"user","content":"Hello"}]}`), + }, + { + name: "large responses", + body: []byte(`{"metadata":"` + largeValue + `","model":"gpt-5.4","instructions":"Be concise.","tools":[{"type":"function","name":"lookup"}],"input":[{"role":"system","content":"System prompt"},{"role":"user","content":[{"type":"input_text","text":"Hello"}]}]}`), + }, + { + name: "fields in reverse order", + body: []byte(`{"input":"fallback input","messages":[{"role":"user","content":"chat wins"}],"instructions":"Be concise.","functions":[{"name":"lookup"}],"tools":[{"type":"function","name":"lookup"}],"model":"gpt-5.4"}`), + }, + { + name: "missing and wrong type fields", + body: []byte(`{"tools":[],"functions":null,"instructions":0,"messages":{},"input":[{"type":"input_text","text":"fallback"}]}`), + }, + { + name: "duplicate fields keep first value", + body: []byte(`{"model":"first","model":"second","tools":[{"name":"first"}],"tools":[{"name":"second"}],"functions":[],"functions":[{"name":"second"}],"instructions":"first","instructions":"second","messages":null,"messages":[{"role":"user","content":"second"}],"input":"first input","input":"second input"}`), + }, + { + name: "escaped field names", + body: []byte(`{"mo\u0064el":"gpt-5.4","mess\u0061ges":[{"role":"user","content":"Hello"}]}`), + }, + { + name: "trailing object fields are outside the root", + body: []byte(`{"foo":1}{"model":"trailing","input":"trailing input"}`), + }, + { + name: "trailing quoted fields are outside the root", + body: []byte(`{"model":"root"}"input":"trailing input"`), + }, + { + name: "leading garbage before the root", + body: []byte(`garbage{"model":"gpt-5.4","input":"Hello"}`), + }, + { + name: "escaped braces remain inside string values", + body: []byte(`{"metadata":"escaped } and [ and \" quote","model":"root","input":"Hello"}{"model":"trailing"}`), + }, + { + name: "nested braces do not end the root", + body: []byte(`{"metadata":{"nested":"} ]"},"model":"root","input":"Hello"}{"model":"trailing"}`), + }, + { + name: "root array does not expose nested or trailing object fields", + body: []byte(`[{"model":"nested"}]{"model":"trailing","input":"trailing input"}`), + }, + { + name: "trailing messages do not override root input", + body: []byte(`{"input":"root input"}{"messages":[{"role":"user","content":"trailing"}]}`), + }, + { + name: "truncated string containing a closing brace", + body: []byte(`{"model":"root","metadata":"still } inside`), + }, + { + name: "lenient truncated body", + body: []byte(`{"model":"gpt-5.4","messages":[{"role":"user","content":"Hello"}]`), + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require.Equal(t, legacyDeriveOpenAIContentSessionSeed(test.body), deriveOpenAIContentSessionSeed(test.body)) + }) + } +} + +func TestDeriveOpenAIContentSessionSeed_AllTruncationOffsetsMatchLegacyBytes(t *testing.T) { + bodies := []string{ + `{"model":"gpt-5.4","tools":[{"type":"function","function":{"name":"lookup"}}],"functions":[{"name":"legacy"}],"instructions":"escaped \" } text","messages":[{"role":"system","content":"System"},{"role":"user","content":[{"type":"text","text":"Hello"}]}],"input":"fallback"}`, + `{"model":"gpt-5.4","instructions":"Be concise.","tools":[{"type":"function","name":"lookup"}],"input":[{"role":"system","content":"System"},{"role":"user","content":[{"type":"input_text","text":"Hello"}]}]}`, + } + for bodyIndex, body := range bodies { + for end := 1; end < len(body); end++ { + truncated := []byte(body[:end]) + require.Equalf(t, legacyDeriveOpenAIContentSessionSeed(truncated), deriveOpenAIContentSessionSeed(truncated), "body %d truncated at byte %d", bodyIndex, end) + } + } +} + +func legacyDeriveOpenAIContentSessionSeed(body []byte) string { + if len(body) == 0 { + return "" + } + + var b strings.Builder + + if model := gjson.GetBytes(body, "model").String(); model != "" { + _, _ = b.WriteString("model=") + _, _ = b.WriteString(model) + } + + if tools := gjson.GetBytes(body, "tools"); tools.Exists() && tools.IsArray() && tools.Raw != "[]" { + _, _ = b.WriteString("|tools=") + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(tools.Raw))) + } + + if funcs := gjson.GetBytes(body, "functions"); funcs.Exists() && funcs.IsArray() && funcs.Raw != "[]" { + _, _ = b.WriteString("|functions=") + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(funcs.Raw))) + } + + if instr := gjson.GetBytes(body, "instructions").String(); instr != "" { + _, _ = b.WriteString("|instructions=") + _, _ = b.WriteString(instr) + } + + firstUserCaptured := false + + msgs := gjson.GetBytes(body, "messages") + if msgs.Exists() && msgs.IsArray() { + msgs.ForEach(func(_, msg gjson.Result) bool { + role := msg.Get("role").String() + switch role { + case "system", "developer": + _, _ = b.WriteString("|system=") + if c := msg.Get("content"); c.Exists() { + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(c.Raw))) + } + case "user": + if !firstUserCaptured { + _, _ = b.WriteString("|first_user=") + if c := msg.Get("content"); c.Exists() { + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(c.Raw))) + } + firstUserCaptured = true + } + } + return true + }) + } else if inp := gjson.GetBytes(body, "input"); inp.Exists() { + if inp.Type == gjson.String { + _, _ = b.WriteString("|input=") + _, _ = b.WriteString(inp.String()) + } else if inp.IsArray() { + inp.ForEach(func(_, item gjson.Result) bool { + role := item.Get("role").String() + switch role { + case "system", "developer": + _, _ = b.WriteString("|system=") + if c := item.Get("content"); c.Exists() { + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(c.Raw))) + } + case "user": + if !firstUserCaptured { + _, _ = b.WriteString("|first_user=") + if c := item.Get("content"); c.Exists() { + _, _ = b.WriteString(normalizeCompatSeedJSON(json.RawMessage(c.Raw))) + } + firstUserCaptured = true + } + } + if !firstUserCaptured && item.Get("type").String() == "input_text" { + _, _ = b.WriteString("|first_user=") + if text := item.Get("text").String(); text != "" { + _, _ = b.WriteString(text) + } + firstUserCaptured = true + } + return true + }) + } + } + + if b.Len() == 0 { + return "" + } + return contentSessionSeedPrefix + b.String() +} + func TestDeriveOpenAIContentSessionSeed_ResponsesAPI_InputTextTypedItem(t *testing.T) { body := []byte(`{ "model": "gpt-5.4", From da85cc7e47882090b115d664afe8e39b37aa7417 Mon Sep 17 00:00:00 2001 From: shaw Date: Tue, 14 Jul 2026 17:00:51 +0800 Subject: [PATCH 12/83] chore: update sponsors --- README.md | 6 ++++++ README_CN.md | 5 +++++ README_JA.md | 6 ++++++ assets/partners/logos/aimzoon.jpg | Bin 0 -> 25231 bytes 4 files changed, 17 insertions(+) create mode 100644 assets/partners/logos/aimzoon.jpg diff --git a/README.md b/README.md index 6bb4068644..00f021ea2c 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,12 @@ Model authenticity: no content intervention or secondary filtering — experienc + +aimzoon +Thanks to Aimzoon for sponsoring this project! Aimzoon provides stable, cost-effective AI API access services, enabling developers to quickly connect popular AI services to coding tools such as Codex, Claude Code, and Gemini CLI. No complex configuration — faster onboarding, more stable calls, and lower costs. Ongoing promotions including discounted Codex rates and special pricing, with free trial credits upon registration, bringing AI coding into your daily workflow. Click here to register and try it out! + + + ## Overview diff --git a/README_CN.md b/README_CN.md index 348e1c93c4..b1139dd122 100644 --- a/README_CN.md +++ b/README_CN.md @@ -166,6 +166,11 @@ + +aimzoon +感谢 Aimzoon 对本项目的赞助! Aimzoon 提供稳定、高性价比的 AI API 接入服务,支持开发者将常用 AI 服务快速接入 Codex、Claude Code、Gemini CLI 等编程工具。无需复杂配置,更快接入,更稳调用,更省成本。codex倍率优惠,特价倍率等促销不断,注册即送免费体验额度,让 AI 编程真正进入日常工作流。点击这里注册体验! + + diff --git a/README_JA.md b/README_JA.md index ac18b36387..ba556139ee 100644 --- a/README_JA.md +++ b/README_JA.md @@ -161,6 +161,12 @@ + +aimzoon +Aimzoon のご支援に感謝します!Aimzoon は安定してコストパフォーマンスに優れた AI API 接続サービスを提供し、開発者が主要な AI サービスを Codex、Claude Code、Gemini CLI などのコーディングツールへ素早く接続できるようにします。複雑な設定は不要で、より速い接続、より安定した呼び出し、より低いコストを実現。Codex レート割引や特価レートなどのキャンペーンも随時開催中、登録するだけで無料お試しクレジットをプレゼント。AI コーディングを日常のワークフローへ。こちらから登録してお試しください! + + + ## 概要 diff --git a/assets/partners/logos/aimzoon.jpg b/assets/partners/logos/aimzoon.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3fa8c653c8f1fcaad2708d31d0062dcad34774a6 GIT binary patch literal 25231 zcmdSAWmsHG)-c*Q1Z&)(aR~12PH+f8gC#(4x8UyX?he6%26uON_u!BKA-BoNnK|#g z^L;btdG3#UcUA9QwQKoWRox~1bK&O(04OUdBME?j001Ds3Gj0nAO?Vkg@uEKfro>G zLqLFkfrN>SgoucQhmL`YNrX>AOoUHJ2%=!529eQ|6B5#J(b6-su(Pw1Q1b|Iv+^^t zv9mrCfj~e&Kte>qMMlPDB_$+f{oB{iE&v)lLA zUa%05P%v=N;6^;K8c@%w{PTi%)F!h1wC!i?u z9+Hl9yljfQ?(gYLOE`!>8`xMPuPG{FrqZB}J$D@Q-m0A8Eq(Jz)n^Yf`nN2fYBU%I z6^gJ}m(p-l)L_=uVJ6Z~K&te7KMXTKe}@|?PCe5quNTLho1lJqiPjuua|33DRX~IK zLD-v_ng-n$dUj;JTSM=1j0qR^Y^N!yY*i^KLsJ+MId0?8TkH$Q`*mU4P`xsa{2l%d zTTQrR(d*4Cl?s=`*Im04I?b5Pp92^xWYv$lR#HCg@t?_(k6ce&3E=Lz&+QbcMuHjg zzN^zGeceWCcfhFoLRUNI z)#bZg%O>a94->kl^P_L(DoYC(b6!~vVrxgy&d07h5oc<-l`v7ZjYy>~%?({FCN73M ztJLy+@E0@)b5Sn;JE~uFQ`wBZ^+YW3Ob@tGM;X9pr z6jk!&&fbq3xwR?)0NPrHF4X+0#Q2r@kLjX(IpCUPo9)5`oeQ3kOc zIFhsU<%CP+2M?Vi(@tBGXjApQD`NKTaen;q^$P)Rk}!-d{tgdXYU5m^^ZaT=#QNX-&cjY~&>#Sx+r=8l@>YA~OMg=p8eY)t0 z+t;EQ`hd<%e0z6cNN4EVj6qp%2N|dz2kNpCsnsvq{UC||7gD8*9h1UoAgK6WV zOIch=(?z4*p-0Pa5m~nn-!tadvks)!lH_8Z0N{uYALX#9Cp>4z;e&a1q7rXF0J8g0 z3XOxbHW6N48h$i^c~V}=$8FlxEf(%WrfzHu%{L&Tp8!HK3i&#v3!3Zhpx5!|cs|n| z(^dvl)O#XG{T~N=+$QTFnP_&YPRIK7mhF*A`KQIj^A-__tYkW<_l5s7mMaNELRA*(pt_m za3r(2ZT(0dKPJ~6=xt(~X&=2@_Q|3R)Ub7NxOBSvb-%ns=aVyc^{m9)rGj4yw`9u*~R~3IXv~@gs9eJ z^j>({%GDLUj`)+F5sx}!7dKXGRAl^;S-(d!8x>(unO!VB6q6c{?#EsQz!BjWJ^eGh z>yI73jlv&8YoVx^7W!Z{8Tr^~cj;!kKJ-xXR%4f!=!Q5a3d{N6$6H19D3a0k8RP9Y zZ7cQjd2mTWi6cqc+VrE5Vik+3M^Rij2d7u}jxM)zk!4rfj;p?Ev}_0Byh6AFl5Ee)E{J!=5-}AozeH!#d3&8XD3I zoyU}mD9hj3wujFdiUCeCy^mr8MPR`-1O@sy_p-8-M^Sy3LIZ;_ZLFCFhMU@bqYvnK zh~y;x+YWHC)bt^TSGKE`ODwvvBVTIXbvrZ3CvELl^z|hSo*voU^Ur;oebMo*maetj zO(Ji9vXU^fh1DW}xQ63P_+s3w<#qc=&F5Y^n^hAtO~+bnu>O6ou@c^0cV&3%Z)VUX zKQmIiheJEAmA&9~0BzfbaZghm8?mTT`B4G0?|Gogo7xa;C;it=?{gV#c7A`h48Ae=9- zM<+yJ(%RKkv&*a)lCGlG#mR6`f`dKd$L&ICA&VUF{;l+-_->4VpfO+ha30p(vNK&} zebwl}g;nWnEncgIaz<9@86O{!MQPc zN0vT@Or zS^%Gk=8w*RFfXyMiwV)$G7ih^S2>VZ1NvF? zTSeY$ZM*WnZGFozTVJa?Z01U7TalrC>zlE`k;axG;WTzI!?`Ubf2925-T3QOmSuB! zLC0JpqnDvWHEuo%^Fmn{7;jM(?e|*Q0RWyAjM@vIEWnwjq002X4hqKI$!8#gQU8q& zr%Z+=`6|MwN;_6=6dxgP#eU3Fccodd=NvQT=VUkuy8~SwNT~Uf7P#*ErHV!nD-R3z z&5()DZSWl`Z8Q(B5QrJz+d3>PjwPqg|5F%%hb9lfw=bs}Hk*$bLz?SXQN?o+TgDI1 zZq!YAYL`7y*j>$*)pY6$=DxTuvzU6|{m`v_?XECbQR>8CiJYdvX{oW~!hg|rRDWe1 zVfjJzJ=n8$V9nR*$+IKf56D&P!M~-UGEv+Q$QWqh3yZQNJ=$WtIVPTbd2X&YAcy+} z9ni)L*Qy{%nFzm6hX*fX;L=b`O3#S;x*{F1DP_I{<)V z84YU2k!9d`uAgOXM3S%rlA8XRfSn`&q&f-4Gq3;Cx5OGfg)Dg^9qg_*6%FF6+Ge`@ z;|_{x)7q+z7A2Wy0tT6hx)^qTqb4%a*j_=EF{Gn84`a5d=n+Jr2)|>nW>;%W=FVS?`R*V&&WfNzb>($z)!-TMxUww_N zsIY+PP1^p_>$kjl^cnLw05dj}EM7&JPVR!QVmxU!Xa&XUzhU$z3@%%GPnC3?HoqKQ z$tq^CdKjhFvKm-xo%*UKOW9(1H7qR&(;O|8*a}Qc6@3U>`S!$Dk}KUzm46cWubxnE z>f~+dRWc;A=rk22=~%bwj~p>ev$0@=5ddhyDhZec5?Cdcb|xX04^Dhq&W6``t;`Pp z73F^d8FZh>yWLx;_BB=G@Aa6cp;cN){;y)?T@-cUjt1JoKk@!QT7m=5Jz2p&;Gm&k zVW6PFGtggCQ1G-A8UO=?MMKBH1Ywi1uyJ59>yxnxi;z>W+e9mYC#CRUKnNJfpMX^~ zAPwG<0j!6ETew@WRI&eGZsBhJe>~?ozHj!&;FZ49lUjwWO4w;8Yw1kgm@!7&MCwn|J zpw@>b!@$_fTs6GZmlreQYJ>RVQ56^#BK2u(t?UN%xjIFFuta?QWM^+c_7mXM>b&)o zOmg&nIJ2wu%;^BSkJ(>Gu92ZoZP9Z>&8&(Ut@a)16P9T7o5repJwvwjCG+zW;<8+IU#ld90Grp86~idVXO3JX1qxrzQ2)DxEY#nX-Z!$jJ=KpnEDg_!dCuREL4cG7s!4=$lgmh zH_y%#gMld7ZeEK2D&E@Tld<)(%DLtU z^WtB(B%WE8RaV48wU~e_y=a~jlBPx<9cGn1-lgkC#rk`@aJ=DU8=$xxC3Cznq)|!T zGX=(CkZ%x{+M)@ePT^rs&g*$R`ws8KR(6>JGj^_D>Z}HCU553ABf8c%Q5hmcQrzL% z_+eHRX1~?qLoG9PG?`zhW3*d3HEyhTf`mnlZvwNeLIm*lS6~v-)>CP_aqB^)#|r)euxaA ztaOq*q`sMeeV%zwek3IY_GEM)OQ>j59Ss$AokAbC&o%W29C#CMvl9ae_!vShs>9Ax zjGQPv59m58QT*{VMgb=|J^xlgN(x(A@?Z3}RHV>jx#MGc@&m6f8*Qt>XgGDqs(won zeXtV(k)U6gXmzHkK)bNmuQsQ!1zJ-S8XS2JEXQZr3{VS{`5L4M4-)!8F9Q~y?9>@u zo=Jr`Oi;n?b;JsZ z=B+a8A-V1esUzVxx-}^s?}UX00!8ew>SFZ9?+H#FB=DtrIQQ69< zy@r`wH095rpLdIE$EeC@$sVN9?SN#7u3XfPkZVi)Lpo)N7qQkvMBAyrK&778c5Zyh z$Ewm7*=E2!xf3G4K8KVqlWb@h$Y@rzJ_rOCeuG(su(ZKu%r3?Xq53=@O!+gr3hjmS zbDV%%DU(XrQWrY6iYqySN9cuw6sB_ZGoI!fJR(xGI|M&4e@sYj7-#h4{xYohvFQBm zbmb<2&vAt6kmlSs{LUdba{mB0%-S(~e2afrwmefwLX}ol_!y(f@V#VBiD|ng_CN!@ zU=rC4d9pHqUf&A9wR;O6n>tn<7ZaUiRmAxr7{v=#{$slCO`!$1Sdbn66 zWNZ~^wU!vr2ImmhG(F;^g-ZR3V=e!zXTm3VhlVPHD2^rL-5{jO(AXn-VbP)dA(I4|alL zVOUvgD5>6zM-~6^!-sjtZ2Q#9SVJl{WNp*g`Uq{)^putq4_+}G{KD7&@I%I^Q=>t*PFlb=UCHf$9#jzXnwd1@;oD(J zlC^>?f@#{ zDS~~qsRh*&&0A``wrR5LP?yW2dM)a*j`M?trob-Nto+*BG86OdQ?LD^(7Nyf)OFUe zH=-{l#7Mj4d?&!RYtv^TqGKXU9_I}urYK{ivOA$QQG0!c(-IDkr9eFj`zN=#Uu15m zJ*h&ROB;-9#_=@I5(`onO7lf%!>-!jhA+|FbgP%tiCLU8g3S^IHVay_t~eA%Fz`#^ zj+r#VDw}0{bAWl+4(>LK z-5KJ25xAAt9x&H#hzHj=lLt(B6M7;$QK||x&b%Rx|K3og$sH=Ag@!j;Am2!A{hn~8 zRnxex`&df5y^jnp+vO=g?8zP6@E6V0nyp0+PBqoaYS#S(WG4CzPK`P{F|6fB^?K4} z4nBQD9(nbMnN0G60*PW_X3?6)aGRW6f>qhkPFb82*BR`yg&%zhNm>JGJHvN^Vsf{M zu6^3g|L6gej5q2hbDG<90+%zjuQTPsa}yF`;xHXg$=^Z@!p z5D{?f&9=p1+TxfO?%RMSI`CB`qbCd4O{4HJI%-t50r6(w5p>aXWwx2D#TOG^elDW5 zKlf!QVxi4zn*Y%Q7XR!4WvrKPM}m60N)p~>aPmp9la8c>@OlcfUwrc&!?rQQ%(Z`& zYML@-Hmo%wx|z#}ZAHrO32+_0@`*G`4cEdu&c%e6{biEXg$B1+A*^qeAF01uS?Kh~ zvs9sx6fdhG$y5n)J{|8=lg~U4@1KO-x7BVF9ox7*?nT_N-Y?$ql;{5YFf1P){K!gz zBNJa2HD$A?UTQ^(l(Wkk!MIqL#xJJ|Tu!ai+={(LsFJMzAD)dIZ2K{SYTqoR3JJ}K zdB@7Bo#lAg5rJ^41pfYeLyKqp$Uz8B=(nKG_Ns!ko+4x^WbtMtV-zw2s(Iec;?3ej z*&qDZ?(-Vcfq8-1^%k;j>5U=XVqhe8=2;>>v$j}s-SZinnOBr;S#Ma8#WL|D|0M+? zv&);6(pE~G9Krc5&Wk{id7>RCZX~*H<`8fS2aZgb>W*nNI3a4*be3OrM2UJqka;p^ zq}wqEWLTwB#hS*w>yoc@>{jkprcbzcy(Jzq6aot=hTY7W6}nyH)ozy*KQIysat#H+ z@~o7@HuHYffQG>fv10E8LXMyT=eZ*6UFJ#gZ!bPs6KAgph}60Hncl!oe2BAwLs2;S z0qHYaq?g`!l6JO6w*NYC_tm312I6X%9x}qN@OC!`pgD4hQH=Y;CYo0 z#7}?=j}P%krv9o42_5%$&HkY=L3P{9+Ngv~_wuVl7C|+ z*S+u(yysaG@*kHfMQ_0oWu3l{xk%;QF$jm3!e^N*9YA1Zz-l_;~4a|ys!;*!GkQ^%~SW1)OX z<+9SxFLN_?b>4Hfx2CO^YFHu}_XX&ppPx~3pJ{o3xb!{HKR%P4LRQH&&Qq4+(`1`1 zEtJfOa%4gQeLt`9YiVXJyPc#4GuivW>Ze+X@%}P5iOxqmRna+6mD!&t-6ko>)qn#% zLZ0=bz%xvqaH)&$x*4g?Yn5ue%*f0n9q2-huip)rP&yQ@zvgE2>iz+UH0wrc#(^n+ z7R27m8)D*s%X-hv7W1D#ZQge%HsV7lBLnKU~_?XEn`Ntv8?pfuU0uz zjxJiA*L`wr)ue`IyoUyriTH=4G&O#fVt5Rhx6U6;6T>-|j@S(h@|d_g`D9CS1L$5S z6P9=G8pF{s^Jw}Eh2d&^r0xP!%UoH)J4nwsujJxwo&EaB@nhL458pOr?b=v?M*AM`-+P@DFg}f(`RrL(tx873KA9)9EHD^ z7r;BkXiz|O3=lX1p;?(l^lgNdZGVLzesMStf@wUTdi@XjB%FG^KQ0jY;=pz46+S#Vm# z`q8pZ5h`pH7S-oxR%GsHQB{+u!oTPXbNt|3$31h^y5KZ%1;N3# zEa7E!8-&BjX`04-W;u7*XEBLS_YBhXS?qH%ry@ZmhTLKwOi5HrnELIRsjaG z80$Ez#U$j`Y-`IB;RhPiLT3eL204$Tiqo};Z3+2+lCUo#V(+e~MuGI~ztD0^*61f8 zZ(uqDl6RALQ+I|6om;J~ZlmyDGLIBijRhefB525VsiRjV_!m}<9)EPMbLh=I&k+rH zf%&$f;iGitoP$@e8SS2;d%yG(@|(WZZ_H^*SVHtgvrjQ>-;ff*%dIq4s=<%@AvWqC&+Ch^s8~FIf=2T;_ z35%-e$K;Y5Vk(K*MAvj){9a~(6#|bsV-YgB&6O)vrfcf-8r6oqVc7rr_-r^Erp}=8 z{P^95b@GU1|7pSNK=3_x^E7z;buB4 zwtVfpz1?BEvKxDHrq^C_iOO1&5p_=(Yc=CUcNHk)sbs?ArTi2cOk~;bydHTTpm=St zo)CBa<65_hs^JHn+p=O?ddBoxwFdpH?_8x2V2r6P@;qy5t@;hI?|Ef=0ioDg-WTd? zM>>5?>t>SDq8hVdAN#<9dBXxPOuqVrs{lhq1Fh^h{y8I@0xy>wQ##?U6s4@ zrnachv?kSt{LoWJeXZ~_Ji_CWS6;(OJc%)q^GmJ7Ooq_I1!*}mtR{~ zwnW!(2XzDPoA!5Ke3gGF`_6J=M}@|LTel^+$=Bs2GHY<5IAS5tD(xsIVQljzJ+A7L z%lgn=#N#J7@T20_BkwK35hpZh>WK3aq1a|#T**u_iK_I2{~5v$80uDz7MSGl8Eb4N zvr({}U(~&w*gBJG`Uwb#x8)219<;{eR+e?226urq`%sJ}rWq0wK4(>KGw7Ra!Q}%cU$t={GVB#VQM1M2PxGh6Hz7 zK?H|f*^+Qy^A@s<3pa|FVOVPY*GGe+?~fRKE|1^5fQEm0Z6JzsY*)Hqi9$Nj1G>^2 z#fZQr7a87rQPl0kz@8>D7BtG)8se+#X#P5{rKir>C2ol{@m)l%gWXDb#w#i35Yw+0 zp!JJY*ZUazU}XHEd~DnzD+qf{~X?h2-20&AJ z;B2_ii~a7vGs-yhs*L%7MEa5ikyC`N!@OX zo1;ZGpZTDubfYQSpuyw#iDgxz`@GVD+e&W~VdNO6yqEJZ>gFsLh858${4A>U_qz<1au8?$G;bQ zXX}7wcwDf&FPtNCFL5A&D^6^GE5%83^?3y&s*4(@cFuy@jNwB*>;~t}lDnYV!)9oZ zB_eHKI9~bUhcB75Pt*oKEJU^sT!n~2GwsLB)pbnf^=BA@x^2w^t6Jl=;MX5CnL&Cu zn)k{dS9G?^mxuh1KQ}0AS~PX@w9q?4f0ujn))Y#+E)Siq)Pn&<25auh~i5-LK4G`iF=*BG0zps_SVF6>nQ zfr`$q`j5W0-^90W-4^%iGCJ*Z8m+M_5m$w}jWNa?X-wdva&{i=9i&n@atnCbZZr{M)T*r4*q4rd}Y}1>uA8OV(+m$j*aB zs`*qVYKD9~S4@v&+aWclb8uMA3Fw^DPKRwgeWcl|Wb^tGFGAqAre&HT`tVvDGdI#b z(YRYP>)~j3k&Ai4)y##7RQO8~?WD&cJBOMv>_Z0wkSmB(Ky~n`nd$w8(_-8s3-@C& zxbwCzDu{8s8UFGiAI$CyI90GkCR|3|we9^0AoqIU?85C4R5izcxsMNxKl$cyY?%#( z&Ms9oJMGYCi5eZEvztavbQZ~Vw5rOAQ9xQOaAGb()Odp|e4Y$EFDb$`q4MbD?A9+! zH-&^H7ng2PfY7Dx_w87yXgf>oL7w?$w2)=k9FZutWWlqP_VPsDX~HipSm!u2&w>-@ zLlr3!K}4xJCmdG8G%q!~9J`@BCb!rwW||Qa8RFe&!l)Pf;#Y+JO^mR`W6p*T@PHFp+0qsFq*Hnt%Ll)v=_piFSdUKb7!-QTIrydE1rx-E`OPRpk5EGTru$S{x*;c- zl7gW}xnPM;&4Ih=pRv@#mnT?DSx}g+)3Uxv>|?OKOn1^GRPRCaC*9|4qg$G*%^0JT z4%kNg{Xtk{$w{hB=b0mwn3H%oafaSL59vL*N#hO(I!`0a^6ioDo^sD?F{fF(N?k3P zB*Sl-9`=|Zh|*I*HqFK_mpCfQ-zGVJM-+t-=)^4@FSk6m{XWQ?TE3j^E5c<&*YLOS zO{e=umJ`L#4k5zFj+dOvt;#$>*r_sAEegkwz|MNB$0b7bEVKpo*SzG_wx6Uh;)ppH z{$WX5MAS`A9wC_Ew4i*j1qZ``E6fDSVZg5h)Uk|#Z0TtzxOv(E$*Y-hy95DoeN?NL zPRGEzENx~Np$ATzlso9}lAG@zC2d+fJaKQS9gy{VdsQTlEn9TTO130vd!ORKv3(Vi z_;Pasg-+fV`2sab<^^N6^{P=LHHp6hlS%nv55188!pNb}k`D|1G=`h|W=y&Q)VN;SAWN5Ymd{<{WK?TK1k8PX3N5%MD;QwOk}mMNPH(^w zmN9`*;%nv95f<43O`lb0u#Jsh*o{jt_H2q$U&jMDtfFa-^hqvw1~_W`gw%2LQIink z+MZg?EzR-^YX0gv(@MucwX2j-uz7z6+rOCT{TMrx*1-D-f*?JexyyUQ$`KnDP@0;e>o({_;vDU`tDm z34JJVWA7B*LOGmmm-#joXa=-lcNw!9OpejPpUA+0@RL&8lHz7ovQ7>w1zn{XZmkgV zMu#AGj`D%0vOPQ%68#vinVNm1Ls>S8@mAP+J-@q(W7T9>1kiMrKSRE5!A}JR|CBQl zB1a|11STEZMzhm|Lq|l7EO20}7BLQmT7i%h3~X)#>AS+H#Bn9Jh}Bp(%SmoyQ=DX@ zAOxTOc3iVISi=jUdhi>)_=*7a5MS*sp-HYaT3k*$M^}I#;svq&kWrYzM9FDc4^AtT zy=b{cr0X#ovS|r7^ne~G<2viyL*G?uv5AH<;b`y23Fo?(AKh$1>5Cd0PuVP}Hm`_$ zVC$41Lo`*LAJ@GWOlvj*ny`We#%9d5TIG`D7Q?YV zAgkSjqS0Uu*%uX5`9DR5dtUgp{1)52VFSnTVxPf>n|j>7B<>@`<^DF#oa;sYytt^H z?`bz=^N{c}mOCQvoiaq;)!(J>TUP%yh7B_;PlcE>6&gq_C!Q)(DIG&e^=&oWIom;v zDrGW1)Z^|esBhkm)6vAKxZ&`8$@NYPl%4W=o&QwabNgL56fKU)^0daPfb|bRWujBN z%fP{ASak*U&-qVa0!q%`xk(DU)9REz2<84lEG5LB2dUH(ku2}bCA|Yv*HS#n^`d&K z%b`G_cS)OQE|>5N^AC#P#=5N84??AXFcldd%BlEZL`Da-JXZ!wo^xY}!*ag5)4Hta z!sNg&Vjs?V`)MyyQB?v9)Qx;RZ~Z;T*R#U>n^DZnMkVv=QtQM8%-1Ep;Vg6l_gTZ% zN!}_%G6E>=D$U!qWvU}p%0Ku3A9TLt)C^}lDNrB&!JiXF{WZrUi$XmahYC&35)Nl2 z9qsy)?6JtE3QfD|o7Y444b>*!>3;$!Gj?hp6TM=`FEyWD2@RTjrwb7XHnYku(YN)u zR&7SCe3Kx;H`_NlPdC(9zMJtny*ANqOmi43v{&~X7-Gj03dVPyUJ$0`>7Ep7S~s|{ z*yFu&BO!2(rlv-E(Jco$ekGl-M68vcP!i#$$6+~W-K6pgEyHR&KC|46!LjcpVpBITbJh=MpHwRIo+2}f&ZbVaW>N3a>Nc3lSt0zSVLq}nU{34qWWB{qv7xh6W*NB}GNCDA!{>{4^> z72lwVEB)EC&j0b%Zh2XN&=oa!Hc0s7a)6EC1dPy(?RF`22cs11K9|}b|U|P;n}lZ&GlRmoEiVj zb}Ij%>N&Ii+2+Lt78p{=HO4Kv9A-^!14`d(LrqxPwQNJzWw8~qj1Q(Nev?om9h?db z6GGK#|9tqr4wa$9jFq7SdgpLg|B-|id;m?*D3;}^ytSPosggx{>th1|x!6jvlC_Y= zZjclxx@$0w3cND+Zm{e57DpTUZm>$3o1dCZ_qd@ z5uaz^m#Sb?PM{sT1OjBXu}a^2fu8_(wqa>}q#?pI1N7bVXP{ryhgp6VRWYCIX-I4E z-aPoxKtPD!!}2bi|BSc(KOhHto zVQ7dy$Q!Hv;xgdB06pNSU?ty=dM3Vf!k25e3_$n;VlbLq_%Hy1ONEa?s?@rgYbmRm z`JtFY0OJ?pU<|y!Btiz&ebicGSmjp`2nY}TEJmmWWHFcg06aczHVPM60ErVK`$8~S zGE!DjV6eDo)|uNDV@o465S~f|kiwcE4jPD#fR}s+$&w*_kTW|C^GLS`FaLI7U~XlQ^iDT?=}ot|=O6*6R|u=TkI+Imv+NwY~4^WZd>tT}=*&H{s}tmZYAn|#TKAkM_f zvcG&wEPC7qCL#h2H3;mu@kSVUF;Mw9dLAdOprBZj#cjYnv`rVD+f}6Y7150pLd6@O z6s;Huhh{9*nG#c3Lg~?M91f60h+Tqro>q{pET zZbp=ZXgp!zU5x#O61Y|s#UEIzos541s_rsheR(Dg@Izx8D6_zZG1DB zT-XDd013i25#LXq0-$TWmi8V83yS#~wWlaevl={sQHJalamMzb0rX(p@dT*GHuk3 zB3w?CCb!s=QUU7od`l1g5EiUS;%m44DMroVso{ERz*4taTgo{&r`$?fIS0#t1`*Y2 z?oGPD*>V~(%AfUMCmfOy-^Mt2pn=2zU`89$O3^xjn{r5b%Ulc%-w7lyU$cm5hac#uL8TK`0+0 zxz1_=?Q0Z3;rR8FeIXa_wR305K?qt2k|gCa#@CP4*m_m~bSHk=z6$!xUF zt_=bW%Qw@4IMad{dIN0s&6m^5Wc$h^*OI&13W(?xs zZ0Pqp7UAGtA>y>&$w_H^?MpeF+TjZos{zfDfU52>{q_?dg-7mz8A?c$yH3V-mrj4{ zg?OhJfYB{?j(o4$7~m+8co3eOj|VqKot6^5_pNh{-;;RM&*QAJNc@!08~31L3uI7F zF|$~S79FwTC2Iqsu(SPw-0!13LHP>iEk`h}vknYi(+_qexmc2`eaD>^f1n)KOL=JD z7p=i$J5w(Y*^np16t0Jg(?zNa9Ypm7VxXuDU~On}joKi=ecPAOdW}lI(N{_#$z9k#;q^x3IzDd%hw$!h~A+c2L|GmsiPmZS;b=Jw%-=d1%(%rNNDP`=SIN~iw2v0rIQ28RTtwUG?fDP|0hEEE3>A_A z>Uhu@9u(rss+#OwMlM}@{{X^ej+}->^`6;+C*x;}aY0JYA%zTq&$(6t0AQeX*1yPg z29Rnl;<{BiNnq0GHV^>Pn%>lj^MymbmaXoYFLn}&z$xLfFLL_R5SVth-a%0C$k4)) z-nX4;ogY=bLE+sq&1!j`HZTo9bxy5J{JPpq9 zvdGRfKlU5Ij-w@D;1U76+)3eSQ1y;`!=rK&@4y-c%Xq!!*+5%@!Yb8|^4R+c-~vZ% zJ_v&>hknQ}l?o=EJ%Y=R8I;>6ikRn1FKs3)IcrlF90{GAg8@J{r`l#dM|aCwm0i zx*~^SuhdmhPvvc{KEb06`Llv|(Gj3?q@Oz+1zT&gKHvp>YzfaOk=2fI=r6fLX1?dT z?PuxrYn>aN`u*-{G?z)D{O_xr!U-8-iV|Hs#5&YpIB$cLEXY~o>H`|YUa$eW*T0bu zt~?>#x;WRF6FZ&oXDDx2{;OOqq8Oy;4dQ@6{VqV4H?vPfQm#>LP=_=Y4Uii;0?Xkb z2sc=mlpTIUzJgU;GdgicRV9cp4#wj}p_GgS_-p6|&ih_l`P%#S=z5G+GVoxY%<@+| z;{C&p5CM1txk&}5sL6q{Bi97+(?>z9O}({2i`ZX#?n%B9nOj%#`-dCH8q$tPVab1k!qU*Pa%U&)~^+}%r zh)cx7>9O?^h^MWv03XJRz7lF?s8%yHA>5H0ipjX_&&19*BOXhUM8$BC!8x3|1pLPsF`p;JfOtUnXL_^J=+m8P z;(U|a8%P-})`R7m)MMWhBauwG04>Y1GQOXjuK&pcU2yUPtnVl-A2~1@yNPQNIM0{F zVhu$yDe}JpNO&KJFAa%>i$vCi?Wwxy=pxPD!QI0>?B@VP4nFen9qU;sMR1s6dU4?Zs41 z%=F}MB8)~?Hn*9Gk4K-Z4qSDIAOdOkR}5bQiFgYszG>slvSz%xf=0_|906&N1>h>_ z#zBDm6Cp4*bV;!-#hMw{#{JX#-ayFl6ea8sM&y1j$>)jDvopS6|1ntoe$T#}03=nmKS@se5(78KH=4m4K@rU%vYI z6iwgx?64lu&I+zMD>h_I%1QgljuOBWI~hJ>fI(7~s$AVMSkmpLE}pA(U%uAZzhm2A zL#rwgo(E%0pYA&-dr8*{jmUO=)LMP6KDe&_LG52Fju|B)I&gE$y4VzNJO)m(>|{gg zlo%C`XsKtPAn8#V2rD$q!YVm$Wf9=il&RfyySQFXwuzFCzE-uNN&h4&gAZdA#ty>H z)<$^uSCIz-)h#G3;1E52^E1|C=XmuKkk&}-1p(CwZOlr;UPkWQ%!8MxB`NA1Qmo0G zHXSn6i5DJ+AUY)RW~qbK9(lJ7%G_kxshpUj#NShfZ;_s>iz8gc= zVp4eTN2r!+0cCg$ox|7>$J!H;%`k_gM?G(!VAy2wH^e!?XVx|1uLhZ;w-whVg~bvC z4+3Ih#5r-iZUECX2V%tpJgIT^57)Wd0xd5gH4o8;e}K@v(*WN4_;|>(GxJXX`q7Kj z;A$8!-GO=4@u$o~1A8j&b=SmIKLH_b^m)2^+yF5o5X@hYgE7UBxuM2spuiG8 z3;h@5;TBGl)@Z7CSHou?_bwyW`2mXjm(YK~1q%YfUkwcq8HX1E;9mU|w_CHU^@D1n z%-vJ{@F`D|BH_h2|M@tf9oS35{I%o!m%j`2V85|FyN>X3{7;3)B0i{#@bLRz1q!G8 z;uHM6kRGPyt9r??m%~kUx50<EWymobMmp|FfKbllcGZ1phb<2?+rS0|f;I1CGXD z7X%uRg%rH1Jqc1eSB}Z4?gX!E+xTq$TGoC(4GDa5v9(PsBKl}qTV|kY&9!j@;ZILe zbOOs}j2EX#5i2=JUBcE?)c)$Tv-c`RtW18KnhblYfQ$nzU6$w0l$+imIn1@k?c7S- zEGsvG+shiIS^RAs_LAsn1w68*%a+rKrXxd985;4g@vn3x0&8=Bze{&7_W!Ua5Y8b@ zQH73_mK{ixEyER`WJ1!(Kk zL(0Z-Cep}~hvwfpfbQHo7^E*dRJuQOR?oRtn#LNNyCZo(VM0L4)bt)M0c1RsOnmaD zw8`G{!Q9I1ll(UsS%VS~VG2SFt4vFg$x{fq>(WfH)rlzQz{iExZ5-5D2h^S72l_^e;j+cQoZmKj(-R+E}3*EbUaGqmeB?5bc zu-Dm|i#l*!LdX_ho>_pM1z#TZVMD@8_24I9L_&i&%SnbJPEI`L|(SP_wl18kjY+A>4ty2fIDI&UOVt?mnxOCCp zId2&J^_om?PlNLD`Pd@`8u*t5#ILirzYpI6AkbKVq{;?L=O7VqoZ0&PinHeUP~n&{8AUZ zj+ir;h?6mJo%fzrmSbLeNSTF2fFv_L^CHj4=sgKq{y@S)0d=jR0&WvZryas1%l5dY zz=jd-qI`@&#Oie_3;%bPVGO}97jbK_ED<+_*dhJm9P+8*R^8;WJXkcM@{Rr#h~p`( zV3bt{%fxw8rp_ufcHo!qX=|`tNOa7Bp%L@1VDtPzRtN{HjcJw?lrUAl8u^pM{Xe_} z(bMqcVK+I8b+ij>f{E;y)#W3kfPYNq7_yTkn1#GStNI{*b*t!t+ZVXCVs_{|yWwx1 zU>I6Y!6fwV&L>LhC!jD5(|-a#ZW6tclzCFHhe^oz&ZpIKG9Mx9cp1f1Pfn2ZGN^0-)fa!3QUQ|1A}O2Hq?KiWvCBz|^*1m6 zx?2YP3HTZ+tkVO>-NjTvB+IMwC5W#T@ZH;*P^j**{ll*3^w5u@ga<{s+f1BOe(NRI z^}4I}5Br|eeLspK9z@ICgus6ep}x&jJQeEwQS`07?#jz_Jt%I?Rqr=Ch=HVqS(eM!La!c+*d*@CEYhB4P;%-JEa`1EIa_uA2H$^XyO?ckM z5g_ohT7MDmCKCR!#lax(rCRaJ>LL{z0g@)=7xi1m9|z!5-)hWkmpnd@q^j|dh^-S% zLfHX4bCtFAL`T8K{UlTz@GLKun=DR{txaTU-{gc#jiII;bOQ3fw%^gvI#WS?VRDFDO7jkDOqGZ z`tc(ITDQdFU$pe*@S9_3n7!QhNLoQ{U>%$ z4l?hjUWGXsHCNKnW8dCJ|Hgu^6Tx)zo@lf%LITUn2Zf;RQQ^x_#21|C^yKh~@oll- zK1#d;a!%E+JuZ0CC5eu}ng(^ESV|tQFE(f=9yu#~F~h`Ng{Fm#dCw%6?*Zx~YBLH` zJD+b*+xOpM$em?T6ca~7g3ZemqAzPYf{*HilGA{*hxHY$Nd;_o40zs&FnFc~qvV&Muc2z!&J!ny7-(#JgJo7V5~PrW#Ogy zofZyE)PYLniQH6bCCbu%?hGD2sGK1iB=$Xm8^Z+Mx1s{ReP;xC<00`^d34&4@HV}L_mu4rhpWwN(dlD zFbD)tR6s?FG-*n25+H!|-b<(fLhq2!L)91mckX?6=DnGn*_oa1?6==Jzw?`K&z`gS z4CG5x*`b+8%9xQsZjQ(nQlQ_h#Ie+-w6g*5F&FI=8!#Nol(4 z7$7JT+M6q8i&W#3 z&2DabBs70UIq3eT@a!M+OA)<~pdRh;Xin4`iNM33gswT_pXeZRSLClw(!}>sIF^jO z0<)9owYrKw07umw?W^mNV7uooz`(1pA(eP$z*4g(RZ+hqW&z~RlpQY(Az*?Ap(1+# zx#a(jEp<$D%d=jY_w8w1kB1G(UZk#fG|9lW&d%F~gRWIpBDyPXKI3}b{puw7F7ESR zZ{-HqL-CP?wH5u^QxT8xEH7%Z%iFke$_n8Q4sFs{i&lLDob^Mz70wvXYlE7hm{+x* zC1$gEmsLODsCgq4<;@@&3~Z}v^8P9|fO+=g>VraicFkYMn1FX;4CcdvOGSj`?M$)CO?`>&60((I@P=HTlJ#<}X zmQg5j>jT2dHSucmyEg$73Gc47cgmB%1`fKxKaWJ#yVgA)*cml9Vkhaox;f}9{Q($6 zv9zYInEr|o<)?ys(}&vMr4@)Qwvmt4Vzz;btNOEF4d02WH9*B+Dr6Lg#-2O~rw*IQ zpf`bBvW)1<-56BfnF-3vatD_Q4kHy%@81>8#IV^ceRyKz1JjET%1XWQkln-VnY8;d zJ=DD_P*NvF+IPkz)0ni@V$5Vfhpez)s3U+YJaOaxxmEr6dtz#?UE&g}hW1z#>Fbdi z{Wmk@Q7xM%fxa%Z5p46$jKl9_piM1n91%&jw3T1x-syFJ|Zh|39 zjyt{-HU~o|*Eg+r45+3|pfe`fbKeYEQsFv(0Ky%P2-Y%02|Nt4L>a=X9YC^jKZ`7G zqgC*Dz7Vm?2_C0K&~SRV{sE{aqHY=!Y)02$TV#8lG&vq3l7)w)(k@7iB_mL*G!9HRN>fGr=O?|AZrs%^8=$ZEXSY;E*9eA28gi|sK7N#2hV zy)MXUt2={V4sCPz#Pd%OfMY09AQ#jQl!!Z_K6u+*P!&*5x6nLb^Ogb7joG)=Z%fl* zQ-1H+Qo?VeYWy&yc)m?oL;ePen@lozg{jz2!W+39@<~%Gp8vf8OtBx7cLOs|G0Qqg zQku6tmf7=KRn)J(#%-?MQ66BKJRJ4Yd%;LnRpO$f#G-?bDSizZW`&S!MY3kq!P zai&VtcSq#rR-I9XXO|~mF)9XO3?*Ap)8H6tcuY=ew}!b$R$~ZFy~o;nycL&JIj*sb zqUUD-RmS3^GsScco`f+F^}>ZD*%4?m!aY?{FUuZ_eVy+dYQ!E>7Q>kng1<-eJo6fn zx+I^Odig@S!xG%7E`!+wa=en_!MPi!=PQf5D+ca)Sn}bKc0pZ`90HkSWB!fS9YkU6 z*C+ANYdL}EmcF+Nedr#!@0dUzclDjh62o@Q(0+Y`T76AeZSDGOUdFs~+1_b`Lt=AQ zPNvugUI*K-r@@@N=)#EvFZ(xak;_+1OQZC@pd^`u{F=)6KKHvRGH^!?1LmI&J8Mvb z9}(3jIpvR0R_PSS1s#?i!&i&SgWB>iyIJxzFoRh2h8&A7%56!(^I2yY)Dq<4N(XHA z;TH`GxlUAh=TyVHxj8_Y!lr#T@s)0L%ODA!aMYNAQtav>>ryp%0k@x#qPN;p#_Qg{ zH`KBJ*f>YfU&ZdDj}hsdTu9qmdQ_}=!_-ceP%nT?BfnGrNVb=F>w=z>#E>1CPA49E z*)A*`3a!`BvGH!_JzU%zxHQQX`2%>|9fR4Qb#7t_ybFKBs~}|`-pK%Sc<7N8`p(ux zu6{Ur$ConR0~Y{V5$s96h;_#MGYJ)A&}rMd2}IF4pMb66@_!hXCZ#xVdbrtxZ=ZQgi<=)^t7g4#QL zjp`P~9WW(rhz?!j%($nWQZV*Yly=sb)uE129 z0cyeVU*o_201781%%T9S*_yD{DVgWs@hFUd-o&wA1R@;Zw2O8T)?NnM z_JlZpmwWp13R=a{LW3qBIu?%RF7b`v#jf@a0tkq#dC6IJGu45eJfRZ$2jEBL*?NJ) z0s8&fJ|iimz9hNt6gJ4Wgf)tHtk1b4vFq0}Z;*IbRb;jM9f8-HS&VM;fn}qo96BNQ z4BFi14M_+rP?2W^;buQlHYm#v$E45{6ZZ!fvizEPx!cyb$Dy*FHB-`;CX~3M*r3o9 zWftKk<2*VXPSrlk@XAvN`?d3U!}r>vm;POV&(ZZG(|yx9G+IPCIJN}&mEjdThSc}B z%gDRZvHn1%1{~%1B9su<`sis?{K)P54m;FLx?M#bH7Zq6JceebxQP~@&UjwEpgtvg zOlCy0oR|CX21(RhHh2LQ6Bk#g>nKJqpgpJIdqgSQypW*U5?NCE2e8IR&=zWCN|uNu zNG>+Fg0l8HR!P7_#zEY%{nGmCcq+eA(g!|fafG7y?MXZM3#k?$DDcLS>2%%Zx9i0| zfRV|ut$d3y5tix98~JXR_-E2UG_nVe@}Mis!W_JJFqx6#u!FRbf9AC#Eu>f*Ug{8Y zuR;f)dbbQPgf#b&mXZyjNl#;02I#fgnOAwqup#h8h6A2aePSe(sEZ!;Eb)GHa&NMM z7OtH6TaMgb@5f)A(I014tF)B~fB7Us0l)K@WNTt`GBF49;<}T2ZmeWzGn&=G%GFtK zdxa4M836P~a5?Ck2x8M)wP=%5MO-0vTsbc%$(5NVobSC2Y%crd`-X3J@wYqiVs**B zSc~&ZpWFK>O`EjKh{4T+plbuQT94X&t-c{(SS@jcJF?cfr~4uyUmR1>MXtLWE~@boL60ZFLce#G3Vqk zrPAEFO`$HJTHX4W8b^@u9{@;>nt3Y37RE|IN#vT0e$+f?p~BAmDJZz<2r+eo9KNJn zncB(@Rl1qPnOiEA!De8AEib59OSimpgi~}(d#!KTJzq1pb&vODI_p>5DR%(%_e;X| zE%rW0+VYB5$^Ywoqe1vJGX`S{Eu*ALXIfpVM#m#j;LEHn2NuA}4<1FsEv zWeN?JpD9jn>s%9)YJ~jpSrKvpO#$`7NXyx%#C00_K}UY1@*!VUAH0aZVVAe~mecVl z6A4jF7wAmGjW~4HQ~!AdhV7ioCz&o(Fz|`L#^1H0vlkkZzcRfVYIm@eEzTQcJo-?Z#8gVZ-}h4XtK1UJa1N2)3+b}4s1nZRTD z)8oC2JOS9d=ceXiN`}*jfrZDNUHdD>%XeOn{`Ky|l?aT21`tk%<9Xg9zuh-Kl!jI zb0+oFS;x*vv)gkYos%&@IFMYgzbf6V?tMZYFf*(sc8@&6MeEAWv?FBw-PI7|MTQ7o z$r4MXVZ68q% z?RV#Ndi(+8YR94!@jc4fzz7}{9UljC?UV3o%zK`TWV}PKJa-FRT(qP?YY2H@4a;pZ z|HP?Y<+X_?O1?d)iq*dAu5}7sj(BoZVL06NV4#D!*sx0@cgkO}VD(rKcYpBSQ0ke^>rY`be4li$-gSoR zZnMa)FVu3-d&Jf2D}M%1{jA(d?3nOu$Fp$H2#}X|uOhk-sm7UnYC1XCS{9D#^47#H zs+U&5WBTG@I$xu!&VTQLmT#qr-NP8#fB0-Y<41{OUqy#3`X@&|e7bfnpUd1vqh|Et z-}JY5)SB(;_1S@xyOoN?jHwFSeAZBV7|@NZ*hTI?4*4NS#p<)FX(fc!Q}?o){-)d{ zX_j3upy1SdLzGgMb?_T4zAXbyqDV z%zQ+}fnUELlrxp6FJRhV{KS@Fw2n%0Wsy7wdA#vT3;n=vn2!;6a}Lx}b-qoa1f((J zToX9ax`lkSEj1e$J9Bz&4XimYhNSG`$|u3dJ?Ahlv%;JJkH`iliK676@v!vD&~%vP#~6 zX;sSWBFTnlI2Kj-#c-#;cIAm_e`8kSAySj=pdl~g%8>Is=TB)X=wJluy9 zHt!l#b+NouERxrn>1?+7O726+M*V1%>_ZiPSP9gqF@HSi04Iy6w{O`4LBb^5;ug0_ z$Iaz}v!PT=eXSE!B)4}18SSR$DdtAg-PQ9yU2mqnm+1Yk%Kv&{GfKB8OaW81t{nW+ zXj6K*w5%U0!=%4RL>;5YmYNPDWqt67pf{>opVhuZy}yw7=h6U)+*_tZc&?k}w$!up zP3u)TEbK^?H75`sty9m0S%Jw0a;n_Eh4A=aIYNj0E5%F*>yknO*!m9QurDZ-#Rz!? z%F^Le#rISsMgg@Sj;?f<0$K)5WO@_WNyz?E)L%)$1OyF9^xbCA{eUMab`Lg zJZH?!OCss%WCyHVX96|5-P#81f=qIEHv2({)UOA2{QIqeixQU48*G0b`}d8{NHixE zRoj(L2h}^D(p^3vbX&Xs8o}-+Ea~nG1bzhR_IKmCknZjuA92umg=e^E2ePE@TAE}2 z02bVfUum1r+X!~8#IQJxtJW^4`ZkBGhh7a4U1X5pmB_JBkn%dwGUneMCs%Fri;({s i3A{PG$MxT0Y2@12o4_SmPYC%g)Bghu&U5+z literal 0 HcmV?d00001 From 1dab126944374f49ffd2014e9087c7276a49e9eb Mon Sep 17 00:00:00 2001 From: cat Date: Tue, 14 Jul 2026 16:46:27 +0800 Subject: [PATCH 13/83] =?UTF-8?q?feat(openai):=20=E6=94=AF=E6=8C=81=20Agen?= =?UTF-8?q?t=20Identity=20=E8=AE=A4=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...ccount_codex_agent_identity_import_test.go | 47 ++ .../handler/admin/account_codex_import.go | 118 ++++- .../handler/dto/credentials_redact_test.go | 4 + .../service/account_credentials_redact.go | 2 +- .../internal/service/account_test_service.go | 89 +++- .../internal/service/account_usage_service.go | 22 +- .../internal/service/openai_agent_identity.go | 431 ++++++++++++++++++ .../openai_agent_identity_compat_test.go | 247 ++++++++++ .../service/openai_agent_identity_test.go | 177 +++++++ .../service/openai_codex_models_service.go | 12 +- .../service/openai_gateway_count_tokens.go | 10 +- .../service/openai_gateway_forward.go | 30 +- .../service/openai_gateway_passthrough.go | 12 +- .../service/openai_gateway_service.go | 4 + .../service/openai_gateway_upstream_errors.go | 1 + backend/internal/service/openai_images.go | 10 +- .../internal/service/openai_quota_service.go | 76 ++- .../service/openai_quota_spark_window_test.go | 43 ++ .../service/openai_ws_forwarder_ingress.go | 15 +- .../service/openai_ws_forwarder_payload.go | 4 +- .../service/openai_ws_forwarder_v2.go | 18 +- backend/internal/service/openai_ws_pool.go | 65 ++- .../openai_ws_v2_passthrough_adapter.go | 26 +- 23 files changed, 1399 insertions(+), 64 deletions(-) create mode 100644 backend/internal/handler/admin/account_codex_agent_identity_import_test.go create mode 100644 backend/internal/service/openai_agent_identity.go create mode 100644 backend/internal/service/openai_agent_identity_compat_test.go create mode 100644 backend/internal/service/openai_agent_identity_test.go diff --git a/backend/internal/handler/admin/account_codex_agent_identity_import_test.go b/backend/internal/handler/admin/account_codex_agent_identity_import_test.go new file mode 100644 index 0000000000..db55182b6b --- /dev/null +++ b/backend/internal/handler/admin/account_codex_agent_identity_import_test.go @@ -0,0 +1,47 @@ +package admin + +import ( + "crypto/ed25519" + "crypto/rand" + "crypto/x509" + "encoding/base64" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestNormalizeCodexImportEntryAcceptsAgentIdentityAuthJSON(t *testing.T) { + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + der, err := x509.MarshalPKCS8PrivateKey(privateKey) + require.NoError(t, err) + privateKeyBase64 := base64.StdEncoding.EncodeToString(der) + + item, err := normalizeCodexImportEntry(codexImportEntry{ + Index: 1, + Value: map[string]any{ + "auth_mode": "agentIdentity", + "agent_identity": map[string]any{ + "agent_runtime_id": "runtime-import", + "agent_private_key": privateKeyBase64, + "account_id": "account-import", + "chatgpt_user_id": "user-import", + "email": "agent@example.invalid", + "plan_type": "pro", + "chatgpt_account_is_fedramp": false, + }, + }, + }) + require.NoError(t, err) + require.NotNil(t, item) + require.True(t, item.IsAgentIdentity) + require.Equal(t, service.OpenAIAuthModeAgentIdentity, item.Credentials["auth_mode"]) + require.Equal(t, "runtime-import", item.Credentials["agent_runtime_id"]) + require.Equal(t, privateKeyBase64, item.Credentials["agent_private_key"]) + require.Equal(t, "account-import", item.Credentials["chatgpt_account_id"]) + require.Equal(t, "user-import", item.Credentials["chatgpt_user_id"]) + require.NotContains(t, item.Credentials, "access_token") + require.NotContains(t, item.Credentials, "refresh_token") + require.NotEmpty(t, item.WarningTexts) +} diff --git a/backend/internal/handler/admin/account_codex_import.go b/backend/internal/handler/admin/account_codex_import.go index 01a5fbfa1c..8abd269f23 100644 --- a/backend/internal/handler/admin/account_codex_import.go +++ b/backend/internal/handler/admin/account_codex_import.go @@ -72,20 +72,25 @@ type codexImportEntry struct { } type codexImportAccount struct { - Name string - AccessToken string - RefreshToken string - IDToken string - Email string - AccountID string - UserID string - PlanType string - Organization string - Credentials map[string]any - Extra map[string]any - TokenExpiresAt *time.Time - IdentityKeys []string - WarningTexts []string + Name string + AccessToken string + RefreshToken string + IDToken string + Email string + AccountID string + UserID string + PlanType string + Organization string + AgentRuntimeID string + AgentPrivateKey string + AgentTaskID string + AgentFedRAMP bool + IsAgentIdentity bool + Credentials map[string]any + Extra map[string]any + TokenExpiresAt *time.Time + IdentityKeys []string + WarningTexts []string } type codexJWTClaims struct { @@ -492,6 +497,41 @@ func normalizeCodexImportEntry(entry codexImportEntry) (*codexImportAccount, err case string: item.AccessToken = strings.TrimSpace(raw) case map[string]any: + if agentIdentity, ok := firstCodexMap(raw, []string{"agent_identity"}, []string{"agentIdentity"}); ok || strings.EqualFold(firstCodexString(raw, []string{"auth_mode"}, []string{"authMode"}), service.OpenAIAuthModeAgentIdentity) { + if !ok { + agentIdentity = raw + } + item.IsAgentIdentity = true + item.AgentRuntimeID = firstCodexString(agentIdentity, []string{"agent_runtime_id"}, []string{"agentRuntimeId"}) + item.AgentPrivateKey = firstCodexString(agentIdentity, []string{"agent_private_key"}, []string{"agentPrivateKey"}) + item.AgentTaskID = firstCodexString(agentIdentity, []string{"task_id"}, []string{"taskId"}) + item.AccountID = firstCodexString(agentIdentity, []string{"account_id"}, []string{"accountId"}) + item.UserID = firstCodexString(agentIdentity, []string{"chatgpt_user_id"}, []string{"chatgptUserId"}) + item.Email = firstCodexString(agentIdentity, []string{"email"}) + item.PlanType = firstCodexString(agentIdentity, []string{"plan_type"}, []string{"planType"}) + item.AgentFedRAMP = firstCodexBool(agentIdentity, []string{"chatgpt_account_is_fedramp"}, []string{"chatgptAccountIsFedramp"}) + if item.AgentRuntimeID == "" || item.AgentPrivateKey == "" || item.AccountID == "" || item.UserID == "" { + return nil, errors.New("Agent Identity 缺少必要字段") + } + if err := service.ValidateOpenAIAgentIdentityPrivateKey(item.AgentPrivateKey); err != nil { + return nil, errors.New("Agent Identity private key 格式无效") + } + item.Credentials["auth_mode"] = service.OpenAIAuthModeAgentIdentity + item.Credentials["agent_runtime_id"] = item.AgentRuntimeID + item.Credentials["agent_private_key"] = item.AgentPrivateKey + item.Credentials["chatgpt_account_id"] = item.AccountID + item.Credentials["chatgpt_user_id"] = item.UserID + item.Credentials["chatgpt_account_is_fedramp"] = item.AgentFedRAMP + setCodexCredentialIfNotEmpty(item.Credentials, "task_id", item.AgentTaskID) + setCodexCredentialIfNotEmpty(item.Credentials, "email", item.Email) + setCodexCredentialIfNotEmpty(item.Credentials, "plan_type", item.PlanType) + if item.AgentTaskID == "" { + item.WarningTexts = append(item.WarningTexts, "未包含 task_id,首次请求会使用现有 runtime 注册新 task") + } + item.IdentityKeys = buildCodexAgentIdentityKeys(item.AccountID, item.UserID, item.Email, item.AgentRuntimeID) + item.Name = buildCodexImportAccountName(item, entry.Index) + return item, nil + } item.AccessToken = firstCodexString(raw, []string{"tokens", "access_token"}, []string{"tokens", "accessToken"}, @@ -573,6 +613,9 @@ func normalizeCodexImportEntry(entry codexImportEntry) (*codexImportAccount, err return nil, fmt.Errorf("第 %d 条格式不支持", entry.Index) } + if item.IsAgentIdentity { + return item, nil + } if item.AccessToken == "" { return nil, errors.New("缺少 accessToken/access_token") } @@ -808,6 +851,9 @@ func sanitizeCodexImportCredentialExtras(input map[string]any) map[string]any { "openai_auth_mode": {}, "token_type": {}, "chatgpt_account_is_fedramp": {}, + "agent_runtime_id": {}, + "agent_private_key": {}, + "task_id": {}, } out := make(map[string]any, len(input)) for key, value := range input { @@ -838,6 +884,14 @@ func buildCodexImportIdentityKeys(accountID, userID, email, accessToken, refresh return buildCodexStoredIdentityKeys(accountID, userID, email, accessToken) } +func buildCodexAgentIdentityKeys(accountID, userID, email, runtimeID string) []string { + keys := buildCodexStoredIdentityKeys(accountID, userID, email, "") + if runtimeID = strings.TrimSpace(runtimeID); runtimeID != "" { + keys = append([]string{"agent:" + runtimeID}, keys...) + } + return keys +} + // buildCodexStoredIdentityKeys 生成存量账号索引键,保留 user/account 维度, // 让 accessToken-only 账号后续升级为完整 OAuth 时仍能命中并更新原账号。 func buildCodexStoredIdentityKeys(accountID, userID, email, accessToken string) []string { @@ -887,6 +941,10 @@ func (i *codexAccountIndex) Add(account service.Account) { for _, key := range keys { i.accountsByKey[key] = upsertCodexAccount(i.accountsByKey[key], account) } + if runtimeID := codexCredentialString(account.Credentials, "agent_runtime_id"); runtimeID != "" { + key := "agent:" + runtimeID + i.accountsByKey[key] = upsertCodexAccount(i.accountsByKey[key], account) + } } func (i *codexAccountIndex) remove(accountID int64) { @@ -1039,6 +1097,38 @@ func firstCodexString(obj map[string]any, paths ...[]string) string { return "" } +func firstCodexMap(obj map[string]any, paths ...[]string) (map[string]any, bool) { + for _, path := range paths { + value, ok := codexPathValue(obj, path) + if !ok || value == nil { + continue + } + if mapped, ok := value.(map[string]any); ok { + return mapped, true + } + } + return nil, false +} + +func firstCodexBool(obj map[string]any, paths ...[]string) bool { + for _, path := range paths { + value, ok := codexPathValue(obj, path) + if !ok { + continue + } + switch value := value.(type) { + case bool: + return value + case string: + parsed, err := strconv.ParseBool(strings.TrimSpace(value)) + if err == nil { + return parsed + } + } + } + return false +} + func copyCodexExtraString(obj map[string]any, extra map[string]any, key string, path []string) { value := firstCodexString(obj, path) if value != "" { diff --git a/backend/internal/handler/dto/credentials_redact_test.go b/backend/internal/handler/dto/credentials_redact_test.go index 431078fafd..9bf4f78039 100644 --- a/backend/internal/handler/dto/credentials_redact_test.go +++ b/backend/internal/handler/dto/credentials_redact_test.go @@ -20,6 +20,7 @@ func TestRedactCredentials_StripsSensitiveKeysAndReportsStatus(t *testing.T) { "aws_secret_access_key": "aws-secret", "service_account_json": map[string]any{"private_key": "..."}, "private_key": "raw-key", + "agent_private_key": "agent-key-secret", // 非敏感 "base_url": "https://api.example.com", "model_mapping": map[string]any{"foo": "bar"}, @@ -35,6 +36,7 @@ func TestRedactCredentials_StripsSensitiveKeysAndReportsStatus(t *testing.T) { require.NotContains(t, out, "aws_secret_access_key") require.NotContains(t, out, "service_account_json") require.NotContains(t, out, "private_key") + require.NotContains(t, out, "agent_private_key") require.Equal(t, "https://api.example.com", out["base_url"]) require.Equal(t, map[string]any{"foo": "bar"}, out["model_mapping"]) @@ -47,6 +49,7 @@ func TestRedactCredentials_StripsSensitiveKeysAndReportsStatus(t *testing.T) { require.True(t, status["has_aws_secret_access_key"]) require.True(t, status["has_service_account_json"]) require.True(t, status["has_private_key"]) + require.True(t, status["has_agent_private_key"]) // 状态 map 不应携带非敏感键的 has_* require.NotContains(t, status, "has_base_url") @@ -84,6 +87,7 @@ func TestRedactCredentials_AllKnownSensitiveKeys(t *testing.T) { "api_key", "session_key", "cookie", "aws_secret_access_key", "aws_session_token", "service_account_json", "service_account", "private_key", + "agent_private_key", } in := make(map[string]any, len(keys)) for _, k := range keys { diff --git a/backend/internal/service/account_credentials_redact.go b/backend/internal/service/account_credentials_redact.go index 76c2d1de5b..8eb70513ba 100644 --- a/backend/internal/service/account_credentials_redact.go +++ b/backend/internal/service/account_credentials_redact.go @@ -4,7 +4,7 @@ package service // dto 层做响应脱敏、service 层做更新合并都引用此清单——新增凭证类型时务必同步。 var SensitiveCredentialKeys = []string{ // OAuth - "access_token", "refresh_token", "id_token", + "access_token", "refresh_token", "id_token", "agent_private_key", // API Key 类 "api_key", "session_key", "cookie", // 云服务凭据 diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index b9dae84057..f83a99a7e2 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -15,6 +15,7 @@ import ( "net/http/httptest" "regexp" "strings" + "sync" "time" "github.com/Wei-Shaw/sub2api/internal/config" @@ -72,6 +73,7 @@ type AccountTestService struct { httpUpstream HTTPUpstream cfg *config.Config tlsFPProfileService *TLSFingerprintProfileService + agentIdentityTaskMu sync.Mutex } // NewAccountTestService creates a new AccountTestService @@ -544,9 +546,11 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account if credentialAccount.IsOAuth() { isOAuth = true - // OAuth - use Bearer token with ChatGPT internal API - authToken = credentialAccount.GetOpenAIAccessToken() - if authToken == "" { + // Agent Identity signs each request and does not retain the OAuth token. + if !credentialAccount.IsOpenAIAgentIdentity() { + authToken = credentialAccount.GetOpenAIAccessToken() + } + if authToken == "" && !credentialAccount.IsOpenAIAgentIdentity() { return s.sendErrorAndEnd(c, "No access token available") } @@ -597,7 +601,19 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account // Set common headers req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "Bearer "+authToken) + if credentialAccount.IsOpenAIAgentIdentity() { + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, credentialAccount) + if authErr != nil { + return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication") + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } + } else { + req.Header.Set("Authorization", "Bearer "+authToken) + } // Set OAuth-specific headers for ChatGPT internal API if isOAuth { @@ -804,16 +820,26 @@ func (s *AccountTestService) testOpenAIChatCompletionsConnection( // resulting capability state on the account. func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account *Account, testModelID string) error { ctx := c.Request.Context() + credentialAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil { + return s.sendErrorAndEnd(c, "Failed to resolve account credentials") + } + credentialAccount = resolved + } authToken := "" apiURL := "" isOAuth := false switch { - case account.IsOAuth(): + case credentialAccount.IsOAuth(): isOAuth = true - authToken = account.GetOpenAIAccessToken() - if authToken == "" { + if !credentialAccount.IsOpenAIAgentIdentity() { + authToken = credentialAccount.GetOpenAIAccessToken() + } + if authToken == "" && !credentialAccount.IsOpenAIAgentIdentity() { return s.sendErrorAndEnd(c, "No access token available") } apiURL = chatgptCodexAPIURL + "/compact" @@ -852,7 +878,19 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") - req.Header.Set("Authorization", "Bearer "+authToken) + if credentialAccount.IsOpenAIAgentIdentity() { + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, credentialAccount) + if authErr != nil { + return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication") + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } + } else { + req.Header.Set("Authorization", "Bearer "+authToken) + } req.Header.Set("OpenAI-Beta", "responses=experimental") req.Header.Set("Originator", "codex_cli_rs") req.Header.Set("User-Agent", codexCLIUserAgent) @@ -863,7 +901,7 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account if isOAuth { req.Host = "chatgpt.com" - setOpenAIChatGPTAccountHeaders(req.Header, account) + setOpenAIChatGPTAccountHeaders(req.Header, credentialAccount) } // 账号级请求头覆写:测试请求与真实转发保持一致的最终头 @@ -1677,8 +1715,19 @@ func (s *AccountTestService) testOpenAIImageAPIKey(c *gin.Context, ctx context.C // testOpenAIImageOAuth tests OpenAI image generation using an OAuth account via Codex /responses API. func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Context, account *Account, modelID, prompt string) error { - authToken := account.GetOpenAIAccessToken() - if authToken == "" { + credentialAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil { + return s.sendErrorAndEnd(c, "Failed to resolve account credentials") + } + credentialAccount = resolved + } + authToken := "" + if !credentialAccount.IsOpenAIAgentIdentity() { + authToken = credentialAccount.GetOpenAIAccessToken() + } + if authToken == "" && !credentialAccount.IsOpenAIAgentIdentity() { return s.sendErrorAndEnd(c, "No access token available") } @@ -1710,17 +1759,29 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co } req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI)) req.Host = "chatgpt.com" - req.Header.Set("Authorization", "Bearer "+authToken) + if credentialAccount.IsOpenAIAgentIdentity() { + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, credentialAccount) + if authErr != nil { + return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication") + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } + } else { + req.Header.Set("Authorization", "Bearer "+authToken) + } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "text/event-stream") req.Header.Set("OpenAI-Beta", "responses=experimental") req.Header.Set("originator", "codex_cli_rs") - if customUA := strings.TrimSpace(account.GetOpenAIUserAgent()); customUA != "" { + if customUA := strings.TrimSpace(credentialAccount.GetOpenAIUserAgent()); customUA != "" { req.Header.Set("User-Agent", customUA) } else { req.Header.Set("User-Agent", codexCLIUserAgent) } - setOpenAIChatGPTAccountHeaders(req.Header, account) + setOpenAIChatGPTAccountHeaders(req.Header, credentialAccount) // 与真实转发一致:originator 与最终 User-Agent 首段配套(原 opencode 与 Codex UA 错配会 404,issue #3901)。 enforceCodexIdentityHeaders(req.Header) diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index 281122d4f0..4dc09c4109 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -291,6 +291,7 @@ type AccountUsageService struct { cache *UsageCache identityCache IdentityCache tlsFPProfileService *TLSFingerprintProfileService + agentIdentityTaskMu sync.Mutex } // NewAccountUsageService 创建AccountUsageService实例 @@ -682,8 +683,11 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco if account == nil || !account.IsOAuth() { return nil, nil } - accessToken := account.GetOpenAIAccessToken() - if accessToken == "" { + accessToken := "" + if !account.IsOpenAIAgentIdentity() { + accessToken = account.GetOpenAIAccessToken() + } + if accessToken == "" && !account.IsOpenAIAgentIdentity() { return nil, fmt.Errorf("no access token available") } modelID := openaipkg.DefaultTestModel @@ -701,7 +705,19 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco } req.Host = "chatgpt.com" req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", "Bearer "+accessToken) + if account.IsOpenAIAgentIdentity() { + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, account) + if authErr != nil { + return nil, fmt.Errorf("build Agent Identity authentication: %w", authErr) + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } + } else { + req.Header.Set("Authorization", "Bearer "+accessToken) + } req.Header.Set("Accept", "text/event-stream") req.Header.Set("OpenAI-Beta", "responses=experimental") req.Header.Set("Originator", "codex_cli_rs") diff --git a/backend/internal/service/openai_agent_identity.go b/backend/internal/service/openai_agent_identity.go new file mode 100644 index 0000000000..c8818cd6f3 --- /dev/null +++ b/backend/internal/service/openai_agent_identity.go @@ -0,0 +1,431 @@ +package service + +import ( + "context" + "crypto" + "crypto/ed25519" + "crypto/sha512" + "crypto/x509" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/httpclient" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/nacl/box" +) + +const ( + OpenAIAuthModeAgentIdentity = "agentIdentity" + agentIdentityAuthAPIBaseURL = "https://auth.openai.com/api/accounts" + agentIdentityTaskRegistrationTimeout = 30 * time.Second +) + +var openAIAgentIdentityAuthAPIBaseURL = agentIdentityAuthAPIBaseURL + +type agentIdentityKey struct { + runtimeID string + privateKey ed25519.PrivateKey + taskID string +} + +type agentIdentityTaskRegistrationResponse struct { + TaskID string `json:"task_id"` + TaskIDCamel string `json:"taskId"` + EncryptedTaskID string `json:"encrypted_task_id"` + EncryptedTaskIDCamel string `json:"encryptedTaskId"` +} + +type agentIdentityTaskRecoveredError struct{} + +func (e *agentIdentityTaskRecoveredError) Error() string { + return "agent identity task recovered" +} + +func (a *Account) IsOpenAIAgentIdentity() bool { + if a == nil || !a.IsOpenAIOAuth() { + return false + } + return strings.EqualFold(strings.TrimSpace(a.GetCredential(openAIAuthModeCredentialKey)), OpenAIAuthModeAgentIdentity) +} + +func agentIdentityPrivateKey(account *Account) (ed25519.PrivateKey, error) { + if account == nil { + return nil, errors.New("agent identity account is nil") + } + raw := strings.TrimSpace(account.GetCredential("agent_private_key")) + if raw == "" { + return nil, errors.New("agent identity private key is missing") + } + der, err := base64.StdEncoding.DecodeString(raw) + if err != nil { + return nil, errors.New("agent identity private key is not valid base64") + } + key, err := x509.ParsePKCS8PrivateKey(der) + if err != nil { + return nil, errors.New("agent identity private key is not valid PKCS#8") + } + privateKey, ok := key.(ed25519.PrivateKey) + if !ok || len(privateKey) != ed25519.PrivateKeySize { + return nil, errors.New("agent identity private key is not Ed25519") + } + return privateKey, nil +} + +// ValidateOpenAIAgentIdentityPrivateKey validates the stored PKCS#8 Ed25519 +// form without returning or logging the key material. +func ValidateOpenAIAgentIdentityPrivateKey(encoded string) error { + account := &Account{Credentials: map[string]any{"agent_private_key": encoded}} + _, err := agentIdentityPrivateKey(account) + return err +} + +func agentIdentityKeyFromAccount(account *Account) (agentIdentityKey, error) { + privateKey, err := agentIdentityPrivateKey(account) + if err != nil { + return agentIdentityKey{}, err + } + runtimeID := strings.TrimSpace(account.GetCredential("agent_runtime_id")) + if runtimeID == "" { + return agentIdentityKey{}, errors.New("agent identity runtime id is missing") + } + return agentIdentityKey{ + runtimeID: runtimeID, + privateKey: privateKey, + taskID: strings.TrimSpace(account.GetCredential("task_id")), + }, nil +} + +func buildAgentAssertion(key agentIdentityKey, now time.Time) (string, error) { + if key.runtimeID == "" || key.taskID == "" { + return "", errors.New("agent identity runtime or task id is missing") + } + timestamp := now.UTC().Format(time.RFC3339) + payload := []byte(key.runtimeID + ":" + key.taskID + ":" + timestamp) + signature, err := key.privateKey.Sign(nil, payload, crypto.Hash(0)) + if err != nil { + return "", errors.New("failed to sign agent assertion") + } + envelope := map[string]string{ + "agent_runtime_id": key.runtimeID, + "task_id": key.taskID, + "timestamp": timestamp, + "signature": base64.StdEncoding.EncodeToString(signature), + } + encoded, err := json.Marshal(envelope) + if err != nil { + return "", errors.New("failed to serialize agent assertion") + } + return "AgentAssertion " + base64.RawURLEncoding.EncodeToString(encoded), nil +} + +func signAgentTaskRegistration(key agentIdentityKey, timestamp time.Time) (string, string, error) { + if key.runtimeID == "" { + return "", "", errors.New("agent identity runtime id is missing") + } + formatted := timestamp.UTC().Format(time.RFC3339) + signature, err := key.privateKey.Sign(nil, []byte(key.runtimeID+":"+formatted), crypto.Hash(0)) + if err != nil { + return "", "", errors.New("failed to sign agent task registration") + } + return formatted, base64.StdEncoding.EncodeToString(signature), nil +} + +func decryptAgentTaskID(key agentIdentityKey, encoded string) (string, error) { + ciphertext, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded)) + if err != nil { + return "", errors.New("encrypted agent task id is not valid base64") + } + seed := key.privateKey.Seed() + digest := sha512.Sum512(seed) + var curvePrivate [32]byte + copy(curvePrivate[:], digest[:32]) + curvePrivate[0] &= 248 + curvePrivate[31] &= 127 + curvePrivate[31] |= 64 + curvePublicBytes, err := curve25519.X25519(curvePrivate[:], curve25519.Basepoint) + if err != nil { + return "", errors.New("failed to derive agent identity decryption key") + } + var curvePublic [32]byte + copy(curvePublic[:], curvePublicBytes) + plaintext, ok := box.OpenAnonymous(nil, ciphertext, &curvePublic, &curvePrivate) + if !ok { + return "", errors.New("failed to decrypt encrypted agent task id") + } + taskID := strings.TrimSpace(string(plaintext)) + if taskID == "" { + return "", errors.New("decrypted agent task id is empty") + } + return taskID, nil +} + +func registerAgentIdentityTask(ctx context.Context, account *Account) (string, error) { + key, err := agentIdentityKeyFromAccount(account) + if err != nil { + return "", err + } + timestamp, signature, err := signAgentTaskRegistration(key, time.Now()) + if err != nil { + return "", err + } + proxyURL := "" + if account.ProxyID != nil && account.Proxy != nil { + proxyURL = account.Proxy.URL() + } + client, err := httpclient.GetClient(httpclient.Options{ + ProxyURL: proxyURL, + Timeout: agentIdentityTaskRegistrationTimeout, + ResponseHeaderTimeout: 15 * time.Second, + }) + if err != nil { + return "", errors.New("invalid proxy configuration for agent task registration") + } + body, err := json.Marshal(map[string]string{ + "timestamp": timestamp, + "signature": signature, + }) + if err != nil { + return "", errors.New("failed to serialize agent task registration") + } + url := strings.TrimRight(strings.TrimSpace(openAIAgentIdentityAuthAPIBaseURL), "/") + "/v1/agent/" + key.runtimeID + "/task/register" + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, strings.NewReader(string(body))) + if err != nil { + return "", errors.New("failed to build agent task registration request") + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Accept", "application/json") + resp, err := client.Do(req) + if err != nil { + return "", errors.New("agent task registration request failed") + } + defer func() { _ = resp.Body.Close() }() + if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices { + return "", fmt.Errorf("agent task registration returned status %d", resp.StatusCode) + } + var result agentIdentityTaskRegistrationResponse + if err := json.NewDecoder(io.LimitReader(resp.Body, 64*1024)).Decode(&result); err != nil { + return "", errors.New("agent task registration response is invalid") + } + if taskID := strings.TrimSpace(result.TaskID); taskID != "" { + return taskID, nil + } + if taskID := strings.TrimSpace(result.TaskIDCamel); taskID != "" { + return taskID, nil + } + encrypted := strings.TrimSpace(result.EncryptedTaskID) + if encrypted == "" { + encrypted = strings.TrimSpace(result.EncryptedTaskIDCamel) + } + if encrypted == "" { + return "", errors.New("agent task registration response omitted task id") + } + return decryptAgentTaskID(key, encrypted) +} + +func ensureAgentIdentityTaskForAccount(ctx context.Context, repo AccountRepository, pool *openAIWSConnPool, taskMu *sync.Mutex, account *Account, expectedTaskID string) error { + if account == nil || !account.IsOpenAIAgentIdentity() { + return nil + } + credAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, repo, account) + if err != nil { + return err + } + credAccount = resolved + } + if credAccount == nil || !credAccount.IsOpenAIAgentIdentity() { + return errors.New("agent identity credentials are unavailable") + } + currentTaskID := strings.TrimSpace(credAccount.GetCredential("task_id")) + if currentTaskID != "" && (expectedTaskID == "" || currentTaskID != expectedTaskID) { + return nil + } + if taskMu == nil { + return errors.New("agent identity task lock is unavailable") + } + taskMu.Lock() + defer taskMu.Unlock() + currentTaskID = strings.TrimSpace(credAccount.GetCredential("task_id")) + if currentTaskID != "" && (expectedTaskID == "" || currentTaskID != expectedTaskID) { + return nil + } + newTaskID, err := registerAgentIdentityTask(ctx, credAccount) + if err != nil { + return err + } + credentials := make(map[string]any, len(credAccount.Credentials)+1) + for key, value := range credAccount.Credentials { + credentials[key] = value + } + credentials["task_id"] = newTaskID + if err := persistAccountCredentials(ctx, repo, credAccount, credentials); err != nil { + return err + } + if pool != nil { + pool.ClearAccount(credAccount.ID) + } + return nil +} + +func (s *OpenAIGatewayService) ensureAgentIdentityTask(ctx context.Context, account *Account, expectedTaskID string) error { + if s == nil { + return errors.New("openai gateway service is nil") + } + return ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.openaiWSPool, &s.agentIdentityTaskMu, account, expectedTaskID) +} + +func isAgentIdentityTaskInvalidHTTPResponse(statusCode int, body []byte) bool { + if statusCode != http.StatusUnauthorized { + return false + } + lower := strings.ToLower(string(body)) + for _, marker := range []string{ + "invalid task", + "task_id", + "task id", + "task_not_found", + "task_expired", + "unknown task", + } { + if strings.Contains(lower, marker) { + return true + } + } + return false +} + +func (s *OpenAIGatewayService) buildOpenAIAuthenticationHeaders(ctx context.Context, account *Account, token string) (http.Header, error) { + if account == nil { + return nil, errors.New("account is nil") + } + credAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil { + return nil, err + } + credAccount = resolved + } + headers := make(http.Header) + if credAccount != nil && credAccount.IsOpenAIAgentIdentity() { + agentHeaders, err := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.openaiWSPool, &s.agentIdentityTaskMu, credAccount) + if err != nil { + return nil, err + } + return agentHeaders, nil + } + headers.Set("Authorization", "Bearer "+token) + return headers, nil +} + +func buildAgentIdentityAuthenticationHeaders(ctx context.Context, repo AccountRepository, pool *openAIWSConnPool, taskMu *sync.Mutex, account *Account) (http.Header, error) { + if account == nil || !account.IsOpenAIAgentIdentity() { + return nil, errors.New("agent identity account is required") + } + if err := ensureAgentIdentityTaskForAccount(ctx, repo, pool, taskMu, account, ""); err != nil { + return nil, err + } + key, err := agentIdentityKeyFromAccount(account) + if err != nil { + return nil, err + } + assertion, err := buildAgentAssertion(key, time.Now()) + if err != nil { + return nil, err + } + headers := make(http.Header) + headers.Set("Authorization", assertion) + return headers, nil +} + +func (s *OpenAIGatewayService) refreshOpenAIAgentIdentityHeaders(ctx context.Context, account *Account, headers http.Header) (http.Header, error) { + if account == nil { + return cloneHeader(headers), nil + } + credAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil { + return nil, err + } + credAccount = resolved + } + if !credAccount.IsOpenAIAgentIdentity() { + return cloneHeader(headers), nil + } + refreshed := cloneHeader(headers) + if refreshed == nil { + refreshed = make(http.Header) + } + authHeaders, err := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.openaiWSPool, &s.agentIdentityTaskMu, credAccount) + if err != nil { + return nil, err + } + refreshed.Set("Authorization", authHeaders.Get("Authorization")) + return refreshed, nil +} + +func (s *OpenAIGatewayService) recoverAgentIdentityTask(ctx context.Context, account *Account, expectedTaskID string) error { + if account != nil && account.IsShadow() { + if resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account); err == nil && resolved != nil && strings.TrimSpace(expectedTaskID) == "" { + expectedTaskID = strings.TrimSpace(resolved.GetCredential("task_id")) + } + } + return s.ensureAgentIdentityTask(ctx, account, expectedTaskID) +} + +func (s *OpenAIGatewayService) isAgentIdentityAccount(ctx context.Context, account *Account) bool { + if account == nil { + return false + } + credAccount := account + if account.IsShadow() { + resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil { + return false + } + credAccount = resolved + } + return credAccount != nil && credAccount.IsOpenAIAgentIdentity() +} + +// redactAgentIdentitySensitiveBody removes credential values before an +// upstream error can reach logs, ops events, or returned error text. Agent +// Identity responses should not echo these values, but keeping this boundary +// defensive prevents accidental disclosure if an upstream error does. +func (s *OpenAIGatewayService) redactAgentIdentitySensitiveBody(ctx context.Context, account *Account, body []byte) []byte { + if !s.isAgentIdentityAccount(ctx, account) || len(body) == 0 { + return body + } + credAccount := account + if account != nil && account.IsShadow() { + if resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account); err == nil && resolved != nil { + credAccount = resolved + } + } + redacted := string(body) + for _, key := range []string{ + "agent_private_key", + "agent_runtime_id", + "task_id", + "access_token", + "refresh_token", + "id_token", + "api_key", + "session_key", + "cookie", + } { + if value := strings.TrimSpace(credAccount.GetCredential(key)); value != "" { + redacted = strings.ReplaceAll(redacted, value, "[redacted]") + } + } + return []byte(redacted) +} diff --git a/backend/internal/service/openai_agent_identity_compat_test.go b/backend/internal/service/openai_agent_identity_compat_test.go new file mode 100644 index 0000000000..5c0c996c42 --- /dev/null +++ b/backend/internal/service/openai_agent_identity_compat_test.go @@ -0,0 +1,247 @@ +package service + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestAccountTestServiceOpenAICompactAgentIdentityUsesFreshAssertion(t *testing.T) { + gin.SetMode(gin.TestMode) + key, privateKey := newTestAgentIdentityKey(t) + account := Account{ + ID: 21, + Name: "agent-identity", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": key.taskID, + "chatgpt_account_id": "account-agent-test", + "chatgpt_account_is_fedramp": true, + }, + } + repo := &snapshotUpdateAccountRepo{stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}} + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"id":"compact-agent","status":"completed"}`)), + }} + svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream} + + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/21/test", bytes.NewReader(nil)) + + require.NoError(t, svc.TestAccountConnection(c, account.ID, "gpt-5.4", "", AccountTestModeCompact)) + require.Equal(t, "AgentAssertion", strings.SplitN(upstream.lastReq.Header.Get("Authorization"), " ", 2)[0]) + require.Equal(t, "account-agent-test", upstream.lastReq.Header.Get("chatgpt-account-id")) + require.Equal(t, "true", upstream.lastReq.Header.Get("x-openai-fedramp")) + require.NotContains(t, upstream.lastReq.Header.Get("Authorization"), privateKey) +} + +func TestOpenAIAgentIdentityPassthroughKeepsSessionAndPromptCacheHeaders(t *testing.T) { + gin.SetMode(gin.TestMode) + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: 24, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": key.taskID, + "chatgpt_account_id": "account-agent-passthrough", + }, + } + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":true,"prompt_cache_key":"cache-agent"}`) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body)) + c.Request.Header.Set("session_id", "client-session") + c.Request.Header.Set("conversation_id", "client-conversation") + c.Request.Header.Set("Authorization", "Bearer inbound-must-not-forward") + + svc := &OpenAIGatewayService{} + req, err := svc.buildUpstreamRequestOpenAIPassthrough(context.Background(), c, account, body, "") + require.NoError(t, err) + require.Equal(t, "AgentAssertion", strings.SplitN(req.Header.Get("Authorization"), " ", 2)[0]) + require.Equal(t, "account-agent-passthrough", req.Header.Get("chatgpt-account-id")) + require.NotEqual(t, "client-session", req.Header.Get("session_id")) + require.NotEqual(t, "client-conversation", req.Header.Get("conversation_id")) + require.Equal(t, isolateOpenAISessionID(0, "cache-agent"), req.Header.Get("session_id")) +} + +func TestOpenAIAgentIdentityErrorRedactionDoesNotLeakCredentialValues(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: 25, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": key.taskID, + "access_token": key.runtimeID + "-oauth-value", + }, + } + svc := &OpenAIGatewayService{} + oauthValue := account.GetCredential("access_token") + redacted := svc.redactAgentIdentitySensitiveBody(context.Background(), account, []byte(`{"message":"runtime-test task-test `+oauthValue+`"}`)) + require.NotContains(t, string(redacted), key.runtimeID) + require.NotContains(t, string(redacted), key.taskID) + require.NotContains(t, string(redacted), oauthValue) + require.Contains(t, string(redacted), "[redacted]") +} + +func TestOpenAIWSConnPoolHeadersFactoryRunsAtDialAndStalePrewarmIsDiscarded(t *testing.T) { + cfg := &config.Config{} + cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 1 + pool := newOpenAIWSConnPool(cfg) + defer pool.Close() + pool.setClientDialerForTest(&openAIWSFakeDialer{}) + + accountID := int64(22) + ap := pool.getOrCreateAccountPool(accountID) + factoryCalls := 0 + latestHeader := "" + req := openAIWSAcquireRequest{ + Account: &Account{ID: accountID, Platform: PlatformOpenAI, Type: AccountTypeOAuth}, + WSURL: "wss://example.com/v1/responses", + HeadersFactory: func(_ context.Context, headers http.Header) (http.Header, error) { + factoryCalls++ + latestHeader = "AgentAssertion dial-" + string(rune('0'+factoryCalls)) + if headers == nil { + headers = make(http.Header) + } + headers.Set("Authorization", latestHeader) + return headers, nil + }, + } + ap.mu.Lock() + ap.lastAcquire = &req + generation := ap.generation + ap.mu.Unlock() + + pool.prewarmConns(accountID, req, 1, generation) + require.Equal(t, 1, factoryCalls, "prewarm must generate authorization inside the actual dial") + require.Equal(t, "AgentAssertion dial-1", latestHeader) + + pool.ClearAccount(accountID) + ap.mu.Lock() + require.Empty(t, ap.conns, "credential recovery must remove pooled connections") + require.Nil(t, ap.lastAcquire, "credential recovery must discard delayed acquire state") + require.Equal(t, generation+1, ap.generation) + ap.mu.Unlock() + + // A prewarm captured before ClearAccount must not be admitted after recovery. + pool.prewarmConns(accountID, req, 1, generation) + ap.mu.Lock() + require.Empty(t, ap.conns) + ap.mu.Unlock() +} + +func TestOpenAIAgentIdentityTaskInvalidRetriesExactlyOnce(t *testing.T) { + gin.SetMode(gin.TestMode) + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: 23, + Name: "agent-identity", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": "task-old", + "chatgpt_account_id": "account-agent-retry", + }, + } + repo := &agentIdentityForwardRepo{account: account} + registerCalls := 0 + registerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + registerCalls++ + _, _ = io.WriteString(w, `{"task_id":"task-new"}`) + })) + defer registerServer.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = registerServer.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + successBody := `{"id":"resp-agent-retry","object":"response","model":"gpt-5.4","output":[],"usage":{"input_tokens":1,"output_tokens":1,"total_tokens":2}}` + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(successBody))}, + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, accountRepo: repo, httpUpstream: upstream} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + + _, err := svc.Forward(context.Background(), c, account, []byte(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + require.NoError(t, err) + require.Equal(t, 1, registerCalls) + require.Len(t, upstream.requests, 2) + require.NotEqual(t, upstream.requests[0].Header.Get("Authorization"), upstream.requests[1].Header.Get("Authorization")) + require.Equal(t, "task-new", decodeAgentAssertionTask(t, upstream.requests[1].Header.Get("Authorization"))) + + // Two consecutive invalid responses still produce only one retry for this + // request; the recovery path must not loop indefinitely. + upstream.responses = []*http.Response{ + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + } + rec2 := httptest.NewRecorder() + c2, _ := gin.CreateTestContext(rec2) + c2.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + _, err = svc.Forward(context.Background(), c2, account, []byte(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + require.Error(t, err) + require.Equal(t, 2, registerCalls) + require.Len(t, upstream.requests, 4) +} + +func decodeAgentAssertionTask(t *testing.T, header string) string { + t.Helper() + encoded := strings.TrimPrefix(header, "AgentAssertion ") + decoded, err := base64.RawURLEncoding.DecodeString(encoded) + require.NoError(t, err) + var envelope struct { + TaskID string `json:"task_id"` + } + require.NoError(t, json.Unmarshal(decoded, &envelope)) + return envelope.TaskID +} + +type agentIdentityForwardRepo struct { + AccountRepository + account *Account +} + +func (r *agentIdentityForwardRepo) GetByID(_ context.Context, _ int64) (*Account, error) { + return r.account, nil +} + +func (r *agentIdentityForwardRepo) UpdateCredentials(_ context.Context, _ int64, credentials map[string]any) error { + r.account.Credentials = credentials + return nil +} diff --git a/backend/internal/service/openai_agent_identity_test.go b/backend/internal/service/openai_agent_identity_test.go new file mode 100644 index 0000000000..73ac0ddf08 --- /dev/null +++ b/backend/internal/service/openai_agent_identity_test.go @@ -0,0 +1,177 @@ +package service + +import ( + "context" + "crypto/ed25519" + "crypto/rand" + "crypto/sha512" + "crypto/x509" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/nacl/box" +) + +func newTestAgentIdentityKey(t *testing.T) (agentIdentityKey, string) { + t.Helper() + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + der, err := x509.MarshalPKCS8PrivateKey(privateKey) + require.NoError(t, err) + return agentIdentityKey{ + runtimeID: "runtime-test", + privateKey: privateKey, + taskID: "task-test", + }, base64.StdEncoding.EncodeToString(der) +} + +func TestBuildAgentAssertionMatchesCodexEnvelopeAndSignature(t *testing.T) { + key, _ := newTestAgentIdentityKey(t) + now := time.Date(2026, 7, 14, 8, 9, 10, 0, time.FixedZone("UTC+8", 8*60*60)) + assertion, err := buildAgentAssertion(key, now) + require.NoError(t, err) + require.True(t, strings.HasPrefix(assertion, "AgentAssertion ")) + + encoded := strings.TrimPrefix(assertion, "AgentAssertion ") + decoded, err := base64.RawURLEncoding.DecodeString(encoded) + require.NoError(t, err) + var envelope struct { + AgentRuntimeID string `json:"agent_runtime_id"` + TaskID string `json:"task_id"` + Timestamp string `json:"timestamp"` + Signature string `json:"signature"` + } + require.NoError(t, json.Unmarshal(decoded, &envelope)) + require.Equal(t, "runtime-test", envelope.AgentRuntimeID) + require.Equal(t, "task-test", envelope.TaskID) + require.Equal(t, "2026-07-14T00:09:10Z", envelope.Timestamp) + signature, err := base64.StdEncoding.DecodeString(envelope.Signature) + require.NoError(t, err) + require.True(t, ed25519.Verify(key.privateKey.Public().(ed25519.PublicKey), []byte("runtime-test:task-test:2026-07-14T00:09:10Z"), signature)) +} + +func TestDecryptAgentTaskIDSupportsCodexSealedBoxResponse(t *testing.T) { + key, _ := newTestAgentIdentityKey(t) + digest := sha512.Sum512(key.privateKey.Seed()) + var curvePrivate [32]byte + copy(curvePrivate[:], digest[:32]) + curvePrivate[0] &= 248 + curvePrivate[31] &= 127 + curvePrivate[31] |= 64 + curvePublicBytes, err := curve25519.X25519(curvePrivate[:], curve25519.Basepoint) + require.NoError(t, err) + var curvePublic [32]byte + copy(curvePublic[:], curvePublicBytes) + ciphertext, err := box.SealAnonymous(nil, []byte("task-sealed"), &curvePublic, rand.Reader) + require.NoError(t, err) + got, err := decryptAgentTaskID(key, base64.StdEncoding.EncodeToString(ciphertext)) + require.NoError(t, err) + require.Equal(t, "task-sealed", got) +} + +func TestRegisterAgentIdentityTaskAcceptsPlaintextAndEncryptedResponses(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + requestCount := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, http.MethodPost, r.Method) + require.Equal(t, "/v1/agent/runtime-test/task/register", r.URL.Path) + var request map[string]string + require.NoError(t, json.NewDecoder(r.Body).Decode(&request)) + require.NotEmpty(t, request["timestamp"]) + require.NotEmpty(t, request["signature"]) + requestCount++ + if requestCount == 2 { + digest := sha512.Sum512(key.privateKey.Seed()) + var curvePrivate [32]byte + copy(curvePrivate[:], digest[:32]) + curvePrivate[0] &= 248 + curvePrivate[31] &= 127 + curvePrivate[31] |= 64 + curvePublicBytes, curveErr := curve25519.X25519(curvePrivate[:], curve25519.Basepoint) + require.NoError(t, curveErr) + var curvePublic [32]byte + copy(curvePublic[:], curvePublicBytes) + ciphertext, sealErr := box.SealAnonymous(nil, []byte("task-encrypted"), &curvePublic, rand.Reader) + require.NoError(t, sealErr) + _, _ = fmt.Fprintf(w, `{"encrypted_task_id":%q}`, base64.StdEncoding.EncodeToString(ciphertext)) + return + } + _, _ = w.Write([]byte(`{"task_id":"task-plain"}`)) + })) + defer server.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = server.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + account := &Account{ID: 1, Type: AccountTypeOAuth, Platform: PlatformOpenAI, Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + }} + taskID, err := registerAgentIdentityTask(context.Background(), account) + require.NoError(t, err) + require.Equal(t, "task-plain", taskID) + taskID, err = registerAgentIdentityTask(context.Background(), account) + require.NoError(t, err) + require.Equal(t, "task-encrypted", taskID) +} + +func TestEnsureAgentIdentityTaskPersistsAndRedactsCredentials(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"task_id":"task-persisted"}`)) + })) + defer server.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = server.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + repo := &agentIdentityCredentialsRepo{} + account := &Account{ID: 7, Type: AccountTypeOAuth, Platform: PlatformOpenAI, Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "chatgpt_account_id": "account-test", + }} + service := &OpenAIGatewayService{accountRepo: repo} + require.NoError(t, service.ensureAgentIdentityTask(context.Background(), account, "")) + require.Equal(t, "task-persisted", account.GetCredential("task_id")) + require.Equal(t, "task-persisted", repo.credentials["task_id"]) + require.True(t, IsSensitiveCredentialKey("agent_private_key")) + redacted := make(map[string]any) + for key, value := range account.Credentials { + if !IsSensitiveCredentialKey(key) { + redacted[key] = value + } + } + require.NotContains(t, string(mustJSON(t, redacted)), privateKey) +} + +type agentIdentityCredentialsRepo struct { + AccountRepository + credentials map[string]any + mu sync.Mutex +} + +func (r *agentIdentityCredentialsRepo) UpdateCredentials(_ context.Context, _ int64, credentials map[string]any) error { + r.mu.Lock() + defer r.mu.Unlock() + r.credentials = credentials + return nil +} + +func mustJSON(t *testing.T, value any) []byte { + t.Helper() + encoded, err := json.Marshal(value) + require.NoError(t, err) + return encoded +} diff --git a/backend/internal/service/openai_codex_models_service.go b/backend/internal/service/openai_codex_models_service.go index 8a919fa2b0..0eb2e1a071 100644 --- a/backend/internal/service/openai_codex_models_service.go +++ b/backend/internal/service/openai_codex_models_service.go @@ -42,7 +42,7 @@ func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, acc return nil, infraerrors.Newf(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_CREDENTIALS_FAILED", "resolve credential account: %v", err) } accessToken := credAccount.GetOpenAIAccessToken() - if accessToken == "" { + if accessToken == "" && !credAccount.IsOpenAIAgentIdentity() { return nil, infraerrors.New(http.StatusBadGateway, "OPENAI_CODEX_MODELS_TOKEN_MISSING", "account has no Codex backend access token") } @@ -58,7 +58,15 @@ func (s *OpenAIGatewayService) FetchCodexModelsManifest(ctx context.Context, acc if err != nil { return nil, infraerrors.Newf(http.StatusInternalServerError, "OPENAI_CODEX_MODELS_REQUEST_FAILED", "create codex models request: %v", err) } - req.Header.Set("Authorization", "Bearer "+accessToken) + authHeaders, err := s.buildOpenAIAuthenticationHeaders(ctx, credAccount, accessToken) + if err != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_CODEX_MODELS_AUTH_FAILED", "build Codex models authentication: %v", err) + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } req.Header.Set("Accept", "application/json") req.Header.Set("Originator", "codex_cli_rs") req.Header.Set("Version", clientVersion) diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index 7518a6073a..46b5a3843a 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -215,7 +215,15 @@ func (s *OpenAIGatewayService) buildInputTokensUpstreamRequest( return nil, err } req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI)) - req.Header.Set("authorization", "Bearer "+token) + authHeaders, err := s.buildOpenAIAuthenticationHeaders(ctx, account, token) + if err != nil { + return nil, err + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } req.Header.Set("content-type", "application/json") req.Header.Set("accept", "application/json") diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 53cc06989e..e1c9aea15f 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -487,6 +487,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco var wsResult *OpenAIForwardResult var wsErr error wsLastFailureReason := "" + agentTaskRecoveryTried := false wsPrevResponseRecoveryTried := false wsInvalidEncryptedContentRecoveryTried := false recoverPrevResponseNotFound := func(attempt int) bool { @@ -571,6 +572,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco startTime, attempt, wsLastFailureReason, + &agentTaskRecoveryTried, ) if wsErr == nil { break @@ -578,6 +580,10 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco if c != nil && c.Writer != nil && c.Writer.Written() { break } + var taskRecoveredErr *agentIdentityTaskRecoveredError + if errors.As(wsErr, &taskRecoveredErr) { + continue + } reason, retryable := classifyOpenAIWSReconnectReason(wsErr) if reason != "" { @@ -684,6 +690,7 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco } httpInvalidEncryptedContentRetryTried := false + agentTaskRecoveryTried := false for { // Build upstream request upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) @@ -719,6 +726,16 @@ func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, acco upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) upstreamCode := extractUpstreamErrorCode(respBody) + if !agentTaskRecoveryTried && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { + agentTaskRecoveryTried = true + expectedTaskID := account.GetCredential("task_id") + if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", err) + } + continue + } + respBody = s.redactAgentIdentitySensitiveBody(ctx, account, respBody) + resp.Body = io.NopCloser(bytes.NewReader(respBody)) if !httpInvalidEncryptedContentRetryTried && resp.StatusCode == http.StatusBadRequest && upstreamCode == "invalid_encrypted_content" { decoded, decodeErr := ensureReqBody() if decodeErr != nil { @@ -869,8 +886,17 @@ func (s *OpenAIGatewayService) buildUpstreamRequest(ctx context.Context, c *gin. } req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI)) - // Set authentication header - req.Header.Set("authorization", "Bearer "+token) + // Build authentication for this request. Agent Identity signs a fresh + // assertion here; OAuth/PAT/API-key keep their existing Bearer behavior. + authHeaders, err := s.buildOpenAIAuthenticationHeaders(ctx, account, token) + if err != nil { + return nil, fmt.Errorf("build openai authentication headers: %w", err) + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } // Set headers specific to OAuth accounts (ChatGPT internal API) if account.Type == AccountTypeOAuth { diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 238d359b9e..2ea914b537 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -338,7 +338,15 @@ func (s *OpenAIGatewayService) buildUpstreamRequestOpenAIPassthrough( req.Header.Del("authorization") req.Header.Del("x-api-key") req.Header.Del("x-goog-api-key") - req.Header.Set("authorization", "Bearer "+token) + authHeaders, err := s.buildOpenAIAuthenticationHeaders(ctx, account, token) + if err != nil { + return nil, fmt.Errorf("build openai authentication headers: %w", err) + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } // OAuth 透传到 ChatGPT internal API 时补齐必要头。 if account.Type == AccountTypeOAuth { @@ -434,6 +442,7 @@ func (s *OpenAIGatewayService) handleFailoverErrorResponsePassthrough( requestBody []byte, ) error { body := s.readUpstreamErrorBody(resp) + body = s.redactAgentIdentitySensitiveBody(ctx, account, body) upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(body)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) @@ -477,6 +486,7 @@ func (s *OpenAIGatewayService) handleErrorResponsePassthrough( ) error { MarkResponseCommitted(c) body := s.readUpstreamErrorBody(resp) + body = s.redactAgentIdentitySensitiveBody(ctx, account, body) // cyber_policy:透传账号本就把原始 body 回给客户端(下方 c.Data),此处仅打标记, // 供 handler 事后写风控/邮件。cyber 是上游网络安全策略拦截,不冷却账号, diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index 0d03d83dcf..a17a6f6b05 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -356,6 +356,7 @@ type OpenAIGatewayService struct { openaiWSStateStoreOnce sync.Once openaiSchedulerOnce sync.Once openaiWSPassthroughDialerOnce sync.Once + agentIdentityTaskMu sync.Mutex openaiWSPool *openAIWSConnPool openaiWSStateStore OpenAIWSStateStore openaiScheduler OpenAIAccountScheduler @@ -1052,6 +1053,9 @@ func (s *OpenAIGatewayService) GetAccessToken(ctx context.Context, account *Acco } switch account.Type { case AccountTypeOAuth: + if account.IsOpenAIAgentIdentity() { + return "", OpenAIAuthModeAgentIdentity, nil + } if account.Platform == PlatformGrok { if s.grokTokenProvider != nil { accessToken, err := s.grokTokenProvider.GetAccessToken(ctx, account) diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index 2e661e7417..bc9bf91fef 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -279,6 +279,7 @@ func (s *OpenAIGatewayService) handleErrorResponse( requestedModel ...string, ) (*OpenAIForwardResult, error) { body := s.readUpstreamErrorBody(resp) + body = s.redactAgentIdentitySensitiveBody(ctx, account, body) // cyber_policy 硬阻断:透传上游原始错误体给客户端(不重包成通用 502),不冷却账号。 // 当前请求恒透传(需求1);标记供 handler 事后写风控/邮件。400 cyber 不可 failover diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index fc7d37a173..b411cb3104 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -752,7 +752,15 @@ func (s *OpenAIGatewayService) buildOpenAIImagesRequest( return nil, err } req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI)) - req.Header.Set("Authorization", "Bearer "+token) + authHeaders, err := s.buildOpenAIAuthenticationHeaders(ctx, account, token) + if err != nil { + return nil, fmt.Errorf("build openai authentication headers: %w", err) + } + for key, values := range authHeaders { + for _, value := range values { + req.Header.Add(key, value) + } + } for key, values := range c.Request.Header { if !openaiPassthroughAllowedHeaders[strings.ToLower(key)] { continue diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index 337f8c1e8f..b8b766fcff 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -10,6 +10,7 @@ import ( "log/slog" "net/http" "strings" + "sync" "time" infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" @@ -118,6 +119,7 @@ type OpenAIQuotaService struct { proxyRepo ProxyRepository tokenProvider *OpenAITokenProvider privacyClientFactory PrivacyClientFactory + agentIdentityTaskMu sync.Mutex } // NewOpenAIQuotaService constructs a quota service. token provider is required — @@ -154,10 +156,14 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* callCtx, cancel := context.WithTimeout(ctx, openaiQuotaUpstreamTimeout) defer cancel() + quotaHeaders, headerErr := s.buildCodexQuotaHeaders(callCtx, accountID, accessToken, chatGPTAccountID, fedRAMP) + if headerErr != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "failed to build upstream authentication: %v", headerErr) + } var payload OpenAIQuotaUsage resp, err := client.R(). SetContext(callCtx). - SetHeaders(buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP)). + SetHeaders(quotaHeaders). SetSuccessResult(&payload). Get(chatGPTUsageURL) if err != nil { @@ -178,9 +184,14 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* } func (s *OpenAIQuotaService) queryResetCreditDetails(ctx context.Context, client *req.Client, accessToken, chatGPTAccountID string, fedRAMP bool, accountID int64) []OpenAIRateLimitResetCreditDetail { + quotaHeaders, headerErr := s.buildCodexQuotaHeaders(ctx, accountID, accessToken, chatGPTAccountID, fedRAMP) + if headerErr != nil { + slog.Warn("openai_quota_reset_credit_details_auth_failed", "account_id", accountID, "error", headerErr) + return nil + } resp, err := client.R(). SetContext(ctx). - SetHeaders(buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP)). + SetHeaders(quotaHeaders). Get(chatGPTRateLimitCreditsURL) if err != nil { slog.Warn("openai_quota_reset_credit_details_failed", "account_id", accountID, "error", err) @@ -239,7 +250,10 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( callCtx, cancel := context.WithTimeout(ctx, openaiQuotaUpstreamTimeout) defer cancel() - headers := buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP) + headers, headerErr := s.buildCodexQuotaHeaders(callCtx, accountID, accessToken, chatGPTAccountID, fedRAMP) + if headerErr != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "failed to build upstream authentication: %v", headerErr) + } headers["content-type"] = "application/json" var payload OpenAIQuotaResetResult @@ -271,7 +285,7 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( // token via the shared TokenProvider, and resolves the chatgpt-account-id and // proxy URL. Centralized so QueryUsage / ResetCredit share validation. func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID int64) (accessToken, chatGPTAccountID, proxyURL string, fedRAMP bool, err error) { - if s == nil || s.accountRepo == nil || s.tokenProvider == nil || s.privacyClientFactory == nil { + if s == nil || s.accountRepo == nil || s.privacyClientFactory == nil { return "", "", "", false, infraerrors.New(http.StatusInternalServerError, "OPENAI_QUOTA_NOT_CONFIGURED", "openai quota service is not configured") } @@ -309,12 +323,17 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID return "", "", "", false, infraerrors.New(http.StatusBadRequest, "OPENAI_QUOTA_MISSING_ACCOUNT_ID", "chatgpt_account_id is missing; please re-authorize this account") } - accessToken, err = s.tokenProvider.GetAccessToken(ctx, account) - if err != nil { - return "", "", "", false, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_TOKEN_UNAVAILABLE", "failed to acquire access token: %v", err) - } - if strings.TrimSpace(accessToken) == "" { - return "", "", "", false, infraerrors.New(http.StatusBadGateway, "OPENAI_QUOTA_TOKEN_UNAVAILABLE", "access token is empty") + if !account.IsOpenAIAgentIdentity() { + if s.tokenProvider == nil { + return "", "", "", false, infraerrors.New(http.StatusInternalServerError, "OPENAI_QUOTA_NOT_CONFIGURED", "openai quota token provider is not configured") + } + accessToken, err = s.tokenProvider.GetAccessToken(ctx, account) + if err != nil { + return "", "", "", false, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_TOKEN_UNAVAILABLE", "failed to acquire access token: %v", err) + } + if strings.TrimSpace(accessToken) == "" { + return "", "", "", false, infraerrors.New(http.StatusBadGateway, "OPENAI_QUOTA_TOKEN_UNAVAILABLE", "access token is empty") + } } fedRAMP = account.IsChatGPTAccountFedRAMP() @@ -337,6 +356,43 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID return accessToken, chatGPTAccountID, proxyURL, fedRAMP, nil } +func (s *OpenAIQuotaService) buildCodexQuotaHeaders(ctx context.Context, accountID int64, accessToken, chatGPTAccountID string, fedRAMP bool) (map[string]string, error) { + headers := buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP) + if s == nil || s.accountRepo == nil { + return headers, nil + } + account, err := s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil { + if strings.TrimSpace(accessToken) == "" { + return nil, fmt.Errorf("agent identity account credentials are unavailable") + } + return headers, nil + } + if account.IsShadow() { + if resolved, resolveErr := resolveCredentialAccount(ctx, s.accountRepo, account); resolveErr == nil && resolved != nil { + account = resolved + } else if strings.TrimSpace(accessToken) == "" { + return nil, fmt.Errorf("agent identity shadow credentials are unavailable") + } + } + if !account.IsOpenAIAgentIdentity() { + return headers, nil + } + if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, account, ""); err != nil { + return nil, err + } + key, err := agentIdentityKeyFromAccount(account) + if err != nil { + return nil, err + } + assertion, err := buildAgentAssertion(key, time.Now()) + if err != nil { + return nil, err + } + headers["authorization"] = assertion + return headers, nil +} + // buildCodexCommonHeaders sets the request headers expected by the chatgpt.com // backend so calls succeed past Cloudflare/WASM checks. func buildCodexCommonHeaders(accessToken, chatGPTAccountID string, fedRAMP bool) map[string]string { diff --git a/backend/internal/service/openai_quota_spark_window_test.go b/backend/internal/service/openai_quota_spark_window_test.go index c56600d3f5..d2b18af05b 100644 --- a/backend/internal/service/openai_quota_spark_window_test.go +++ b/backend/internal/service/openai_quota_spark_window_test.go @@ -2,6 +2,10 @@ package service import ( "context" + "crypto/ed25519" + "crypto/rand" + "crypto/x509" + "encoding/base64" "encoding/json" "errors" "fmt" @@ -214,6 +218,45 @@ func TestPrepareUpstreamCallShadowResolve(t *testing.T) { "prepareUpstreamCall should use parent's chatgpt_account_id after shadow resolve") } +func TestQueryUsageAgentIdentityUsesAssertionWithoutOAuthToken(t *testing.T) { + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + der, err := x509.MarshalPKCS8PrivateKey(privateKey) + require.NoError(t, err) + account := &Account{ + ID: 300, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": "runtime-quota", + "agent_private_key": base64.StdEncoding.EncodeToString(der), + "task_id": "task-quota", + "chatgpt_account_id": "account-quota", + "chatgpt_account_is_fedramp": true, + }, + } + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + var authorization string + var accountHeader string + var fedrampHeader string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authorization = r.Header.Get("authorization") + accountHeader = r.Header.Get("chatgpt-account-id") + fedrampHeader = r.Header.Get("x-openai-fedramp") + w.Header().Set("content-type", "application/json") + _, _ = w.Write([]byte(`{"plan_type":"pro","rate_limit":{"allowed":true}}`)) + })) + defer srv.Close() + svc := NewOpenAIQuotaService(repo, nil, nil, newQuotaRedirectingFactory(srv)) + usage, err := svc.QueryUsage(context.Background(), account.ID) + require.NoError(t, err) + require.NotNil(t, usage) + require.True(t, strings.HasPrefix(authorization, "AgentAssertion ")) + require.Equal(t, "account-quota", accountHeader) + require.Equal(t, "true", fedrampHeader) +} + func TestParseOpenAIRateLimitResetCreditDetails_CompatibleContainers(t *testing.T) { tests := []struct { name string diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 45e004b6d0..9a6453892a 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -539,6 +539,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( Account: account, WSURL: wsURL, Headers: wsHeaders, + HeadersFactory: func(factoryCtx context.Context, headers http.Header) (http.Header, error) { + return s.refreshOpenAIAgentIdentityHeaders(factoryCtx, account, headers) + }, ProxyURL: func() string { if account.ProxyID != nil && account.Proxy != nil { return account.Proxy.URL() @@ -602,7 +605,9 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( acquireTimeout = 30 * time.Second } - acquireTurnLease := func(turn int, preferred string, forcePreferredConn bool) (*openAIWSConnLease, error) { + agentTaskRecoveryTried := false + var acquireTurnLease func(int, string, bool) (*openAIWSConnLease, error) + acquireTurnLease = func(turn int, preferred string, forcePreferredConn bool) (*openAIWSConnLease, error) { req := cloneOpenAIWSAcquireRequest(baseAcquireReq) req.PreferredConnID = strings.TrimSpace(preferred) req.ForcePreferredConn = forcePreferredConn @@ -611,6 +616,14 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( acquireCtx, acquireCancel := context.WithTimeout(ctx, acquireTimeout) lease, acquireErr := pool.Acquire(acquireCtx, req) acquireCancel() + var dialErr *openAIWSDialError + if acquireErr != nil && s.isAgentIdentityAccount(ctx, account) && errors.As(acquireErr, &dialErr) && dialErr != nil && dialErr.StatusCode == http.StatusUnauthorized && !agentTaskRecoveryTried { + agentTaskRecoveryTried = true + if recoveryErr := s.recoverAgentIdentityTask(ctx, account, account.GetCredential("task_id")); recoveryErr != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) + } + return acquireTurnLease(turn, preferred, forcePreferredConn) + } if acquireErr != nil { dialStatus, dialClass, dialCloseStatus, dialCloseReason, dialRespServer, dialRespVia, dialRespCFRay, dialRespReqID := summarizeOpenAIWSDialError(acquireErr) logOpenAIWSModeInfo( diff --git a/backend/internal/service/openai_ws_forwarder_payload.go b/backend/internal/service/openai_ws_forwarder_payload.go index a4d47218e7..0aa4adc313 100644 --- a/backend/internal/service/openai_ws_forwarder_payload.go +++ b/backend/internal/service/openai_ws_forwarder_payload.go @@ -67,7 +67,9 @@ func (s *OpenAIGatewayService) buildOpenAIWSHeaders( promptCacheKey string, ) (http.Header, openAIWSSessionHeaderResolution, error) { headers := make(http.Header) - headers.Set("authorization", "Bearer "+token) + if account == nil || !account.IsOpenAIAgentIdentity() { + headers.Set("authorization", "Bearer "+token) + } sessionResolution := resolveOpenAIWSSessionHeaders(c, promptCacheKey) if c != nil && c.Request != nil { diff --git a/backend/internal/service/openai_ws_forwarder_v2.go b/backend/internal/service/openai_ws_forwarder_v2.go index f0f71648dd..65a6add7a5 100644 --- a/backend/internal/service/openai_ws_forwarder_v2.go +++ b/backend/internal/service/openai_ws_forwarder_v2.go @@ -30,6 +30,7 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( startTime time.Time, attempt int, lastFailureReason string, + agentTaskRecoveryTried *bool, ) (*OpenAIForwardResult, error) { if s == nil || account == nil { return nil, wrapOpenAIWSFallback("invalid_state", errors.New("service or account is nil")) @@ -174,9 +175,12 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( defer acquireCancel() lease, err := s.getOpenAIWSConnPool().Acquire(acquireCtx, openAIWSAcquireRequest{ - Account: account, - WSURL: wsURL, - Headers: wsHeaders, + Account: account, + WSURL: wsURL, + Headers: wsHeaders, + HeadersFactory: func(factoryCtx context.Context, headers http.Header) (http.Header, error) { + return s.refreshOpenAIAgentIdentityHeaders(factoryCtx, account, headers) + }, PreferredConnID: preferredConnID, ForceNewConn: forceNewConn, ProxyURL: func() string { @@ -187,6 +191,14 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( }(), }) if err != nil { + var agentDialErr *openAIWSDialError + if s.isAgentIdentityAccount(ctx, account) && errors.As(err, &agentDialErr) && agentDialErr != nil && agentDialErr.StatusCode == http.StatusUnauthorized && agentTaskRecoveryTried != nil && !*agentTaskRecoveryTried { + *agentTaskRecoveryTried = true + if recoveryErr := s.recoverAgentIdentityTask(ctx, account, account.GetCredential("task_id")); recoveryErr != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) + } + return nil, &agentIdentityTaskRecoveredError{} + } dialStatus, dialClass, dialCloseStatus, dialCloseReason, dialRespServer, dialRespVia, dialRespCFRay, dialRespReqID := summarizeOpenAIWSDialError(err) logOpenAIWSModeInfo( "acquire_fail account_id=%d account_type=%s transport=%s reason=%s dial_status=%d dial_class=%s dial_close_status=%s dial_close_reason=%s dial_resp_server=%s dial_resp_via=%s dial_resp_cf_ray=%s dial_resp_x_request_id=%s cause=%s preferred_conn_id=%s force_new_conn=%v ws_host=%s ws_path=%s proxy_enabled=%v", diff --git a/backend/internal/service/openai_ws_pool.go b/backend/internal/service/openai_ws_pool.go index 5950e02841..be81d611f9 100644 --- a/backend/internal/service/openai_ws_pool.go +++ b/backend/internal/service/openai_ws_pool.go @@ -60,9 +60,13 @@ func (e *openAIWSDialError) Unwrap() error { } type openAIWSAcquireRequest struct { - Account *Account - WSURL string - Headers http.Header + Account *Account + WSURL string + Headers http.Header + // HeadersFactory is evaluated inside dialConn. It exists so credentials + // whose authorization is per-dial (Agent Identity) are never cached in + // lastAcquire or delayed prewarm state. + HeadersFactory func(context.Context, http.Header) (http.Header, error) ProxyURL string PreferredConnID string // ForceNewConn: 强制本次获取新连接(避免复用导致连接内续链状态互相污染)。 @@ -517,6 +521,7 @@ type openAIWSAccountPool struct { conns map[string]*openAIWSConn pinnedConns map[string]int creating int + generation uint64 lastCleanupAt time.Time lastAcquire *openAIWSAcquireRequest prewarmActive bool @@ -1283,6 +1288,7 @@ func (p *openAIWSConnPool) ensureTargetIdleAsync(accountID int64) { } var req openAIWSAcquireRequest + generation := uint64(0) need := 0 ap, ok := p.getAccountPool(accountID) if !ok || ap == nil { @@ -1317,6 +1323,7 @@ func (p *openAIWSConnPool) ensureTargetIdleAsync(accountID int64) { return } req = cloneOpenAIWSAcquireRequest(*ap.lastAcquire) + generation = ap.generation ap.prewarmActive = true if cooldown := p.prewarmCooldown(); cooldown > 0 { ap.prewarmUntil = now.Add(cooldown) @@ -1324,7 +1331,7 @@ func (p *openAIWSConnPool) ensureTargetIdleAsync(accountID int64) { ap.creating += need p.metrics.scaleUpTotal.Add(int64(need)) - go p.prewarmConns(accountID, req, need) + go p.prewarmConns(accountID, req, need, generation) } func (p *openAIWSConnPool) targetConnCountLocked(ap *openAIWSAccountPool, maxConns int) int { @@ -1367,7 +1374,11 @@ func (p *openAIWSConnPool) targetConnCountLocked(ap *openAIWSAccountPool, maxCon return target } -func (p *openAIWSConnPool) prewarmConns(accountID int64, req openAIWSAcquireRequest, total int) { +func (p *openAIWSConnPool) prewarmConns(accountID int64, req openAIWSAcquireRequest, total int, generations ...uint64) { + generation := uint64(0) + if len(generations) > 0 { + generation = generations[0] + } defer func() { if ap, ok := p.getAccountPool(accountID); ok && ap != nil { ap.mu.Lock() @@ -1398,6 +1409,11 @@ func (p *openAIWSConnPool) prewarmConns(accountID int64, req openAIWSAcquireRequ ap.mu.Unlock() continue } + if ap.generation != generation || ap.lastAcquire == nil { + ap.mu.Unlock() + conn.close() + continue + } if len(ap.conns) >= p.effectiveMaxConnsByAccount(req.Account) { ap.mu.Unlock() conn.close() @@ -1410,6 +1426,35 @@ func (p *openAIWSConnPool) prewarmConns(accountID int64, req openAIWSAcquireRequ } } +// ClearAccount closes all pooled connections and discards delayed prewarm +// state for one account. The generation guard prevents an in-flight prewarm +// started before credential recovery from re-entering the pool afterwards. +func (p *openAIWSConnPool) ClearAccount(accountID int64) { + if p == nil || accountID <= 0 { + return + } + ap, ok := p.getAccountPool(accountID) + if !ok || ap == nil { + return + } + ap.mu.Lock() + ap.generation++ + conns := make([]*openAIWSConn, 0, len(ap.conns)) + for id, conn := range ap.conns { + delete(ap.conns, id) + delete(ap.pinnedConns, id) + if conn != nil { + conns = append(conns, conn) + } + } + ap.lastAcquire = nil + ap.prewarmUntil = time.Time{} + ap.prewarmFails = 0 + ap.prewarmFailAt = time.Time{} + ap.mu.Unlock() + closeOpenAIWSConns(conns) +} + func (p *openAIWSConnPool) evictConn(accountID int64, connID string) { if p == nil || accountID <= 0 || stringsTrim(connID) == "" { return @@ -1485,7 +1530,15 @@ func (p *openAIWSConnPool) dialConn(ctx context.Context, req openAIWSAcquireRequ if p == nil || p.clientDialer == nil { return nil, errors.New("openai ws client dialer is nil") } - conn, status, handshakeHeaders, err := p.clientDialer.Dial(ctx, req.WSURL, req.Headers, req.ProxyURL) + headers := cloneHeader(req.Headers) + var err error + if req.HeadersFactory != nil { + headers, err = req.HeadersFactory(ctx, headers) + if err != nil { + return nil, err + } + } + conn, status, handshakeHeaders, err := p.clientDialer.Dial(ctx, req.WSURL, headers, req.ProxyURL) if err != nil { return nil, &openAIWSDialError{ StatusCode: status, diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index d822d181cd..01b66c376b 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -359,10 +359,28 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( return errors.New("openai ws passthrough dialer is nil") } - dialCtx, cancelDial := context.WithTimeout(ctx, s.openAIWSDialTimeout()) - defer cancelDial() - upstreamConn, statusCode, handshakeHeaders, err := dialer.Dial(dialCtx, wsURL, headers, proxyURL) - if err != nil { + agentTaskRecoveryTried := false + var upstreamConn openAIWSClientConn + statusCode := 0 + var handshakeHeaders http.Header + for { + headers, err = s.refreshOpenAIAgentIdentityHeaders(ctx, account, headers) + if err != nil { + return fmt.Errorf("refresh ws authentication headers: %w", err) + } + dialCtx, cancelDial := context.WithTimeout(ctx, s.openAIWSDialTimeout()) + upstreamConn, statusCode, handshakeHeaders, err = dialer.Dial(dialCtx, wsURL, headers, proxyURL) + cancelDial() + if err == nil { + break + } + if s.isAgentIdentityAccount(ctx, account) && statusCode == http.StatusUnauthorized && !agentTaskRecoveryTried { + agentTaskRecoveryTried = true + if recoveryErr := s.recoverAgentIdentityTask(ctx, account, account.GetCredential("task_id")); recoveryErr != nil { + return fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) + } + continue + } logOpenAIWSV2Passthrough( "relay_dial_failed account_id=%d status_code=%d err=%s", account.ID, From 57cf2df09fe743db260b8dfa4a446498959dcedb Mon Sep 17 00:00:00 2001 From: cat Date: Tue, 14 Jul 2026 16:54:53 +0800 Subject: [PATCH 14/83] =?UTF-8?q?fix(openai):=20=E6=94=B6=E7=B4=A7=20Agent?= =?UTF-8?q?=20Identity=20=E6=81=A2=E5=A4=8D=E4=B8=8E=E8=84=B1=E6=95=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/service/account_test_service.go | 4 ++ .../internal/service/openai_agent_identity.go | 43 +++++++++++++-- .../openai_agent_identity_compat_test.go | 49 ++++++++++++++++- .../service/openai_agent_identity_test.go | 38 +++++++++++++ .../service/openai_gateway_passthrough.go | 55 +++++++++++++------ .../internal/service/openai_quota_service.go | 15 ++++- backend/internal/service/openai_ws_client.go | 30 +++++++++- .../service/openai_ws_forwarder_ingress.go | 2 +- .../service/openai_ws_forwarder_v2.go | 2 +- backend/internal/service/openai_ws_pool.go | 7 +++ .../openai_ws_v2_passthrough_adapter.go | 9 ++- 11 files changed, 224 insertions(+), 30 deletions(-) diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index f83a99a7e2..5a0bc40f40 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -655,6 +655,7 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) + body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) if resp.StatusCode == http.StatusTooManyRequests { s.reconcileOpenAI429State(ctx, account, resp.Header, body) } @@ -924,6 +925,7 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account defer func() { _ = resp.Body.Close() }() body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20)) + body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) if s.accountRepo != nil { updates := buildOpenAICompactProbeExtraUpdates(resp, body, nil, time.Now()) @@ -1800,6 +1802,7 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co }() if resp.StatusCode >= 400 { body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20)) + body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) message := strings.TrimSpace(extractUpstreamErrorMessage(body)) if message == "" { message = fmt.Sprintf("Responses API returned %d", resp.StatusCode) @@ -1811,6 +1814,7 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co if err != nil { return s.sendErrorAndEnd(c, fmt.Sprintf("Failed to read image response: %s", err.Error())) } + body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) results, _, _, _, _, err := collectOpenAIImagesFromResponsesBody(body) if err != nil { diff --git a/backend/internal/service/openai_agent_identity.go b/backend/internal/service/openai_agent_identity.go index c8818cd6f3..8383a10e9c 100644 --- a/backend/internal/service/openai_agent_identity.go +++ b/backend/internal/service/openai_agent_identity.go @@ -29,6 +29,8 @@ const ( var openAIAgentIdentityAuthAPIBaseURL = agentIdentityAuthAPIBaseURL +var agentIdentityTaskLocks sync.Map // map[int64]*sync.Mutex + type agentIdentityKey struct { runtimeID string privateKey ed25519.PrivateKey @@ -251,8 +253,14 @@ func ensureAgentIdentityTaskForAccount(ctx context.Context, repo AccountReposito if taskMu == nil { return errors.New("agent identity task lock is unavailable") } - taskMu.Lock() - defer taskMu.Unlock() + sharedTaskMu := taskMu + if credAccount.ID > 0 { + candidate := &sync.Mutex{} + actual, _ := agentIdentityTaskLocks.LoadOrStore(credAccount.ID, candidate) + sharedTaskMu = actual.(*sync.Mutex) + } + sharedTaskMu.Lock() + defer sharedTaskMu.Unlock() currentTaskID = strings.TrimSpace(credAccount.GetCredential("task_id")) if currentTaskID != "" && (expectedTaskID == "" || currentTaskID != expectedTaskID) { return nil @@ -302,6 +310,10 @@ func isAgentIdentityTaskInvalidHTTPResponse(statusCode int, body []byte) bool { return false } +func isAgentIdentityTaskInvalidWSDialError(err *openAIWSDialError) bool { + return err != nil && isAgentIdentityTaskInvalidHTTPResponse(err.StatusCode, err.ResponseBody) +} + func (s *OpenAIGatewayService) buildOpenAIAuthenticationHeaders(ctx context.Context, account *Account, token string) (http.Header, error) { if account == nil { return nil, errors.New("account is nil") @@ -401,16 +413,19 @@ func (s *OpenAIGatewayService) isAgentIdentityAccount(ctx context.Context, accou // upstream error can reach logs, ops events, or returned error text. Agent // Identity responses should not echo these values, but keeping this boundary // defensive prevents accidental disclosure if an upstream error does. -func (s *OpenAIGatewayService) redactAgentIdentitySensitiveBody(ctx context.Context, account *Account, body []byte) []byte { - if !s.isAgentIdentityAccount(ctx, account) || len(body) == 0 { +func redactAgentIdentitySensitiveBodyForAccount(ctx context.Context, repo AccountRepository, account *Account, body []byte) []byte { + if account == nil || len(body) == 0 { return body } credAccount := account if account != nil && account.IsShadow() { - if resolved, err := resolveCredentialAccount(ctx, s.accountRepo, account); err == nil && resolved != nil { + if resolved, err := resolveCredentialAccount(ctx, repo, account); err == nil && resolved != nil { credAccount = resolved } } + if credAccount == nil || !credAccount.IsOpenAIAgentIdentity() { + return body + } redacted := string(body) for _, key := range []string{ "agent_private_key", @@ -427,5 +442,23 @@ func (s *OpenAIGatewayService) redactAgentIdentitySensitiveBody(ctx context.Cont redacted = strings.ReplaceAll(redacted, value, "[redacted]") } } + for { + start := strings.Index(redacted, "AgentAssertion ") + if start < 0 { + break + } + end := start + len("AgentAssertion ") + for end < len(redacted) && !strings.ContainsRune(" \t\r\n\"',}", rune(redacted[end])) { + end++ + } + redacted = redacted[:start] + "AgentAssertion [redacted]" + redacted[end:] + } return []byte(redacted) } + +func (s *OpenAIGatewayService) redactAgentIdentitySensitiveBody(ctx context.Context, account *Account, body []byte) []byte { + if !s.isAgentIdentityAccount(ctx, account) { + return body + } + return redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, account, body) +} diff --git a/backend/internal/service/openai_agent_identity_compat_test.go b/backend/internal/service/openai_agent_identity_compat_test.go index 5c0c996c42..c034af2bfa 100644 --- a/backend/internal/service/openai_agent_identity_compat_test.go +++ b/backend/internal/service/openai_agent_identity_compat_test.go @@ -104,13 +104,45 @@ func TestOpenAIAgentIdentityErrorRedactionDoesNotLeakCredentialValues(t *testing } svc := &OpenAIGatewayService{} oauthValue := account.GetCredential("access_token") - redacted := svc.redactAgentIdentitySensitiveBody(context.Background(), account, []byte(`{"message":"runtime-test task-test `+oauthValue+`"}`)) + redacted := svc.redactAgentIdentitySensitiveBody(context.Background(), account, []byte(`{"message":"runtime-test task-test `+oauthValue+` AgentAssertion abc123"}`)) require.NotContains(t, string(redacted), key.runtimeID) require.NotContains(t, string(redacted), key.taskID) require.NotContains(t, string(redacted), oauthValue) + require.NotContains(t, string(redacted), "AgentAssertion abc123") require.Contains(t, string(redacted), "[redacted]") } +func TestOpenAIAuthenticationHeadersPreserveOAuthPATAndAPIKeyBearerModes(t *testing.T) { + svc := &OpenAIGatewayService{} + tests := []struct { + name string + account *Account + token string + }{ + {name: "oauth", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth}, token: "oauth-runtime-token"}, + {name: "personal access token", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"auth_mode": OpenAIAuthModePersonalAccessToken}}, token: "pat-runtime-token"}, + {name: "api key", account: &Account{Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, token: "api-key-runtime-token"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + headers, err := svc.buildOpenAIAuthenticationHeaders(context.Background(), tt.account, tt.token) + require.NoError(t, err) + require.Equal(t, "Bearer "+tt.token, headers.Get("Authorization")) + }) + } +} + +func TestOpenAIWSAgentIdentityRecoveryRequiresTaskInvalidBody(t *testing.T) { + require.False(t, isAgentIdentityTaskInvalidWSDialError(&openAIWSDialError{ + StatusCode: http.StatusUnauthorized, + ResponseBody: []byte(`{"error":{"code":"invalid_signature"}}`), + })) + require.True(t, isAgentIdentityTaskInvalidWSDialError(&openAIWSDialError{ + StatusCode: http.StatusUnauthorized, + ResponseBody: []byte(`{"error":{"code":"invalid_task_id"}}`), + })) +} + func TestOpenAIWSConnPoolHeadersFactoryRunsAtDialAndStalePrewarmIsDiscarded(t *testing.T) { cfg := &config.Config{} cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 1 @@ -218,6 +250,21 @@ func TestOpenAIAgentIdentityTaskInvalidRetriesExactlyOnce(t *testing.T) { require.Error(t, err) require.Equal(t, 2, registerCalls) require.Len(t, upstream.requests, 4) + + // Passthrough uses the same one-shot task recovery contract. + account.Extra = map[string]any{"openai_passthrough": true} + account.Credentials["task_id"] = "task-old-passthrough" + upstream.responses = []*http.Response{ + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(successBody))}, + } + rec3 := httptest.NewRecorder() + c3, _ := gin.CreateTestContext(rec3) + c3.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + _, err = svc.Forward(context.Background(), c3, account, []byte(`{"model":"gpt-5.4","instructions":"Reply OK","input":[],"stream":false}`)) + require.NoError(t, err) + require.Equal(t, 3, registerCalls) + require.Len(t, upstream.requests, 6) } func decodeAgentAssertionTask(t *testing.T, header string) string { diff --git a/backend/internal/service/openai_agent_identity_test.go b/backend/internal/service/openai_agent_identity_test.go index 73ac0ddf08..6e94f53abe 100644 --- a/backend/internal/service/openai_agent_identity_test.go +++ b/backend/internal/service/openai_agent_identity_test.go @@ -156,6 +156,44 @@ func TestEnsureAgentIdentityTaskPersistsAndRedactsCredentials(t *testing.T) { require.NotContains(t, string(mustJSON(t, redacted)), privateKey) } +func TestEnsureAgentIdentityTaskSharesLockAcrossServicesForSameAccount(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ID: 9001, Type: AccountTypeOAuth, Platform: PlatformOpenAI, Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + }} + repo := &agentIdentityCredentialsRepo{} + registerCalls := 0 + var registerMu sync.Mutex + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + registerMu.Lock() + registerCalls++ + registerMu.Unlock() + _, _ = w.Write([]byte(`{"task_id":"task-shared"}`)) + })) + defer server.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = server.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + start := make(chan struct{}) + errors := make(chan error, 2) + for range 2 { + go func() { + <-start + errors <- ensureAgentIdentityTaskForAccount(context.Background(), repo, nil, &sync.Mutex{}, account, "") + }() + } + close(start) + require.NoError(t, <-errors) + require.NoError(t, <-errors) + registerMu.Lock() + defer registerMu.Unlock() + require.Equal(t, 1, registerCalls) + require.Equal(t, "task-shared", account.GetCredential("task_id")) +} + type agentIdentityCredentialsRepo struct { AccountRepository credentials map[string]any diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 2ea914b537..f280f37841 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -11,6 +11,7 @@ import ( "encoding/json" "errors" "fmt" + "io" "net/http" "sort" "strings" @@ -161,13 +162,6 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( return nil, err } - upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) - upstreamReq, err := s.buildUpstreamRequestOpenAIPassthrough(upstreamCtx, c, account, body, token) - releaseUpstreamCtx() - if err != nil { - return nil, err - } - proxyURL := "" if account.ProxyID != nil && account.Proxy != nil { proxyURL = account.Proxy.URL() @@ -177,18 +171,42 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( c.Set("openai_passthrough", true) } - upstreamStart := time.Now() - resp, err := s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.Concurrency) - SetOpsLatencyMs(c, OpsUpstreamLatencyMsKey, time.Since(upstreamStart).Milliseconds()) - if err != nil { - // Transport-level failure (proxy/DNS/TCP/TLS — no HTTP response). Convert to - // a failover so the handler switches to a healthy account, and temporarily - // unschedule the account on durable faults (e.g. rejected proxy credentials). - return nil, s.handleOpenAIUpstreamTransportError(ctx, c, account, err, true) - } - defer func() { _ = resp.Body.Close() }() + agentTaskRecoveryTried := false + var resp *http.Response + for { + upstreamCtx, releaseUpstreamCtx := detachUpstreamContext(ctx) + upstreamReq, buildErr := s.buildUpstreamRequestOpenAIPassthrough(upstreamCtx, c, account, body, token) + releaseUpstreamCtx() + if buildErr != nil { + return nil, buildErr + } + + upstreamStart := time.Now() + resp, err = s.httpUpstream.Do(upstreamReq, proxyURL, account.ID, account.Concurrency) + SetOpsLatencyMs(c, OpsUpstreamLatencyMsKey, time.Since(upstreamStart).Milliseconds()) + if err != nil { + // Transport-level failure (proxy/DNS/TCP/TLS — no HTTP response). Convert to + // a failover so the handler switches to a healthy account. + return nil, s.handleOpenAIUpstreamTransportError(ctx, c, account, err, true) + } + if resp.StatusCode < 400 { + break + } + + // Peek only to identify an invalid task. Restore the body so the existing + // passthrough error handling sees the same response after recovery fails. + probeBody := s.readUpstreamErrorBody(resp) + _ = resp.Body.Close() + resp.Body = io.NopCloser(bytes.NewReader(probeBody)) + if !agentTaskRecoveryTried && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, probeBody) { + agentTaskRecoveryTried = true + expectedTaskID := account.GetCredential("task_id") + if recoveryErr := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); recoveryErr != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) + } + continue + } - if resp.StatusCode >= 400 { // 透传模式默认保持原样代理;但 429/529 属于网关必须兜底的 // 上游容量类错误,应先触发多账号 failover 以维持基础 SLA。 if shouldFailoverOpenAIPassthroughResponse(resp.StatusCode) { @@ -196,6 +214,7 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( } return nil, s.handleErrorResponsePassthrough(ctx, resp, c, account, body) } + defer func() { _ = resp.Body.Close() }() serviceTier := extractOpenAIServiceTierFromBody(body) diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index b8b766fcff..cebab0a1d7 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -171,7 +171,7 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* } if !resp.IsSuccessState() { status := resp.StatusCode - body := truncate(resp.String(), 240) + body := truncate(s.redactQuotaErrorBody(ctx, accountID, resp.String()), 240) slog.Warn("openai_quota_query_failed", "account_id", accountID, "status", status, "body", body) return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) } @@ -268,7 +268,7 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( } if !resp.IsSuccessState() { status := resp.StatusCode - body := truncate(resp.String(), 240) + body := truncate(s.redactQuotaErrorBody(callCtx, accountID, resp.String()), 240) slog.Warn("openai_quota_reset_failed", "account_id", accountID, "status", status, "body", body) return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_RESET_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) } @@ -393,6 +393,17 @@ func (s *OpenAIQuotaService) buildCodexQuotaHeaders(ctx context.Context, account return headers, nil } +func (s *OpenAIQuotaService) redactQuotaErrorBody(ctx context.Context, accountID int64, body string) string { + if s == nil || s.accountRepo == nil { + return body + } + account, err := s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil { + return body + } + return string(redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, account, []byte(body))) +} + // buildCodexCommonHeaders sets the request headers expected by the chatgpt.com // backend so calls succeed past Cloudflare/WASM checks. func buildCodexCommonHeaders(accessToken, chatGPTAccountID string, fedRAMP bool) map[string]string { diff --git a/backend/internal/service/openai_ws_client.go b/backend/internal/service/openai_ws_client.go index 80b7553083..d30c4a1cb3 100644 --- a/backend/internal/service/openai_ws_client.go +++ b/backend/internal/service/openai_ws_client.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "io" "net/http" "net/url" "strings" @@ -61,6 +62,28 @@ type coderOpenAIWSClientDialer struct { proxyMisses atomic.Int64 } +// openAIWSHandshakeError keeps a bounded, non-logged HTTP error body so the +// Agent Identity recovery path can distinguish an invalid task from other +// 401 handshake failures. +type openAIWSHandshakeError struct { + Body []byte + Err error +} + +func (e *openAIWSHandshakeError) Error() string { + if e == nil || e.Err == nil { + return "openai ws handshake failed" + } + return e.Err.Error() +} + +func (e *openAIWSHandshakeError) Unwrap() error { + if e == nil { + return nil + } + return e.Err +} + type openAIWSProxyClientEntry struct { client *http.Client lastUsedUnixNano int64 @@ -97,7 +120,12 @@ func (d *coderOpenAIWSClientDialer) Dial( status = resp.StatusCode respHeaders = cloneHeader(resp.Header) } - return nil, status, respHeaders, err + var body []byte + if resp != nil && resp.Body != nil { + body, _ = io.ReadAll(io.LimitReader(resp.Body, 8<<10)) + _ = resp.Body.Close() + } + return nil, status, respHeaders, &openAIWSHandshakeError{Body: body, Err: err} } // coder/websocket 默认单消息读取上限为 32KB,Codex WS 事件(如 rate_limits/大 delta) // 可能超过该阈值,需显式提高上限,避免本地 read_fail(message too big)。 diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 9a6453892a..169919b8b9 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -617,7 +617,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( lease, acquireErr := pool.Acquire(acquireCtx, req) acquireCancel() var dialErr *openAIWSDialError - if acquireErr != nil && s.isAgentIdentityAccount(ctx, account) && errors.As(acquireErr, &dialErr) && dialErr != nil && dialErr.StatusCode == http.StatusUnauthorized && !agentTaskRecoveryTried { + if acquireErr != nil && s.isAgentIdentityAccount(ctx, account) && errors.As(acquireErr, &dialErr) && isAgentIdentityTaskInvalidWSDialError(dialErr) && !agentTaskRecoveryTried { agentTaskRecoveryTried = true if recoveryErr := s.recoverAgentIdentityTask(ctx, account, account.GetCredential("task_id")); recoveryErr != nil { return nil, fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) diff --git a/backend/internal/service/openai_ws_forwarder_v2.go b/backend/internal/service/openai_ws_forwarder_v2.go index 65a6add7a5..90151be93a 100644 --- a/backend/internal/service/openai_ws_forwarder_v2.go +++ b/backend/internal/service/openai_ws_forwarder_v2.go @@ -192,7 +192,7 @@ func (s *OpenAIGatewayService) forwardOpenAIWSV2( }) if err != nil { var agentDialErr *openAIWSDialError - if s.isAgentIdentityAccount(ctx, account) && errors.As(err, &agentDialErr) && agentDialErr != nil && agentDialErr.StatusCode == http.StatusUnauthorized && agentTaskRecoveryTried != nil && !*agentTaskRecoveryTried { + if s.isAgentIdentityAccount(ctx, account) && errors.As(err, &agentDialErr) && isAgentIdentityTaskInvalidWSDialError(agentDialErr) && agentTaskRecoveryTried != nil && !*agentTaskRecoveryTried { *agentTaskRecoveryTried = true if recoveryErr := s.recoverAgentIdentityTask(ctx, account, account.GetCredential("task_id")); recoveryErr != nil { return nil, fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) diff --git a/backend/internal/service/openai_ws_pool.go b/backend/internal/service/openai_ws_pool.go index be81d611f9..3a02da6fe5 100644 --- a/backend/internal/service/openai_ws_pool.go +++ b/backend/internal/service/openai_ws_pool.go @@ -39,6 +39,7 @@ var ( type openAIWSDialError struct { StatusCode int ResponseHeaders http.Header + ResponseBody []byte Err error } @@ -1540,9 +1541,15 @@ func (p *openAIWSConnPool) dialConn(ctx context.Context, req openAIWSAcquireRequ } conn, status, handshakeHeaders, err := p.clientDialer.Dial(ctx, req.WSURL, headers, req.ProxyURL) if err != nil { + var handshakeErr *openAIWSHandshakeError + var responseBody []byte + if errors.As(err, &handshakeErr) && handshakeErr != nil { + responseBody = append([]byte(nil), handshakeErr.Body...) + } return nil, &openAIWSDialError{ StatusCode: status, ResponseHeaders: cloneHeader(handshakeHeaders), + ResponseBody: responseBody, Err: err, } } diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 01b66c376b..bb097e540b 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -374,7 +374,8 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( if err == nil { break } - if s.isAgentIdentityAccount(ctx, account) && statusCode == http.StatusUnauthorized && !agentTaskRecoveryTried { + var dialErr *openAIWSDialError + if s.isAgentIdentityAccount(ctx, account) && errors.As(err, &dialErr) && isAgentIdentityTaskInvalidWSDialError(dialErr) && !agentTaskRecoveryTried { agentTaskRecoveryTried = true if recoveryErr := s.recoverAgentIdentityTask(ctx, account, account.GetCredential("task_id")); recoveryErr != nil { return fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) @@ -696,9 +697,15 @@ func (s *OpenAIGatewayService) mapOpenAIWSPassthroughDialError( wrappedErr := err var dialErr *openAIWSDialError if !errors.As(err, &dialErr) { + var handshakeErr *openAIWSHandshakeError + var responseBody []byte + if errors.As(err, &handshakeErr) && handshakeErr != nil { + responseBody = append([]byte(nil), handshakeErr.Body...) + } wrappedErr = &openAIWSDialError{ StatusCode: statusCode, ResponseHeaders: cloneHeader(handshakeHeaders), + ResponseBody: responseBody, Err: err, } } From 3fe7b4da78715389a60c07bcf1ba02da044f50cc Mon Sep 17 00:00:00 2001 From: cat Date: Tue, 14 Jul 2026 17:01:53 +0800 Subject: [PATCH 15/83] =?UTF-8?q?fix(openai):=20=E9=97=AD=E5=90=88?= =?UTF-8?q?=E7=9B=B4=E9=80=9A=20WS=20=E6=81=A2=E5=A4=8D=E4=B8=8E=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E8=84=B1=E6=95=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/service/openai_agent_identity.go | 22 +++++++++++++++++++ .../service/openai_agent_identity_test.go | 20 +++++++++++++---- .../service/openai_gateway_upstream_errors.go | 1 + backend/internal/service/openai_images.go | 1 + .../openai_ws_v2_passthrough_adapter.go | 9 ++++++-- 5 files changed, 47 insertions(+), 6 deletions(-) diff --git a/backend/internal/service/openai_agent_identity.go b/backend/internal/service/openai_agent_identity.go index 8383a10e9c..a5ea9b7612 100644 --- a/backend/internal/service/openai_agent_identity.go +++ b/backend/internal/service/openai_agent_identity.go @@ -261,6 +261,25 @@ func ensureAgentIdentityTaskForAccount(ctx context.Context, repo AccountReposito } sharedTaskMu.Lock() defer sharedTaskMu.Unlock() + // Re-read inside the shared lock. Different request paths often receive + // independent repository snapshots; checking only the caller's snapshot + // would allow sequential duplicate registrations after the first writer + // has already persisted a new task. + if repo != nil && credAccount.ID > 0 { + if refreshed, refreshErr := repo.GetByID(ctx, credAccount.ID); refreshErr == nil && refreshed != nil { + if refreshed.IsShadow() { + if resolved, resolveErr := resolveCredentialAccount(ctx, repo, refreshed); resolveErr == nil && resolved != nil { + refreshed = resolved + } + } + if refreshed.IsOpenAIAgentIdentity() { + credAccount = refreshed + if !account.IsShadow() { + account.Credentials = shallowCopyMap(credAccount.Credentials) + } + } + } + } currentTaskID = strings.TrimSpace(credAccount.GetCredential("task_id")) if currentTaskID != "" && (expectedTaskID == "" || currentTaskID != expectedTaskID) { return nil @@ -277,6 +296,9 @@ func ensureAgentIdentityTaskForAccount(ctx context.Context, repo AccountReposito if err := persistAccountCredentials(ctx, repo, credAccount, credentials); err != nil { return err } + if !account.IsShadow() && account != credAccount { + account.Credentials = shallowCopyMap(credAccount.Credentials) + } if pool != nil { pool.ClearAccount(credAccount.ID) } diff --git a/backend/internal/service/openai_agent_identity_test.go b/backend/internal/service/openai_agent_identity_test.go index 6e94f53abe..12f5a7766a 100644 --- a/backend/internal/service/openai_agent_identity_test.go +++ b/backend/internal/service/openai_agent_identity_test.go @@ -163,7 +163,7 @@ func TestEnsureAgentIdentityTaskSharesLockAcrossServicesForSameAccount(t *testin "agent_runtime_id": key.runtimeID, "agent_private_key": privateKey, }} - repo := &agentIdentityCredentialsRepo{} + repo := &agentIdentityCredentialsRepo{account: account} registerCalls := 0 var registerMu sync.Mutex server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -179,10 +179,11 @@ func TestEnsureAgentIdentityTaskSharesLockAcrossServicesForSameAccount(t *testin start := make(chan struct{}) errors := make(chan error, 2) - for range 2 { + requests := []*Account{cloneAgentIdentityTestAccount(account), cloneAgentIdentityTestAccount(account)} + for _, request := range requests { go func() { <-start - errors <- ensureAgentIdentityTaskForAccount(context.Background(), repo, nil, &sync.Mutex{}, account, "") + errors <- ensureAgentIdentityTaskForAccount(context.Background(), repo, nil, &sync.Mutex{}, request, "") }() } close(start) @@ -191,15 +192,26 @@ func TestEnsureAgentIdentityTaskSharesLockAcrossServicesForSameAccount(t *testin registerMu.Lock() defer registerMu.Unlock() require.Equal(t, 1, registerCalls) - require.Equal(t, "task-shared", account.GetCredential("task_id")) + require.Equal(t, "task-shared", repo.account.GetCredential("task_id")) +} + +func cloneAgentIdentityTestAccount(account *Account) *Account { + copy := *account + copy.Credentials = shallowCopyMap(account.Credentials) + return © } type agentIdentityCredentialsRepo struct { AccountRepository credentials map[string]any + account *Account mu sync.Mutex } +func (r *agentIdentityCredentialsRepo) GetByID(_ context.Context, _ int64) (*Account, error) { + return r.account, nil +} + func (r *agentIdentityCredentialsRepo) UpdateCredentials(_ context.Context, _ int64, credentials map[string]any) error { r.mu.Lock() defer r.mu.Unlock() diff --git a/backend/internal/service/openai_gateway_upstream_errors.go b/backend/internal/service/openai_gateway_upstream_errors.go index bc9bf91fef..d8823fe4ed 100644 --- a/backend/internal/service/openai_gateway_upstream_errors.go +++ b/backend/internal/service/openai_gateway_upstream_errors.go @@ -471,6 +471,7 @@ func (s *OpenAIGatewayService) handleCompatErrorResponse( requestedModel ...string, ) (*OpenAIForwardResult, error) { body := s.readUpstreamErrorBody(resp) + body = s.redactAgentIdentitySensitiveBody(context.Background(), account, body) // cyber_policy:兼容路径(Chat Completions / Anthropic)以各自格式回写错误, // 不原样透传 responses 格式的 cyber body(否则对下游格式不合法)。cyber 是上游网络 diff --git a/backend/internal/service/openai_images.go b/backend/internal/service/openai_images.go index b411cb3104..081b5e741b 100644 --- a/backend/internal/service/openai_images.go +++ b/backend/internal/service/openai_images.go @@ -632,6 +632,7 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesAPIKey( if resp.StatusCode >= 400 { respBody := s.readUpstreamErrorBody(resp) _ = resp.Body.Close() + respBody = s.redactAgentIdentitySensitiveBody(upstreamCtx, account, respBody) resp.Body = io.NopCloser(bytes.NewReader(respBody)) upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index bb097e540b..75df7191ac 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -374,8 +374,13 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( if err == nil { break } - var dialErr *openAIWSDialError - if s.isAgentIdentityAccount(ctx, account) && errors.As(err, &dialErr) && isAgentIdentityTaskInvalidWSDialError(dialErr) && !agentTaskRecoveryTried { + var handshakeErr *openAIWSHandshakeError + responseBody := []byte(nil) + if errors.As(err, &handshakeErr) && handshakeErr != nil { + responseBody = handshakeErr.Body + } + dialErr := &openAIWSDialError{StatusCode: statusCode, ResponseBody: responseBody, Err: err} + if s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidWSDialError(dialErr) && !agentTaskRecoveryTried { agentTaskRecoveryTried = true if recoveryErr := s.recoverAgentIdentityTask(ctx, account, account.GetCredential("task_id")); recoveryErr != nil { return fmt.Errorf("agent identity task recovery failed: %w", recoveryErr) From 806bb230532622386e0ffdc4539c0e0a685859d3 Mon Sep 17 00:00:00 2001 From: wucm667 Date: Tue, 14 Jul 2026 17:16:24 +0800 Subject: [PATCH 16/83] fix: add root Codex models alias --- backend/internal/server/routes/gateway.go | 16 +++++++++------- .../server/routes/gateway_codex_models_test.go | 10 ++++++---- backend/internal/web/embed_on.go | 1 + backend/internal/web/embed_test.go | 2 ++ 4 files changed, 18 insertions(+), 11 deletions(-) diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index 45db227e58..f73379981e 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -42,6 +42,13 @@ func RegisterGatewayRoutes( isOpenAIGatewayPlatform := func(c *gin.Context) bool { return getGroupPlatform(c) == service.PlatformOpenAI } + modelsHandler := func(c *gin.Context) { + if isOpenAIGatewayPlatform(c) && c.Query("client_version") != "" { + h.OpenAIGateway.CodexModels(c) + return + } + h.Gateway.Models(c) + } imagesHandler := func(c *gin.Context) { switch getGroupPlatform(c) { case service.PlatformOpenAI: @@ -140,13 +147,7 @@ func RegisterGatewayRoutes( // Codex CLI / Codex app refresh their model picker from the provider's // /models endpoint with a client_version query and expect the ChatGPT // Codex manifest format; other clients keep the OpenAI-style list. - gateway.GET("/models", func(c *gin.Context) { - if isOpenAIGatewayPlatform(c) && c.Query("client_version") != "" { - h.OpenAIGateway.CodexModels(c) - return - } - h.Gateway.Models(c) - }) + gateway.GET("/models", modelsHandler) gateway.GET("/usage", h.Gateway.Usage) // OpenAI Responses API: auto-route based on group platform gateway.POST("/responses", func(c *gin.Context) { @@ -235,6 +236,7 @@ func RegisterGatewayRoutes( r.GET("/responses", bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), requireGroupAnthropic, func(c *gin.Context) { h.OpenAIGateway.ResponsesWebSocket(c) }) + r.GET("/models", bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), requireGroupAnthropic, modelsHandler) codexDirect := r.Group("/backend-api/codex") codexDirect.Use(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), requireGroupAnthropic) { diff --git a/backend/internal/server/routes/gateway_codex_models_test.go b/backend/internal/server/routes/gateway_codex_models_test.go index 74af755919..04a8b8fa67 100644 --- a/backend/internal/server/routes/gateway_codex_models_test.go +++ b/backend/internal/server/routes/gateway_codex_models_test.go @@ -10,13 +10,15 @@ import ( func TestGatewayRoutesCodexModelsManifestPathIsRegistered(t *testing.T) { router := newGatewayRoutesTestRouter() - registered := make(map[string]bool) + registered := make(map[string]string) for _, route := range router.Routes() { if route.Method == http.MethodGet { - registered[route.Path] = true + registered[route.Path] = route.Handler } } - require.True(t, registered["/backend-api/codex/models"], "GET /backend-api/codex/models should be registered") - require.True(t, registered["/v1/models"], "GET /v1/models should be registered") + require.NotEmpty(t, registered["/backend-api/codex/models"], "GET /backend-api/codex/models should be registered") + require.NotEmpty(t, registered["/v1/models"], "GET /v1/models should be registered") + require.NotEmpty(t, registered["/models"], "GET /models should be registered") + require.Equal(t, registered["/v1/models"], registered["/models"], "root alias should use the same platform-aware handler") } diff --git a/backend/internal/web/embed_on.go b/backend/internal/web/embed_on.go index 716fb77e75..6acf0778a5 100644 --- a/backend/internal/web/embed_on.go +++ b/backend/internal/web/embed_on.go @@ -310,6 +310,7 @@ func shouldBypassEmbeddedFrontend(path string) bool { strings.HasPrefix(trimmed, "/antigravity/") || strings.HasPrefix(trimmed, "/setup/") || trimmed == "/health" || + trimmed == "/models" || trimmed == "/responses" || strings.HasPrefix(trimmed, "/responses/") || trimmed == "/alpha/search" || diff --git a/backend/internal/web/embed_test.go b/backend/internal/web/embed_test.go index b27bbfc9dc..c12e07399a 100644 --- a/backend/internal/web/embed_test.go +++ b/backend/internal/web/embed_test.go @@ -451,6 +451,7 @@ func TestFrontendServer_Middleware(t *testing.T) { apiPaths := []string{ "/api/v1/users", + "/models", "/v1/models", "/v1beta/chat", "/backend-api/codex/responses", @@ -692,6 +693,7 @@ func TestServeEmbeddedFrontend(t *testing.T) { apiPaths := []string{ "/api/users", + "/models", "/v1/models", "/v1beta/chat", "/backend-api/codex/responses", From 10aa88aab95f19a48b66142ae2803408fd37a2be Mon Sep 17 00:00:00 2001 From: cat Date: Tue, 14 Jul 2026 17:19:15 +0800 Subject: [PATCH 17/83] =?UTF-8?q?fix(openai):=20=E8=A1=A5=E9=BD=90?= =?UTF-8?q?=E8=BA=AB=E4=BB=BD=E5=A4=B1=E6=95=88=E6=81=A2=E5=A4=8D=E8=B7=AF?= =?UTF-8?q?=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internal/service/account_test_service.go | 31 +++- .../internal/service/openai_agent_identity.go | 36 ++++- .../openai_agent_identity_compat_test.go | 147 +++++++++++++++++- .../openai_gateway_chat_completions.go | 7 + .../service/openai_gateway_messages.go | 7 + .../service/openai_images_responses.go | 8 + .../internal/service/openai_quota_service.go | 132 +++++++++++----- .../service/openai_quota_spark_window_test.go | 58 +++++++ 8 files changed, 378 insertions(+), 48 deletions(-) diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 5a0bc40f40..68a00a5191 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -590,8 +590,11 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account payload := createOpenAITestPayload(testModelID, isOAuth) payloadBytes, _ := json.Marshal(payload) - // Send test_start event - s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + // Send test_start event once. A task-invalid Agent Identity response may + // restart this probe after registering a replacement task. + if !agentIdentityTaskRecoveryWasTried(ctx) { + s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + } req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewReader(payloadBytes)) if err != nil { @@ -656,6 +659,14 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account if resp.StatusCode != http.StatusOK { body, _ := io.ReadAll(resp.Body) body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) + if !agentIdentityTaskRecoveryWasTried(ctx) && credentialAccount.IsOpenAIAgentIdentity() && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, body) { + expectedTaskID := credentialAccount.GetCredential("task_id") + if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, credentialAccount, expectedTaskID); err != nil { + return s.sendErrorAndEnd(c, fmt.Sprintf("Agent Identity task recovery failed: %s", err.Error())) + } + c.Request = c.Request.WithContext(markAgentIdentityTaskRecoveryTried(ctx)) + return s.testOpenAIAccountConnection(c, account, modelID, prompt, mode) + } if resp.StatusCode == http.StatusTooManyRequests { s.reconcileOpenAI429State(ctx, account, resp.Header, body) } @@ -718,7 +729,9 @@ func (s *AccountTestService) testGrokAccountConnection(c *gin.Context, account * return s.sendErrorAndEnd(c, "Failed to create Grok test payload") } - s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + if !agentIdentityTaskRecoveryWasTried(ctx) { + s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + } req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewReader(payloadBytes)) if err != nil { @@ -869,7 +882,9 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account c.Writer.Flush() payloadBytes, _ := json.Marshal(createOpenAICompactProbePayload(testModelID)) - s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + if !agentIdentityTaskRecoveryWasTried(ctx) { + s.sendEvent(c, TestEvent{Type: "test_start", Model: testModelID}) + } req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewReader(payloadBytes)) if err != nil { @@ -926,6 +941,14 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20)) body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) + if !agentIdentityTaskRecoveryWasTried(ctx) && credentialAccount.IsOpenAIAgentIdentity() && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, body) { + expectedTaskID := credentialAccount.GetCredential("task_id") + if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, credentialAccount, expectedTaskID); err != nil { + return s.sendErrorAndEnd(c, fmt.Sprintf("Agent Identity task recovery failed: %s", err.Error())) + } + c.Request = c.Request.WithContext(markAgentIdentityTaskRecoveryTried(ctx)) + return s.testOpenAICompactConnection(c, account, testModelID) + } if s.accountRepo != nil { updates := buildOpenAICompactProbeExtraUpdates(resp, body, nil, time.Now()) diff --git a/backend/internal/service/openai_agent_identity.go b/backend/internal/service/openai_agent_identity.go index a5ea9b7612..0492a2b82e 100644 --- a/backend/internal/service/openai_agent_identity.go +++ b/backend/internal/service/openai_agent_identity.go @@ -317,13 +317,26 @@ func isAgentIdentityTaskInvalidHTTPResponse(statusCode int, body []byte) bool { return false } lower := strings.ToLower(string(body)) + compact := strings.NewReplacer(" ", "", "\t", "", "\r", "", "\n", "").Replace(lower) for _, marker := range []string{ - "invalid task", - "task_id", - "task id", - "task_not_found", - "task_expired", - "unknown task", + `"code":"invalid_task_id"`, + `"code":"task_not_found"`, + `"code":"task_expired"`, + `"error":"invalid_task_id"`, + } { + if strings.Contains(compact, marker) { + return true + } + } + for _, marker := range []string{ + "invalid task_id", + "invalid task id", + "task_id is invalid", + "task id is invalid", + "task not found", + "task expired", + "unknown task_id", + "unknown task id", } { if strings.Contains(lower, marker) { return true @@ -332,6 +345,17 @@ func isAgentIdentityTaskInvalidHTTPResponse(statusCode int, body []byte) bool { return false } +type agentIdentityTaskRecoveryContextKey struct{} + +func markAgentIdentityTaskRecoveryTried(ctx context.Context) context.Context { + return context.WithValue(ctx, agentIdentityTaskRecoveryContextKey{}, true) +} + +func agentIdentityTaskRecoveryWasTried(ctx context.Context) bool { + tried, _ := ctx.Value(agentIdentityTaskRecoveryContextKey{}).(bool) + return tried +} + func isAgentIdentityTaskInvalidWSDialError(err *openAIWSDialError) bool { return err != nil && isAgentIdentityTaskInvalidHTTPResponse(err.StatusCode, err.ResponseBody) } diff --git a/backend/internal/service/openai_agent_identity_compat_test.go b/backend/internal/service/openai_agent_identity_compat_test.go index c034af2bfa..bbfa82481d 100644 --- a/backend/internal/service/openai_agent_identity_compat_test.go +++ b/backend/internal/service/openai_agent_identity_compat_test.go @@ -55,6 +55,52 @@ func TestAccountTestServiceOpenAICompactAgentIdentityUsesFreshAssertion(t *testi require.NotContains(t, upstream.lastReq.Header.Get("Authorization"), privateKey) } +func TestAccountTestServiceOpenAICompactAgentIdentityRecoversInvalidTaskOnce(t *testing.T) { + gin.SetMode(gin.TestMode) + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: 22, + Name: "agent-identity-recovery", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": "task-compact-old", + "chatgpt_account_id": "account-agent-compact-recovery", + }, + } + repo := &accountTestAgentIdentityRepo{account: account} + registerCalls := 0 + registerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + registerCalls++ + _, _ = io.WriteString(w, `{"task_id":"task-compact-new"}`) + })) + defer registerServer.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = registerServer.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"id":"compact-agent","status":"completed"}`))}, + }} + svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/22/test", bytes.NewReader(nil)) + + require.NoError(t, svc.TestAccountConnection(c, account.ID, "gpt-5.4", "", AccountTestModeCompact)) + require.Equal(t, 1, registerCalls) + require.Len(t, upstream.requests, 2) + require.Equal(t, "task-compact-new", account.GetCredential("task_id")) + require.Equal(t, 0, repo.setErrorCalls) +} + func TestOpenAIAgentIdentityPassthroughKeepsSessionAndPromptCacheHeaders(t *testing.T) { gin.SetMode(gin.TestMode) key, privateKey := newTestAgentIdentityKey(t) @@ -225,6 +271,7 @@ func TestOpenAIAgentIdentityTaskInvalidRetriesExactlyOnce(t *testing.T) { {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(successBody))}, }} + require.True(t, isAgentIdentityTaskInvalidHTTPResponse(http.StatusUnauthorized, []byte(`{"error":{"code":"invalid_task_id"}}`))) svc := &OpenAIGatewayService{cfg: &config.Config{}, accountRepo: repo, httpUpstream: upstream} rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) @@ -256,7 +303,7 @@ func TestOpenAIAgentIdentityTaskInvalidRetriesExactlyOnce(t *testing.T) { account.Credentials["task_id"] = "task-old-passthrough" upstream.responses = []*http.Response{ {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, - {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(successBody))}, + {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("data: {\"type\":\"response.completed\",\"response\":{\"usage\":{\"input_tokens\":1,\"output_tokens\":1,\"total_tokens\":2}}}\n\ndata: [DONE]\n\n"))}, } rec3 := httptest.NewRecorder() c3, _ := gin.CreateTestContext(rec3) @@ -267,6 +314,80 @@ func TestOpenAIAgentIdentityTaskInvalidRetriesExactlyOnce(t *testing.T) { require.Len(t, upstream.requests, 6) } +func TestOpenAIAgentIdentityCompatRoutesRecoverInvalidTaskOnce(t *testing.T) { + gin.SetMode(gin.TestMode) + tests := []struct { + name string + path string + body []byte + call func(*OpenAIGatewayService, context.Context, *gin.Context, *Account, []byte) (*OpenAIForwardResult, error) + }{ + { + name: "chat completions", + path: "/v1/chat/completions", + body: []byte(`{"model":"gpt-5.4","stream":false,"messages":[{"role":"user","content":"hi"}]}`), + call: func(s *OpenAIGatewayService, ctx context.Context, c *gin.Context, account *Account, body []byte) (*OpenAIForwardResult, error) { + return s.ForwardAsChatCompletions(ctx, c, account, body, "", "gpt-5.4") + }, + }, + { + name: "anthropic messages", + path: "/v1/messages", + body: []byte(`{"model":"gpt-5.4","stream":false,"max_tokens":32,"messages":[{"role":"user","content":"hi"}]}`), + call: func(s *OpenAIGatewayService, ctx context.Context, c *gin.Context, account *Account, body []byte) (*OpenAIForwardResult, error) { + return s.ForwardAsAnthropic(ctx, c, account, body, "", "gpt-5.4") + }, + }, + } + + for index, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key, privateKey := newTestAgentIdentityKey(t) + account := &Account{ + ID: int64(40 + index), + Name: "agent-identity-compat", + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Status: StatusActive, + Schedulable: true, + Concurrency: 1, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": key.runtimeID, + "agent_private_key": privateKey, + "task_id": "task-compat-old", + "chatgpt_account_id": "account-compat-recovery", + }, + } + repo := &agentIdentityForwardRepo{account: account} + registerCalls := 0 + registerServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + registerCalls++ + _, _ = io.WriteString(w, `{"task_id":"task-compat-new"}`) + })) + defer registerServer.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = registerServer.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + upstream := &httpUpstreamRecorder{responses: []*http.Response{ + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, + }} + svc := &OpenAIGatewayService{cfg: &config.Config{}, accountRepo: repo, httpUpstream: upstream} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, tt.path, bytes.NewReader(tt.body)) + + _, err := tt.call(svc, context.Background(), c, account, tt.body) + require.Error(t, err) + require.Equal(t, 1, registerCalls) + require.Len(t, upstream.requests, 2) + require.Equal(t, "task-compat-new", account.GetCredential("task_id")) + }) + } +} + func decodeAgentAssertionTask(t *testing.T, header string) string { t.Helper() encoded := strings.TrimPrefix(header, "AgentAssertion ") @@ -284,6 +405,30 @@ type agentIdentityForwardRepo struct { account *Account } +type accountTestAgentIdentityRepo struct { + AccountRepository + account *Account + setErrorCalls int +} + +func (r *accountTestAgentIdentityRepo) GetByID(_ context.Context, _ int64) (*Account, error) { + return r.account, nil +} + +func (r *accountTestAgentIdentityRepo) UpdateCredentials(_ context.Context, _ int64, credentials map[string]any) error { + r.account.Credentials = credentials + return nil +} + +func (r *accountTestAgentIdentityRepo) UpdateExtra(_ context.Context, _ int64, _ map[string]any) error { + return nil +} + +func (r *accountTestAgentIdentityRepo) SetError(_ context.Context, _ int64, _ string) error { + r.setErrorCalls++ + return nil +} + func (r *agentIdentityForwardRepo) GetByID(_ context.Context, _ int64) (*Account, error) { return r.account, nil } diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 15c4e47635..5d80292c47 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -267,6 +267,13 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions( // 8. Handle error response with failover if resp.StatusCode >= 400 { respBody, upstreamMsg := s.readOpenAIUpstreamError(resp) + if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { + expectedTaskID := account.GetCredential("task_id") + if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", err) + } + return s.ForwardAsChatCompletions(markAgentIdentityTaskRecoveryTried(ctx), c, account, body, promptCacheKey, defaultMappedModel) + } if account.Type == AccountTypeAPIKey && openai_compat.ResolveResponsesSupport(account.Extra) == openai_compat.ResponsesSupportUnknown && !isResponsesEndpointSupportedByStatus(resp.StatusCode) { diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 219b5e4be4..4d8b14cc28 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -316,6 +316,13 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( // 8. Handle error response with failover if resp.StatusCode >= 400 { respBody, upstreamMsg := s.readOpenAIUpstreamError(resp) + if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { + expectedTaskID := account.GetCredential("task_id") + if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", err) + } + return s.ForwardAsAnthropic(markAgentIdentityTaskRecoveryTried(ctx), c, account, body, promptCacheKey, defaultMappedModel) + } if account.Platform == PlatformGrok { s.updateGrokUsageSnapshot(ctx, account.ID, xai.ParseQuotaHeaders(resp.Header, resp.StatusCode)) s.handleGrokAccountUpstreamError(ctx, account, resp.StatusCode, resp.Header, respBody) diff --git a/backend/internal/service/openai_images_responses.go b/backend/internal/service/openai_images_responses.go index 226cbf8e88..04347d6f90 100644 --- a/backend/internal/service/openai_images_responses.go +++ b/backend/internal/service/openai_images_responses.go @@ -1560,6 +1560,14 @@ func (s *OpenAIGatewayService) forwardOpenAIImagesOAuth( if resp.StatusCode >= 400 { respBody := s.readUpstreamErrorBody(resp) _ = resp.Body.Close() + respBody = s.redactAgentIdentitySensitiveBody(upstreamCtx, account, respBody) + if !agentIdentityTaskRecoveryWasTried(ctx) && s.isAgentIdentityAccount(ctx, account) && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, respBody) { + expectedTaskID := account.GetCredential("task_id") + if err := s.recoverAgentIdentityTask(ctx, account, expectedTaskID); err != nil { + return nil, fmt.Errorf("agent identity task recovery failed: %w", err) + } + return s.forwardOpenAIImagesOAuth(markAgentIdentityTaskRecoveryTried(ctx), c, account, parsed, channelMappedModel) + } resp.Body = io.NopCloser(bytes.NewReader(respBody)) upstreamMsg := strings.TrimSpace(extractUpstreamErrorMessage(respBody)) upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg) diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index cebab0a1d7..c736768b72 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -155,25 +155,36 @@ func (s *OpenAIQuotaService) QueryUsage(ctx context.Context, accountID int64) (* callCtx, cancel := context.WithTimeout(ctx, openaiQuotaUpstreamTimeout) defer cancel() + agentIdentity := s.isAgentIdentityAccount(ctx, accountID) - quotaHeaders, headerErr := s.buildCodexQuotaHeaders(callCtx, accountID, accessToken, chatGPTAccountID, fedRAMP) - if headerErr != nil { - return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "failed to build upstream authentication: %v", headerErr) - } var payload OpenAIQuotaUsage - resp, err := client.R(). - SetContext(callCtx). - SetHeaders(quotaHeaders). - SetSuccessResult(&payload). - Get(chatGPTUsageURL) - if err != nil { - return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_REQUEST_FAILED", "upstream request failed: %v", err) - } - if !resp.IsSuccessState() { - status := resp.StatusCode - body := truncate(s.redactQuotaErrorBody(ctx, accountID, resp.String()), 240) - slog.Warn("openai_quota_query_failed", "account_id", accountID, "status", status, "body", body) - return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) + for recovered := false; ; { + quotaHeaders, headerErr := s.buildCodexQuotaHeaders(callCtx, accountID, accessToken, chatGPTAccountID, fedRAMP) + if headerErr != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "failed to build upstream authentication: %v", headerErr) + } + resp, err := client.R(). + SetContext(callCtx). + SetHeaders(quotaHeaders). + SetSuccessResult(&payload). + Get(chatGPTUsageURL) + if err != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_REQUEST_FAILED", "upstream request failed: %v", err) + } + if !resp.IsSuccessState() { + if agentIdentity && !recovered && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, []byte(resp.String())) { + recovered = true + if err := s.recoverAgentIdentityTask(ctx, accountID); err != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "agent identity task recovery failed: %v", err) + } + continue + } + status := resp.StatusCode + body := truncate(s.redactQuotaErrorBody(ctx, accountID, resp.String()), 240) + slog.Warn("openai_quota_query_failed", "account_id", accountID, "status", status, "body", body) + return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) + } + break } payload.FetchedAt = time.Now().Unix() @@ -249,28 +260,38 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( callCtx, cancel := context.WithTimeout(ctx, openaiQuotaUpstreamTimeout) defer cancel() - - headers, headerErr := s.buildCodexQuotaHeaders(callCtx, accountID, accessToken, chatGPTAccountID, fedRAMP) - if headerErr != nil { - return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "failed to build upstream authentication: %v", headerErr) - } - headers["content-type"] = "application/json" + agentIdentity := s.isAgentIdentityAccount(ctx, accountID) var payload OpenAIQuotaResetResult - resp, err := client.R(). - SetContext(callCtx). - SetHeaders(headers). - SetBody(map[string]string{"redeem_request_id": redeemRequestID}). - SetSuccessResult(&payload). - Post(chatGPTRateLimitResetURL) - if err != nil { - return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_RESET_REQUEST_FAILED", "upstream request failed: %v", err) - } - if !resp.IsSuccessState() { - status := resp.StatusCode - body := truncate(s.redactQuotaErrorBody(callCtx, accountID, resp.String()), 240) - slog.Warn("openai_quota_reset_failed", "account_id", accountID, "status", status, "body", body) - return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_RESET_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) + for recovered := false; ; { + headers, headerErr := s.buildCodexQuotaHeaders(callCtx, accountID, accessToken, chatGPTAccountID, fedRAMP) + if headerErr != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "failed to build upstream authentication: %v", headerErr) + } + headers["content-type"] = "application/json" + resp, err := client.R(). + SetContext(callCtx). + SetHeaders(headers). + SetBody(map[string]string{"redeem_request_id": redeemRequestID}). + SetSuccessResult(&payload). + Post(chatGPTRateLimitResetURL) + if err != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_RESET_REQUEST_FAILED", "upstream request failed: %v", err) + } + if !resp.IsSuccessState() { + if agentIdentity && !recovered && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, []byte(resp.String())) { + recovered = true + if err := s.recoverAgentIdentityTask(ctx, accountID); err != nil { + return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "agent identity task recovery failed: %v", err) + } + continue + } + status := resp.StatusCode + body := truncate(s.redactQuotaErrorBody(callCtx, accountID, resp.String()), 240) + slog.Warn("openai_quota_reset_failed", "account_id", accountID, "status", status, "body", body) + return nil, infraerrors.Newf(mapUpstreamStatus(status), "OPENAI_QUOTA_RESET_UPSTREAM_ERROR", "upstream returned %d: %s", status, body) + } + break } slog.Info("openai_quota_reset_success", @@ -356,6 +377,43 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID return accessToken, chatGPTAccountID, proxyURL, fedRAMP, nil } +func (s *OpenAIQuotaService) recoverAgentIdentityTask(ctx context.Context, accountID int64) error { + if s == nil || s.accountRepo == nil { + return fmt.Errorf("account repository is unavailable") + } + account, err := s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil { + return fmt.Errorf("account is unavailable") + } + if account.IsShadow() { + account, err = resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil || account == nil { + return fmt.Errorf("credential account is unavailable") + } + } + if !account.IsOpenAIAgentIdentity() { + return nil + } + return ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, account, account.GetCredential("task_id")) +} + +func (s *OpenAIQuotaService) isAgentIdentityAccount(ctx context.Context, accountID int64) bool { + if s == nil || s.accountRepo == nil { + return false + } + account, err := s.accountRepo.GetByID(ctx, accountID) + if err != nil || account == nil { + return false + } + if account.IsShadow() { + account, err = resolveCredentialAccount(ctx, s.accountRepo, account) + if err != nil || account == nil { + return false + } + } + return account.IsOpenAIAgentIdentity() +} + func (s *OpenAIQuotaService) buildCodexQuotaHeaders(ctx context.Context, accountID int64, accessToken, chatGPTAccountID string, fedRAMP bool) (map[string]string, error) { headers := buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP) if s == nil || s.accountRepo == nil { diff --git a/backend/internal/service/openai_quota_spark_window_test.go b/backend/internal/service/openai_quota_spark_window_test.go index d2b18af05b..99bfe15ca1 100644 --- a/backend/internal/service/openai_quota_spark_window_test.go +++ b/backend/internal/service/openai_quota_spark_window_test.go @@ -38,6 +38,15 @@ func (r *stubQuotaAccountRepo) GetByID(_ context.Context, id int64) (*Account, e return acc, nil } +func (r *stubQuotaAccountRepo) UpdateCredentials(_ context.Context, id int64, credentials map[string]any) error { + acc, ok := r.accounts[id] + if !ok { + return fmt.Errorf("account %d not found", id) + } + acc.Credentials = credentials + return nil +} + // stubQuotaTokenCache 实现 OpenAITokenCache,返回预设静态 token。 type stubQuotaTokenCache struct { tokens map[string]string @@ -257,6 +266,55 @@ func TestQueryUsageAgentIdentityUsesAssertionWithoutOAuthToken(t *testing.T) { require.Equal(t, "true", fedrampHeader) } +func TestQueryUsageAgentIdentityRecoversInvalidTaskOnce(t *testing.T) { + _, privateKey, err := ed25519.GenerateKey(rand.Reader) + require.NoError(t, err) + der, err := x509.MarshalPKCS8PrivateKey(privateKey) + require.NoError(t, err) + account := &Account{ + ID: 301, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + "agent_runtime_id": "runtime-quota-recovery", + "agent_private_key": base64.StdEncoding.EncodeToString(der), + "task_id": "task-quota-old", + "chatgpt_account_id": "account-quota-recovery", + }, + } + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + usageCalls := 0 + registerCalls := 0 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("content-type", "application/json") + if strings.Contains(r.URL.Path, "/task/register") { + registerCalls++ + _, _ = w.Write([]byte(`{"task_id":"task-quota-new"}`)) + return + } + usageCalls++ + if usageCalls == 1 { + w.WriteHeader(http.StatusUnauthorized) + _, _ = w.Write([]byte(`{"error":{"code":"invalid_task_id"}}`)) + return + } + _, _ = w.Write([]byte(`{"plan_type":"pro","rate_limit":{"allowed":true}}`)) + })) + defer srv.Close() + oldBase := openAIAgentIdentityAuthAPIBaseURL + openAIAgentIdentityAuthAPIBaseURL = srv.URL + t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + + svc := NewOpenAIQuotaService(repo, nil, nil, newQuotaRedirectingFactory(srv)) + usage, err := svc.QueryUsage(context.Background(), account.ID) + require.NoError(t, err) + require.NotNil(t, usage) + require.Equal(t, 2, usageCalls) + require.Equal(t, 1, registerCalls) + require.Equal(t, "task-quota-new", account.GetCredential("task_id")) +} + func TestParseOpenAIRateLimitResetCreditDetails_CompatibleContainers(t *testing.T) { tests := []struct { name string From 8b37ba8828d77ada5d05e90cac665d9ac5532d60 Mon Sep 17 00:00:00 2001 From: Lyonle <214648221+lyon-le@users.noreply.github.com> Date: Tue, 14 Jul 2026 16:34:20 +0800 Subject: [PATCH 18/83] perf(risk): optimize keyword moderation hot path --- .../internal/service/content_moderation.go | 184 ++++++- .../content_moderation_keyword_matcher.go | 222 +++++++++ ...content_moderation_keyword_matcher_test.go | 59 +++ .../content_moderation_runtime_cache_test.go | 451 ++++++++++++++++++ 4 files changed, 900 insertions(+), 16 deletions(-) create mode 100644 backend/internal/service/content_moderation_keyword_matcher.go create mode 100644 backend/internal/service/content_moderation_keyword_matcher_test.go create mode 100644 backend/internal/service/content_moderation_runtime_cache_test.go diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go index f633c8ad17..8102f34a90 100644 --- a/backend/internal/service/content_moderation.go +++ b/backend/internal/service/content_moderation.go @@ -92,6 +92,9 @@ const ( contentModerationCleanupInterval = 24 * time.Hour contentModerationCleanupTimeout = 30 * time.Minute contentModerationCleanupDelay = 5 * time.Minute + + contentModerationRuntimeCacheTTL = time.Second + contentModerationRuntimeRefreshTimeout = 5 * time.Second ) var contentModerationCategoryOrder = []string{ @@ -512,10 +515,22 @@ type ContentModerationService struct { lastCleanupUnix atomic.Int64 lastCleanupDeletedHit atomic.Int64 lastCleanupDeletedNonHit atomic.Int64 + runtimeSnapshot atomic.Pointer[contentModerationRuntimeSnapshot] + runtimeRefreshMu sync.Mutex + runtimeCacheTTL time.Duration + runtimeRefreshRetryAt atomic.Int64 keyHealthMu sync.Mutex keyHealth map[string]*contentModerationKeyHealth } +type contentModerationRuntimeSnapshot struct { + riskControlEnabled bool + config *ContentModerationConfig + keywordMatcher *contentModerationKeywordMatcher + configDigest [sha256.Size]byte + loadedAt time.Time +} + type contentModerationTask struct { input ContentModerationCheckInput content ContentModerationInput @@ -700,6 +715,7 @@ func (s *ContentModerationService) UpdateConfig(ctx context.Context, input Updat if err := s.settingRepo.Set(ctx, SettingKeyContentModerationConfig, string(raw)); err != nil { return nil, fmt.Errorf("save content moderation config: %w", err) } + s.replaceRuntimeConfig(cfg, raw) return s.configView(cfg), nil } @@ -776,16 +792,7 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer "protocol", input.Protocol) return allow, nil } - if !s.isRiskControlEnabled(ctx) { - slog.Info("content_moderation.skip_feature_disabled", - "user_id", input.UserID, - "api_key_id", input.APIKeyID, - "group_id", contentModerationLogGroupID(input.GroupID), - "endpoint", input.Endpoint, - "protocol", input.Protocol) - return allow, nil - } - cfg, err := s.loadConfig(ctx) + runtimeSnapshot, err := s.loadRuntimeSnapshot(ctx) if err != nil { slog.Warn("content_moderation.skip_config_load_failed", "user_id", input.UserID, @@ -796,6 +803,16 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer "error", err) return allow, nil } + if !runtimeSnapshot.riskControlEnabled { + slog.Info("content_moderation.skip_feature_disabled", + "user_id", input.UserID, + "api_key_id", input.APIKeyID, + "group_id", contentModerationLogGroupID(input.GroupID), + "endpoint", input.Endpoint, + "protocol", input.Protocol) + return allow, nil + } + cfg := runtimeSnapshot.config inGroupScope := cfg.includesGroup(input.GroupID) inModelScope := cfg.includesModel(input.Model) slog.Info("content_moderation.config_loaded", @@ -885,7 +902,7 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer hashText := content.Hash() if cfg.Mode == ContentModerationModePreBlock { if cfg.KeywordBlockingMode != ContentModerationKeywordModeAPIOnly && len(cfg.BlockedKeywords) > 0 { - if keyword, hit := matchBlockedKeyword(content.Text, cfg.BlockedKeywords); hit { + if keyword, hit := runtimeSnapshot.matchBlockedKeyword(content.Text); hit { s.recordPreBlockSyncMetric(0, ContentModerationActionKeywordBlock) slog.Info("content_moderation.keyword_block", "user_id", input.UserID, @@ -1178,12 +1195,13 @@ func (s *ContentModerationService) enqueueRecord(input ContentModerationCheckInp func (s *ContentModerationService) worker(id int) { for { ctx, cancel := context.WithTimeout(context.Background(), maxContentModerationTimeoutMS*time.Millisecond+10*time.Second) - cfg, err := s.loadConfig(ctx) - if err != nil || id >= cfg.WorkerCount { + runtimeSnapshot, err := s.loadRuntimeSnapshot(ctx) + if err != nil || runtimeSnapshot == nil || runtimeSnapshot.config == nil || id >= runtimeSnapshot.config.WorkerCount { cancel() time.Sleep(time.Second) continue } + cfg := runtimeSnapshot.config task, ok := s.dequeueAsyncTask(ctx, time.Second) if !ok { cancel() @@ -1438,15 +1456,18 @@ func (s *ContentModerationService) runCleanupOnce() { } func (s *ContentModerationService) loadConfig(ctx context.Context) (*ContentModerationConfig, error) { - cfg := defaultContentModerationConfig() raw, err := s.settingRepo.GetValue(ctx, SettingKeyContentModerationConfig) if err != nil { if errors.Is(err, ErrSettingNotFound) { - cfg.normalize() - return cfg, nil + return parseContentModerationConfig("") } return nil, fmt.Errorf("get content moderation config: %w", err) } + return parseContentModerationConfig(raw) +} + +func parseContentModerationConfig(raw string) (*ContentModerationConfig, error) { + cfg := defaultContentModerationConfig() if strings.TrimSpace(raw) == "" { cfg.normalize() return cfg, nil @@ -1458,6 +1479,137 @@ func (s *ContentModerationService) loadConfig(ctx context.Context) (*ContentMode return cfg, nil } +func (s *ContentModerationService) loadRuntimeSnapshot(ctx context.Context) (*contentModerationRuntimeSnapshot, error) { + if s == nil || s.settingRepo == nil { + return nil, errors.New("content moderation setting repository unavailable") + } + now := time.Now() + if snapshot := s.runtimeSnapshot.Load(); snapshot != nil { + if now.Sub(snapshot.loadedAt) < s.runtimeSnapshotTTL() { + return snapshot, nil + } + s.triggerRuntimeSnapshotRefresh() + return snapshot, nil + } + + s.runtimeRefreshMu.Lock() + defer s.runtimeRefreshMu.Unlock() + if snapshot := s.runtimeSnapshot.Load(); snapshot != nil { + return snapshot, nil + } + return s.refreshRuntimeSnapshot(ctx) +} + +func (s *ContentModerationService) runtimeSnapshotTTL() time.Duration { + if s != nil && s.runtimeCacheTTL > 0 { + return s.runtimeCacheTTL + } + return contentModerationRuntimeCacheTTL +} + +func (s *ContentModerationService) triggerRuntimeSnapshotRefresh() { + if s == nil || s.runtimeRefreshDeferred() || !s.runtimeRefreshMu.TryLock() { + return + } + if s.runtimeRefreshDeferred() { + s.runtimeRefreshMu.Unlock() + return + } + go func() { + defer s.runtimeRefreshMu.Unlock() + ctx, cancel := context.WithTimeout(context.Background(), contentModerationRuntimeRefreshTimeout) + defer cancel() + if _, err := s.refreshRuntimeSnapshot(ctx); err != nil { + s.runtimeRefreshRetryAt.Store(time.Now().Add(s.runtimeSnapshotTTL()).UnixNano()) + slog.Warn("content_moderation.runtime_snapshot_refresh_failed", "error", err) + } + }() +} + +func (s *ContentModerationService) runtimeRefreshDeferred() bool { + if s == nil { + return false + } + return time.Now().UnixNano() < s.runtimeRefreshRetryAt.Load() +} + +func (s *ContentModerationService) refreshRuntimeSnapshot(ctx context.Context) (*contentModerationRuntimeSnapshot, error) { + values, err := s.settingRepo.GetMultiple(ctx, []string{ + SettingKeyRiskControlEnabled, + SettingKeyContentModerationConfig, + }) + if err != nil { + return nil, fmt.Errorf("get content moderation runtime settings: %w", err) + } + rawConfig := values[SettingKeyContentModerationConfig] + configDigest := sha256.Sum256([]byte(rawConfig)) + if current := s.runtimeSnapshot.Load(); current != nil && current.configDigest == configDigest { + snapshot := &contentModerationRuntimeSnapshot{ + riskControlEnabled: values[SettingKeyRiskControlEnabled] == "true", + config: current.config, + keywordMatcher: current.keywordMatcher, + configDigest: configDigest, + loadedAt: time.Now(), + } + s.runtimeSnapshot.Store(snapshot) + s.runtimeRefreshRetryAt.Store(0) + return snapshot, nil + } + cfg, err := parseContentModerationConfig(rawConfig) + if err != nil { + return nil, err + } + snapshot := &contentModerationRuntimeSnapshot{ + riskControlEnabled: values[SettingKeyRiskControlEnabled] == "true", + config: cfg, + keywordMatcher: newContentModerationKeywordMatcher(cfg.BlockedKeywords), + configDigest: configDigest, + loadedAt: time.Now(), + } + s.runtimeSnapshot.Store(snapshot) + s.runtimeRefreshRetryAt.Store(0) + return snapshot, nil +} + +func (s *ContentModerationService) replaceRuntimeConfig(cfg *ContentModerationConfig, raw []byte) { + if s == nil || cfg == nil { + return + } + s.runtimeRefreshMu.Lock() + hasSnapshot := s.runtimeSnapshot.Load() != nil + s.runtimeRefreshMu.Unlock() + if !hasSnapshot { + return + } + config := cloneContentModerationConfig(cfg) + keywordMatcher := newContentModerationKeywordMatcher(cfg.BlockedKeywords) + configDigest := sha256.Sum256(raw) + + s.runtimeRefreshMu.Lock() + defer s.runtimeRefreshMu.Unlock() + current := s.runtimeSnapshot.Load() + if current == nil { + return + } + s.runtimeSnapshot.Store(&contentModerationRuntimeSnapshot{ + riskControlEnabled: current.riskControlEnabled, + config: config, + keywordMatcher: keywordMatcher, + configDigest: configDigest, + loadedAt: time.Now(), + }) +} + +func (s *contentModerationRuntimeSnapshot) matchBlockedKeyword(text string) (string, bool) { + if s == nil || s.config == nil { + return "", false + } + if s.keywordMatcher != nil { + return s.keywordMatcher.Match(text) + } + return matchBlockedKeyword(text, s.config.BlockedKeywords) +} + func (s *ContentModerationService) isRiskControlEnabled(ctx context.Context) bool { raw, err := s.settingRepo.GetValue(ctx, SettingKeyRiskControlEnabled) if err != nil { diff --git a/backend/internal/service/content_moderation_keyword_matcher.go b/backend/internal/service/content_moderation_keyword_matcher.go new file mode 100644 index 0000000000..4628d3b70a --- /dev/null +++ b/backend/internal/service/content_moderation_keyword_matcher.go @@ -0,0 +1,222 @@ +package service + +import ( + "strings" +) + +type contentModerationKeywordMatcher struct { + nodes []contentModerationKeywordNode + edges []contentModerationKeywordEdge + rootTransitions [256]int32 + keywords []string +} + +type contentModerationKeywordNode struct { + failure int32 + bestKeyword int32 + edgeStart uint32 + edgeCount uint16 +} + +type contentModerationKeywordEdge struct { + target int32 + label byte +} + +type contentModerationKeywordBuildEdge struct { + target int32 + nextSibling int32 + label byte +} + +func newContentModerationKeywordMatcher(keywords []string) *contentModerationKeywordMatcher { + if len(keywords) == 0 { + return nil + } + + buildNodes := []contentModerationKeywordNode{newContentModerationKeywordNode()} + buildEdges := make([]contentModerationKeywordBuildEdge, 0) + originalKeywords := append([]string(nil), keywords...) + + for keywordIndex, keyword := range keywords { + if keyword == "" { + continue + } + state := int32(0) + for _, label := range []byte(strings.ToLower(keyword)) { + next := contentModerationKeywordBuildTransition(buildNodes, buildEdges, state, label) + if next < 0 { + next = int32(len(buildNodes)) + buildNodes = append(buildNodes, newContentModerationKeywordNode()) + buildEdges = append(buildEdges, contentModerationKeywordBuildEdge{ + target: next, + nextSibling: contentModerationKeywordBuildFirstEdge(buildNodes[state]), + label: label, + }) + buildNodes[state].edgeStart = uint32(len(buildEdges)) + } + state = next + } + if current := buildNodes[state].bestKeyword; current < 0 || int32(keywordIndex) < current { + buildNodes[state].bestKeyword = int32(keywordIndex) + } + } + + if len(buildNodes) == 1 { + return nil + } + + queue := make([]int32, 0, len(buildNodes)-1) + var rootTransitions [256]int32 + for edgeIndex := contentModerationKeywordBuildFirstEdge(buildNodes[0]); edgeIndex >= 0; edgeIndex = buildEdges[edgeIndex].nextSibling { + edge := buildEdges[edgeIndex] + rootTransitions[edge.label] = edge.target + queue = append(queue, edge.target) + } + + for queueIndex := 0; queueIndex < len(queue); queueIndex++ { + state := queue[queueIndex] + for edgeIndex := contentModerationKeywordBuildFirstEdge(buildNodes[state]); edgeIndex >= 0; edgeIndex = buildEdges[edgeIndex].nextSibling { + edge := buildEdges[edgeIndex] + failure := buildNodes[state].failure + fallback := contentModerationKeywordBuildTransition(buildNodes, buildEdges, failure, edge.label) + for fallback < 0 && failure != 0 { + failure = buildNodes[failure].failure + fallback = contentModerationKeywordBuildTransition(buildNodes, buildEdges, failure, edge.label) + } + if fallback >= 0 { + buildNodes[edge.target].failure = fallback + } + buildNodes[edge.target].bestKeyword = minKeywordIndex( + buildNodes[edge.target].bestKeyword, + buildNodes[buildNodes[edge.target].failure].bestKeyword, + ) + queue = append(queue, edge.target) + } + } + + edges := make([]contentModerationKeywordEdge, 0, len(buildEdges)) + var outgoing [256]contentModerationKeywordEdge + for nodeIndex := range buildNodes { + count := 0 + for edgeIndex := contentModerationKeywordBuildFirstEdge(buildNodes[nodeIndex]); edgeIndex >= 0; edgeIndex = buildEdges[edgeIndex].nextSibling { + edge := buildEdges[edgeIndex] + outgoing[count] = contentModerationKeywordEdge{target: edge.target, label: edge.label} + count++ + } + for index := 1; index < count; index++ { + current := outgoing[index] + insertAt := index + for insertAt > 0 && current.label < outgoing[insertAt-1].label { + outgoing[insertAt] = outgoing[insertAt-1] + insertAt-- + } + outgoing[insertAt] = current + } + buildNodes[nodeIndex].edgeStart = uint32(len(edges)) + buildNodes[nodeIndex].edgeCount = uint16(count) + edges = append(edges, outgoing[:count]...) + } + + return &contentModerationKeywordMatcher{ + nodes: buildNodes, + edges: edges, + rootTransitions: rootTransitions, + keywords: originalKeywords, + } +} + +func newContentModerationKeywordNode() contentModerationKeywordNode { + return contentModerationKeywordNode{bestKeyword: -1} +} + +func contentModerationKeywordBuildFirstEdge(node contentModerationKeywordNode) int32 { + if node.edgeStart == 0 { + return -1 + } + return int32(node.edgeStart - 1) +} + +func contentModerationKeywordBuildTransition( + nodes []contentModerationKeywordNode, + edges []contentModerationKeywordBuildEdge, + state int32, + label byte, +) int32 { + if state < 0 || int(state) >= len(nodes) { + return -1 + } + for edgeIndex := contentModerationKeywordBuildFirstEdge(nodes[state]); edgeIndex >= 0; edgeIndex = edges[edgeIndex].nextSibling { + if edges[edgeIndex].label == label { + return edges[edgeIndex].target + } + } + return -1 +} + +func minKeywordIndex(left, right int32) int32 { + if left < 0 { + return right + } + if right < 0 || left < right { + return left + } + return right +} + +func (m *contentModerationKeywordMatcher) Match(text string) (string, bool) { + if m == nil || text == "" || len(m.nodes) == 0 || len(m.keywords) == 0 { + return "", false + } + lower := strings.ToLower(text) + state := int32(0) + bestKeyword := int32(-1) + for index := 0; index < len(lower); index++ { + label := lower[index] + for { + next := m.next(state, label) + if next != 0 { + state = next + break + } + if state == 0 { + break + } + state = m.nodes[state].failure + } + bestKeyword = minKeywordIndex(bestKeyword, m.nodes[state].bestKeyword) + if bestKeyword == 0 { + return m.keywords[0], true + } + } + if bestKeyword < 0 || int(bestKeyword) >= len(m.keywords) { + return "", false + } + return m.keywords[bestKeyword], true +} + +func (m *contentModerationKeywordMatcher) next(state int32, label byte) int32 { + if state == 0 { + return m.rootTransitions[label] + } + if state < 0 || int(state) >= len(m.nodes) { + return 0 + } + node := m.nodes[state] + left := int(node.edgeStart) + right := left + int(node.edgeCount) + for left < right { + middle := left + (right-left)/2 + edge := m.edges[middle] + if edge.label < label { + left = middle + 1 + continue + } + right = middle + } + end := int(node.edgeStart) + int(node.edgeCount) + if left < end && m.edges[left].label == label { + return m.edges[left].target + } + return 0 +} diff --git a/backend/internal/service/content_moderation_keyword_matcher_test.go b/backend/internal/service/content_moderation_keyword_matcher_test.go new file mode 100644 index 0000000000..4be70dca3e --- /dev/null +++ b/backend/internal/service/content_moderation_keyword_matcher_test.go @@ -0,0 +1,59 @@ +package service + +import ( + "math/rand" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestContentModerationKeywordMatcherMatchesLegacyBehavior(t *testing.T) { + tests := []struct { + name string + text string + keywords []string + }{ + {name: "miss", text: "clean prompt", keywords: []string{"blocked", "secret"}}, + {name: "case insensitive", text: "contains SECRET value", keywords: []string{"secret"}}, + {name: "configured order wins", text: "early appears before later", keywords: []string{"later", "early"}}, + {name: "overlap uses configured order", text: "abc", keywords: []string{"bc", "abc"}}, + {name: "unicode", text: "这里包含敏感词和世界", keywords: []string{"世界", "敏感词"}}, + {name: "duplicates", text: "duplicate", keywords: []string{"duplicate", "DUPLICATE"}}, + {name: "empty entries", text: "blocked", keywords: []string{"", "blocked"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + wantKeyword, wantHit := matchBlockedKeyword(tt.text, tt.keywords) + gotKeyword, gotHit := newContentModerationKeywordMatcher(tt.keywords).Match(tt.text) + require.Equal(t, wantHit, gotHit) + require.Equal(t, wantKeyword, gotKeyword) + }) + } +} + +func TestContentModerationKeywordMatcherRandomizedParity(t *testing.T) { + rng := rand.New(rand.NewSource(20260714)) + const alphabet = "abcXYZ" + for iteration := 0; iteration < 1000; iteration++ { + keywords := make([]string, 1+rng.Intn(30)) + for index := range keywords { + length := 1 + rng.Intn(8) + var value strings.Builder + for range length { + _ = value.WriteByte(alphabet[rng.Intn(len(alphabet))]) + } + keywords[index] = value.String() + } + var text strings.Builder + for range 20 + rng.Intn(100) { + _ = text.WriteByte(alphabet[rng.Intn(len(alphabet))]) + } + + wantKeyword, wantHit := matchBlockedKeyword(text.String(), keywords) + gotKeyword, gotHit := newContentModerationKeywordMatcher(keywords).Match(text.String()) + require.Equal(t, wantHit, gotHit, "iteration %d", iteration) + require.Equal(t, wantKeyword, gotKeyword, "iteration %d", iteration) + } +} diff --git a/backend/internal/service/content_moderation_runtime_cache_test.go b/backend/internal/service/content_moderation_runtime_cache_test.go new file mode 100644 index 0000000000..2b34d1fa57 --- /dev/null +++ b/backend/internal/service/content_moderation_runtime_cache_test.go @@ -0,0 +1,451 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +type contentModerationRuntimeSettingRepo struct { + mu sync.Mutex + values map[string]string + getValueCalls int + getMultipleCalls int + getMultipleErr error + getMultipleStart chan<- struct{} + getMultipleWait <-chan struct{} +} + +func (r *contentModerationRuntimeSettingRepo) Get(_ context.Context, key string) (*Setting, error) { + r.mu.Lock() + defer r.mu.Unlock() + value, ok := r.values[key] + if !ok { + return nil, ErrSettingNotFound + } + return &Setting{Key: key, Value: value}, nil +} + +func (r *contentModerationRuntimeSettingRepo) GetValue(_ context.Context, key string) (string, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.getValueCalls++ + value, ok := r.values[key] + if !ok { + return "", ErrSettingNotFound + } + return value, nil +} + +func (r *contentModerationRuntimeSettingRepo) Set(_ context.Context, key, value string) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.values == nil { + r.values = make(map[string]string) + } + r.values[key] = value + return nil +} + +func (r *contentModerationRuntimeSettingRepo) GetMultiple(_ context.Context, keys []string) (map[string]string, error) { + r.mu.Lock() + r.getMultipleCalls++ + if err := r.getMultipleErr; err != nil { + r.mu.Unlock() + return nil, err + } + out := make(map[string]string, len(keys)) + for _, key := range keys { + if value, ok := r.values[key]; ok { + out[key] = value + } + } + start := r.getMultipleStart + wait := r.getMultipleWait + r.getMultipleStart = nil + r.getMultipleWait = nil + r.mu.Unlock() + if start != nil { + start <- struct{}{} + } + if wait != nil { + <-wait + } + return out, nil +} + +func (r *contentModerationRuntimeSettingRepo) SetMultiple(_ context.Context, values map[string]string) error { + r.mu.Lock() + defer r.mu.Unlock() + if r.values == nil { + r.values = make(map[string]string) + } + for key, value := range values { + r.values[key] = value + } + return nil +} + +func (r *contentModerationRuntimeSettingRepo) GetAll(_ context.Context) (map[string]string, error) { + r.mu.Lock() + defer r.mu.Unlock() + out := make(map[string]string, len(r.values)) + for key, value := range r.values { + out[key] = value + } + return out, nil +} + +func (r *contentModerationRuntimeSettingRepo) Delete(_ context.Context, key string) error { + r.mu.Lock() + defer r.mu.Unlock() + delete(r.values, key) + return nil +} + +func (r *contentModerationRuntimeSettingRepo) calls() (getValue, getMultiple int) { + r.mu.Lock() + defer r.mu.Unlock() + return r.getValueCalls, r.getMultipleCalls +} + +func (r *contentModerationRuntimeSettingRepo) failMultiple(err error) { + r.mu.Lock() + defer r.mu.Unlock() + r.getMultipleErr = err +} + +func (r *contentModerationRuntimeSettingRepo) blockNextMultiple(start chan<- struct{}, wait <-chan struct{}) { + r.mu.Lock() + defer r.mu.Unlock() + r.getMultipleStart = start + r.getMultipleWait = wait +} + +func runtimeCacheTestConfig(t *testing.T, keywords ...string) string { + t.Helper() + cfg := defaultContentModerationConfig() + cfg.Enabled = true + cfg.Mode = ContentModerationModePreBlock + cfg.KeywordBlockingMode = ContentModerationKeywordModeKeywordOnly + cfg.BlockedKeywords = keywords + raw, err := json.Marshal(cfg) + require.NoError(t, err) + return string(raw) +} + +func runtimeCacheTestService(repo *contentModerationRuntimeSettingRepo, ttl time.Duration) *ContentModerationService { + return &ContentModerationService{ + settingRepo: repo, + repo: &contentModerationTestRepo{}, + runtimeCacheTTL: ttl, + } +} + +func runtimeCacheTestInput(text string) ContentModerationCheckInput { + return ContentModerationCheckInput{ + Protocol: ContentModerationProtocolOpenAIChat, + Model: "risk-cache-test", + Body: []byte(`{"messages":[{"role":"user","content":"` + text + `"}]}`), + } +} + +func TestContentModerationRuntimeSnapshotCachesSettings(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), + }} + svc := runtimeCacheTestService(repo, time.Hour) + + for range 20 { + decision, err := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt")) + require.NoError(t, err) + require.True(t, decision.Allowed) + } + + getValue, getMultiple := repo.calls() + require.Zero(t, getValue) + require.Equal(t, 1, getMultiple) +} + +func TestContentModerationRuntimeSnapshotUpdateConfigIsImmediate(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "old-keyword"), + }} + svc := runtimeCacheTestService(repo, time.Hour) + + decision, err := svc.Check(context.Background(), runtimeCacheTestInput("new-keyword")) + require.NoError(t, err) + require.True(t, decision.Allowed) + + keywords := []string{"new-keyword"} + _, err = svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{ + BlockedKeywords: &keywords, + }) + require.NoError(t, err) + + decision, err = svc.Check(context.Background(), runtimeCacheTestInput("new-keyword")) + require.NoError(t, err) + require.True(t, decision.Blocked) + + _, getMultiple := repo.calls() + require.Equal(t, 1, getMultiple) +} + +func TestContentModerationRuntimeSnapshotUpdateWinsOverInitialLoad(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "old-keyword"), + }} + svc := runtimeCacheTestService(repo, time.Hour) + + refreshStarted := make(chan struct{}, 1) + releaseRefresh := make(chan struct{}) + released := false + defer func() { + if !released { + close(releaseRefresh) + } + }() + repo.blockNextMultiple(refreshStarted, releaseRefresh) + + initialCheckDone := make(chan error, 1) + go func() { + decision, err := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt")) + if err == nil && (decision == nil || !decision.Allowed) { + err = errors.New("unexpected initial moderation decision") + } + initialCheckDone <- err + }() + require.Eventually(t, func() bool { + select { + case <-refreshStarted: + return true + default: + return false + } + }, time.Second, time.Millisecond) + + updateDone := make(chan error, 1) + go func() { + keywords := []string{"new-keyword"} + _, updateErr := svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{ + BlockedKeywords: &keywords, + }) + updateDone <- updateErr + }() + select { + case updateErr := <-updateDone: + require.NoError(t, updateErr) + t.Fatal("configuration update completed before the initial load released its lock") + case <-time.After(10 * time.Millisecond): + } + + close(releaseRefresh) + released = true + require.NoError(t, <-initialCheckDone) + require.NoError(t, <-updateDone) + + decision, err := svc.Check(context.Background(), runtimeCacheTestInput("new-keyword")) + require.NoError(t, err) + require.True(t, decision.Blocked) + decision, err = svc.Check(context.Background(), runtimeCacheTestInput("old-keyword")) + require.NoError(t, err) + require.True(t, decision.Allowed) +} + +func TestContentModerationRuntimeSnapshotRefreshFailureKeepsStaleConfig(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), + }} + svc := runtimeCacheTestService(repo, time.Nanosecond) + input := runtimeCacheTestInput("blocked") + + decision, err := svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + + repo.failMultiple(errors.New("database unavailable")) + decision, err = svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + require.Eventually(t, func() bool { + _, calls := repo.calls() + return calls >= 2 + }, time.Second, time.Millisecond) +} + +func TestContentModerationRuntimeSnapshotRefreshFailureBacksOff(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), + }} + svc := runtimeCacheTestService(repo, time.Minute) + input := runtimeCacheTestInput("blocked") + + decision, err := svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + + current := svc.runtimeSnapshot.Load() + require.NotNil(t, current) + expired := *current + expired.loadedAt = time.Now().Add(-2 * time.Minute) + svc.runtimeSnapshot.Store(&expired) + repo.failMultiple(errors.New("database unavailable")) + + decision, err = svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + require.Eventually(t, func() bool { + _, calls := repo.calls() + return calls == 2 + }, time.Second, time.Millisecond) + + for range 100 { + decision, err = svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + } + _, calls := repo.calls() + require.Equal(t, 2, calls) +} + +func TestContentModerationRuntimeSnapshotRefreshReusesUnchangedMatcher(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), + }} + svc := runtimeCacheTestService(repo, time.Minute) + input := runtimeCacheTestInput("blocked") + + decision, err := svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + + current := svc.runtimeSnapshot.Load() + require.NotNil(t, current) + expired := *current + expired.loadedAt = time.Now().Add(-2 * time.Minute) + svc.runtimeSnapshot.Store(&expired) + + decision, err = svc.Check(context.Background(), input) + require.NoError(t, err) + require.True(t, decision.Blocked) + require.Eventually(t, func() bool { + refreshed := svc.runtimeSnapshot.Load() + return refreshed != nil && refreshed.loadedAt.After(expired.loadedAt) + }, time.Second, time.Millisecond) + + refreshed := svc.runtimeSnapshot.Load() + require.Same(t, current.config, refreshed.config) + require.Same(t, current.keywordMatcher, refreshed.keywordMatcher) + _, calls := repo.calls() + require.Equal(t, 2, calls) +} + +func TestContentModerationRuntimeSnapshotUpdateWinsOverInFlightRefresh(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "old-keyword"), + }} + svc := runtimeCacheTestService(repo, time.Minute) + + decision, err := svc.Check(context.Background(), runtimeCacheTestInput("old-keyword")) + require.NoError(t, err) + require.True(t, decision.Blocked) + + current := svc.runtimeSnapshot.Load() + require.NotNil(t, current) + expired := *current + expired.loadedAt = time.Now().Add(-2 * time.Minute) + svc.runtimeSnapshot.Store(&expired) + + refreshStarted := make(chan struct{}, 1) + releaseRefresh := make(chan struct{}) + repo.blockNextMultiple(refreshStarted, releaseRefresh) + decision, err = svc.Check(context.Background(), runtimeCacheTestInput("clean prompt")) + require.NoError(t, err) + require.True(t, decision.Allowed) + require.Eventually(t, func() bool { + select { + case <-refreshStarted: + return true + default: + return false + } + }, time.Second, time.Millisecond) + + updateDone := make(chan error, 1) + go func() { + keywords := []string{"new-keyword"} + _, updateErr := svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{ + BlockedKeywords: &keywords, + }) + updateDone <- updateErr + }() + select { + case updateErr := <-updateDone: + require.NoError(t, updateErr) + t.Fatal("configuration update completed before the in-flight refresh released its lock") + case <-time.After(10 * time.Millisecond): + } + + close(releaseRefresh) + require.NoError(t, <-updateDone) + decision, err = svc.Check(context.Background(), runtimeCacheTestInput("new-keyword")) + require.NoError(t, err) + require.True(t, decision.Blocked) + decision, err = svc.Check(context.Background(), runtimeCacheTestInput("old-keyword")) + require.NoError(t, err) + require.True(t, decision.Allowed) +} + +func TestContentModerationRuntimeSnapshotConcurrentReadAndReplace(t *testing.T) { + repo := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked-0"), + }} + svc := runtimeCacheTestService(repo, time.Hour) + _, err := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt")) + require.NoError(t, err) + + var wg sync.WaitGroup + errs := make(chan error, 8) + for range 8 { + wg.Add(1) + go func() { + defer wg.Done() + for range 100 { + decision, checkErr := svc.Check(context.Background(), runtimeCacheTestInput("clean prompt")) + if checkErr != nil { + errs <- checkErr + return + } + if decision == nil || !decision.Allowed { + errs <- errors.New("unexpected moderation decision") + return + } + } + }() + } + for i := 1; i <= 20; i++ { + keywords := []string{"blocked-" + time.Duration(i).String()} + _, err := svc.UpdateConfig(context.Background(), UpdateContentModerationConfigInput{ + BlockedKeywords: &keywords, + }) + require.NoError(t, err) + } + wg.Wait() + close(errs) + for err := range errs { + require.NoError(t, err) + } +} From bd1399f81e33292df5720b8c3bcd073efb7ed161 Mon Sep 17 00:00:00 2001 From: cat Date: Tue, 14 Jul 2026 17:41:17 +0800 Subject: [PATCH 19/83] =?UTF-8?q?fix(openai):=20=E5=85=81=E8=AE=B8=20Agent?= =?UTF-8?q?=20Identity=20=E6=97=A0=E4=BB=A4=E7=89=8C=E6=8B=A8=E5=8F=B7=20W?= =?UTF-8?q?S?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../openai_agent_identity_compat_test.go | 26 +++++++++++++++++++ .../service/openai_ws_forwarder_ingress.go | 4 +-- .../service/openai_ws_forwarder_payload.go | 10 +++++++ .../openai_ws_v2_passthrough_adapter.go | 4 +-- 4 files changed, 40 insertions(+), 4 deletions(-) diff --git a/backend/internal/service/openai_agent_identity_compat_test.go b/backend/internal/service/openai_agent_identity_compat_test.go index bbfa82481d..ff58276310 100644 --- a/backend/internal/service/openai_agent_identity_compat_test.go +++ b/backend/internal/service/openai_agent_identity_compat_test.go @@ -189,6 +189,32 @@ func TestOpenAIWSAgentIdentityRecoveryRequiresTaskInvalidBody(t *testing.T) { })) } +func TestValidateOpenAIWSBearerTokenAllowsAgentIdentityWithoutStoredToken(t *testing.T) { + t.Run("Given Agent Identity When a WS path receives no bearer token Then dial-time assertion auth is allowed", func(t *testing.T) { + account := &Account{ + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + }, + } + + require.NoError(t, validateOpenAIWSBearerToken(account, "")) + }) + + t.Run("Given bearer credentials When a WS path receives no token Then the request is rejected", func(t *testing.T) { + accounts := []*Account{ + {Platform: PlatformOpenAI, Type: AccountTypeOAuth}, + {Platform: PlatformOpenAI, Type: AccountTypeOAuth, Credentials: map[string]any{"auth_mode": OpenAIAuthModePersonalAccessToken}}, + {Platform: PlatformOpenAI, Type: AccountTypeAPIKey}, + } + + for _, account := range accounts { + require.EqualError(t, validateOpenAIWSBearerToken(account, ""), "token is empty") + } + }) +} + func TestOpenAIWSConnPoolHeadersFactoryRunsAtDialAndStalePrewarmIsDiscarded(t *testing.T) { cfg := &config.Config{} cfg.Gateway.OpenAIWS.MaxConnsPerAccount = 1 diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index 169919b8b9..f7a54fb2b5 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -39,8 +39,8 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( if account == nil { return errors.New("account is nil") } - if strings.TrimSpace(token) == "" { - return errors.New("token is empty") + if err := validateOpenAIWSBearerToken(account, token); err != nil { + return err } // 预取一次 OpenAI Fast Policy settings,绑定到 ctx,让该 WS session diff --git a/backend/internal/service/openai_ws_forwarder_payload.go b/backend/internal/service/openai_ws_forwarder_payload.go index 0aa4adc313..67fdddc9f7 100644 --- a/backend/internal/service/openai_ws_forwarder_payload.go +++ b/backend/internal/service/openai_ws_forwarder_payload.go @@ -15,6 +15,16 @@ import ( "github.com/tidwall/sjson" ) +func validateOpenAIWSBearerToken(account *Account, token string) error { + if account == nil { + return errors.New("account is nil") + } + if strings.TrimSpace(token) == "" && !account.IsOpenAIAgentIdentity() { + return errors.New("token is empty") + } + return nil +} + func (s *OpenAIGatewayService) buildOpenAIResponsesWSURL(account *Account) (string, error) { if account == nil { return "", errors.New("account is nil") diff --git a/backend/internal/service/openai_ws_v2_passthrough_adapter.go b/backend/internal/service/openai_ws_v2_passthrough_adapter.go index 75df7191ac..72fbbd0f35 100644 --- a/backend/internal/service/openai_ws_v2_passthrough_adapter.go +++ b/backend/internal/service/openai_ws_v2_passthrough_adapter.go @@ -243,8 +243,8 @@ func (s *OpenAIGatewayService) proxyResponsesWebSocketV2Passthrough( if account == nil { return errors.New("account is nil") } - if strings.TrimSpace(token) == "" { - return errors.New("token is empty") + if err := validateOpenAIWSBearerToken(account, token); err != nil { + return err } requestModel := strings.TrimSpace(gjson.GetBytes(firstClientMessage, "model").String()) requestPreviousResponseID := strings.TrimSpace(gjson.GetBytes(firstClientMessage, "previous_response_id").String()) From f479a5d10cb4d61379a1174b809948b5e911065d Mon Sep 17 00:00:00 2001 From: cat Date: Tue, 14 Jul 2026 18:09:59 +0800 Subject: [PATCH 20/83] =?UTF-8?q?fix(openai):=20=E6=94=B6=E7=B4=A7=20Agent?= =?UTF-8?q?=20Identity=20task=20=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/cmd/server/wire_gen.go | 22 +++---- .../internal/service/account_test_service.go | 11 ++-- .../internal/service/account_usage_service.go | 3 +- .../internal/service/openai_agent_identity.go | 20 +++--- .../openai_agent_identity_compat_test.go | 12 +++- .../service/openai_gateway_service.go | 6 ++ .../internal/service/openai_quota_service.go | 21 +++---- .../service/openai_quota_spark_window_test.go | 20 ++++++ backend/internal/service/wire.go | 63 ++++++++++++++++++- 9 files changed, 137 insertions(+), 41 deletions(-) diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index e148c5c363..088046de96 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -96,9 +96,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { usageLogRepository := repository.NewUsageLogRepository(client, db) usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator) opsRepository := repository.NewOpsRepository(db) - batchImageRepository := repository.NewBatchImageRepository(db) - batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig) - batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig) usageBillingRepository := repository.NewUsageBillingRepository(client, db) gatewayCache := repository.NewGatewayCache(redisClient) schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db) @@ -137,11 +134,6 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { channelRepository := repository.NewChannelRepository(db) channelService := service.NewChannelService(channelRepository, groupRepository, apiKeyAuthCacheInvalidator, pricingService) modelPricingResolver := service.NewModelPricingResolver(channelService, billingService) - batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver) - batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig) - batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig) - batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig) - batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig) notificationEmailService := service.NewNotificationEmailService(settingRepository, emailService) balanceNotifyService := service.ProvideBalanceNotifyService(emailService, settingRepository, accountRepository, notificationEmailService) gatewayService := service.NewGatewayService(accountRepository, groupRepository, usageLogRepository, usageBillingRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, identityService, httpUpstream, deferredService, claudeTokenProvider, sessionLimitCache, rpmCache, digestSessionStore, settingService, tlsFingerprintProfileService, channelService, modelPricingResolver, balanceNotifyService, serviceUserPlatformQuotaRepository) @@ -190,10 +182,10 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { claudeUsageFetcher := repository.NewClaudeUsageFetcher(httpUpstream) antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository) grokQuotaFetcher := service.NewGrokQuotaFetcher() - openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory) + openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIGatewayService) usageCache := service.NewUsageCache() - accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService) - accountTestService := service.NewAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService) + accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService) + accountTestService := service.ProvideAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService, openAIGatewayService) crsSyncService := service.NewCRSSyncService(accountRepository, proxyRepository, oAuthService, openAIOAuthService, geminiOAuthService, configConfig) accountHandler := admin.NewAccountHandler(adminService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, rateLimitService, accountUsageService, accountTestService, concurrencyService, crsSyncService, sessionLimitCache, rpmCache, compositeTokenCacheInvalidator) adminAnnouncementHandler := admin.NewAnnouncementHandler(announcementService) @@ -267,6 +259,13 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { handlerPaymentHandler := handler.NewPaymentHandler(paymentService, paymentConfigService, channelService) paymentWebhookHandler := handler.NewPaymentWebhookHandler(paymentService, registry) availableChannelHandler := handler.NewAvailableChannelHandler(channelService, apiKeyService, settingService) + batchImageRepository := repository.NewBatchImageRepository(db) + batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig) + batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver) + batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig) + batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig) + batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig) + batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig) batchImageHandler := handler.NewBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService) idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig) idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig) @@ -285,6 +284,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { accountExpiryService := service.ProvideAccountExpiryService(accountRepository) proxyExpiryService := service.ProvideProxyExpiryService(proxyRepository) subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository, settingRepository, notificationEmailService, leaderLockCache, db) + batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig) scheduledTestRunnerService := service.ProvideScheduledTestRunnerService(scheduledTestPlanRepository, scheduledTestService, accountTestService, rateLimitService, configConfig) paymentOrderExpiryService := service.ProvidePaymentOrderExpiryService(paymentService, leaderLockCache, db) channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService) diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 68a00a5191..bb57a93cd7 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -74,6 +74,7 @@ type AccountTestService struct { cfg *config.Config tlsFPProfileService *TLSFingerprintProfileService agentIdentityTaskMu sync.Mutex + agentIdentityWS agentIdentityWSConnectionInvalidator } // NewAccountTestService creates a new AccountTestService @@ -605,7 +606,7 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account // Set common headers req.Header.Set("Content-Type", "application/json") if credentialAccount.IsOpenAIAgentIdentity() { - authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, credentialAccount) + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount) if authErr != nil { return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication") } @@ -661,7 +662,7 @@ func (s *AccountTestService) testOpenAIAccountConnection(c *gin.Context, account body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) if !agentIdentityTaskRecoveryWasTried(ctx) && credentialAccount.IsOpenAIAgentIdentity() && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, body) { expectedTaskID := credentialAccount.GetCredential("task_id") - if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, credentialAccount, expectedTaskID); err != nil { + if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount, expectedTaskID); err != nil { return s.sendErrorAndEnd(c, fmt.Sprintf("Agent Identity task recovery failed: %s", err.Error())) } c.Request = c.Request.WithContext(markAgentIdentityTaskRecoveryTried(ctx)) @@ -895,7 +896,7 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") if credentialAccount.IsOpenAIAgentIdentity() { - authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, credentialAccount) + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount) if authErr != nil { return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication") } @@ -943,7 +944,7 @@ func (s *AccountTestService) testOpenAICompactConnection(c *gin.Context, account body = redactAgentIdentitySensitiveBodyForAccount(ctx, s.accountRepo, credentialAccount, body) if !agentIdentityTaskRecoveryWasTried(ctx) && credentialAccount.IsOpenAIAgentIdentity() && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, body) { expectedTaskID := credentialAccount.GetCredential("task_id") - if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, credentialAccount, expectedTaskID); err != nil { + if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount, expectedTaskID); err != nil { return s.sendErrorAndEnd(c, fmt.Sprintf("Agent Identity task recovery failed: %s", err.Error())) } c.Request = c.Request.WithContext(markAgentIdentityTaskRecoveryTried(ctx)) @@ -1785,7 +1786,7 @@ func (s *AccountTestService) testOpenAIImageOAuth(c *gin.Context, ctx context.Co req = req.WithContext(WithHTTPUpstreamProfile(req.Context(), HTTPUpstreamProfileOpenAI)) req.Host = "chatgpt.com" if credentialAccount.IsOpenAIAgentIdentity() { - authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, credentialAccount) + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, credentialAccount) if authErr != nil { return s.sendErrorAndEnd(c, "Failed to build Agent Identity authentication") } diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index 4dc09c4109..622323c617 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -292,6 +292,7 @@ type AccountUsageService struct { identityCache IdentityCache tlsFPProfileService *TLSFingerprintProfileService agentIdentityTaskMu sync.Mutex + agentIdentityWS agentIdentityWSConnectionInvalidator } // NewAccountUsageService 创建AccountUsageService实例 @@ -706,7 +707,7 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco req.Host = "chatgpt.com" req.Header.Set("Content-Type", "application/json") if account.IsOpenAIAgentIdentity() { - authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, account) + authHeaders, authErr := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, account) if authErr != nil { return nil, fmt.Errorf("build Agent Identity authentication: %w", authErr) } diff --git a/backend/internal/service/openai_agent_identity.go b/backend/internal/service/openai_agent_identity.go index 0492a2b82e..4bf447ad64 100644 --- a/backend/internal/service/openai_agent_identity.go +++ b/backend/internal/service/openai_agent_identity.go @@ -31,6 +31,10 @@ var openAIAgentIdentityAuthAPIBaseURL = agentIdentityAuthAPIBaseURL var agentIdentityTaskLocks sync.Map // map[int64]*sync.Mutex +type agentIdentityWSConnectionInvalidator interface { + InvalidateAgentIdentityWSConnections(accountID int64) +} + type agentIdentityKey struct { runtimeID string privateKey ed25519.PrivateKey @@ -231,7 +235,7 @@ func registerAgentIdentityTask(ctx context.Context, account *Account) (string, e return decryptAgentTaskID(key, encrypted) } -func ensureAgentIdentityTaskForAccount(ctx context.Context, repo AccountRepository, pool *openAIWSConnPool, taskMu *sync.Mutex, account *Account, expectedTaskID string) error { +func ensureAgentIdentityTaskForAccount(ctx context.Context, repo AccountRepository, wsInvalidator agentIdentityWSConnectionInvalidator, taskMu *sync.Mutex, account *Account, expectedTaskID string) error { if account == nil || !account.IsOpenAIAgentIdentity() { return nil } @@ -299,8 +303,8 @@ func ensureAgentIdentityTaskForAccount(ctx context.Context, repo AccountReposito if !account.IsShadow() && account != credAccount { account.Credentials = shallowCopyMap(credAccount.Credentials) } - if pool != nil { - pool.ClearAccount(credAccount.ID) + if wsInvalidator != nil { + wsInvalidator.InvalidateAgentIdentityWSConnections(credAccount.ID) } return nil } @@ -309,7 +313,7 @@ func (s *OpenAIGatewayService) ensureAgentIdentityTask(ctx context.Context, acco if s == nil { return errors.New("openai gateway service is nil") } - return ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.openaiWSPool, &s.agentIdentityTaskMu, account, expectedTaskID) + return ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s, &s.agentIdentityTaskMu, account, expectedTaskID) } func isAgentIdentityTaskInvalidHTTPResponse(statusCode int, body []byte) bool { @@ -374,7 +378,7 @@ func (s *OpenAIGatewayService) buildOpenAIAuthenticationHeaders(ctx context.Cont } headers := make(http.Header) if credAccount != nil && credAccount.IsOpenAIAgentIdentity() { - agentHeaders, err := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.openaiWSPool, &s.agentIdentityTaskMu, credAccount) + agentHeaders, err := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s, &s.agentIdentityTaskMu, credAccount) if err != nil { return nil, err } @@ -384,11 +388,11 @@ func (s *OpenAIGatewayService) buildOpenAIAuthenticationHeaders(ctx context.Cont return headers, nil } -func buildAgentIdentityAuthenticationHeaders(ctx context.Context, repo AccountRepository, pool *openAIWSConnPool, taskMu *sync.Mutex, account *Account) (http.Header, error) { +func buildAgentIdentityAuthenticationHeaders(ctx context.Context, repo AccountRepository, wsInvalidator agentIdentityWSConnectionInvalidator, taskMu *sync.Mutex, account *Account) (http.Header, error) { if account == nil || !account.IsOpenAIAgentIdentity() { return nil, errors.New("agent identity account is required") } - if err := ensureAgentIdentityTaskForAccount(ctx, repo, pool, taskMu, account, ""); err != nil { + if err := ensureAgentIdentityTaskForAccount(ctx, repo, wsInvalidator, taskMu, account, ""); err != nil { return nil, err } key, err := agentIdentityKeyFromAccount(account) @@ -423,7 +427,7 @@ func (s *OpenAIGatewayService) refreshOpenAIAgentIdentityHeaders(ctx context.Con if refreshed == nil { refreshed = make(http.Header) } - authHeaders, err := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s.openaiWSPool, &s.agentIdentityTaskMu, credAccount) + authHeaders, err := buildAgentIdentityAuthenticationHeaders(ctx, s.accountRepo, s, &s.agentIdentityTaskMu, credAccount) if err != nil { return nil, err } diff --git a/backend/internal/service/openai_agent_identity_compat_test.go b/backend/internal/service/openai_agent_identity_compat_test.go index ff58276310..eb90dfb56e 100644 --- a/backend/internal/service/openai_agent_identity_compat_test.go +++ b/backend/internal/service/openai_agent_identity_compat_test.go @@ -89,7 +89,8 @@ func TestAccountTestServiceOpenAICompactAgentIdentityRecoversInvalidTaskOnce(t * {StatusCode: http.StatusUnauthorized, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"code":"invalid_task_id"}}`))}, {StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"id":"compact-agent","status":"completed"}`))}, }} - svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream} + invalidator := &agentIdentityWSInvalidationRecorder{} + svc := &AccountTestService{accountRepo: repo, httpUpstream: upstream, agentIdentityWS: invalidator} rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/22/test", bytes.NewReader(nil)) @@ -99,6 +100,7 @@ func TestAccountTestServiceOpenAICompactAgentIdentityRecoversInvalidTaskOnce(t * require.Len(t, upstream.requests, 2) require.Equal(t, "task-compact-new", account.GetCredential("task_id")) require.Equal(t, 0, repo.setErrorCalls) + require.Equal(t, []int64{account.ID}, invalidator.accountIDs) } func TestOpenAIAgentIdentityPassthroughKeepsSessionAndPromptCacheHeaders(t *testing.T) { @@ -431,6 +433,14 @@ type agentIdentityForwardRepo struct { account *Account } +type agentIdentityWSInvalidationRecorder struct { + accountIDs []int64 +} + +func (r *agentIdentityWSInvalidationRecorder) InvalidateAgentIdentityWSConnections(accountID int64) { + r.accountIDs = append(r.accountIDs, accountID) +} + type accountTestAgentIdentityRepo struct { AccountRepository account *Account diff --git a/backend/internal/service/openai_gateway_service.go b/backend/internal/service/openai_gateway_service.go index a17a6f6b05..24f4786e09 100644 --- a/backend/internal/service/openai_gateway_service.go +++ b/backend/internal/service/openai_gateway_service.go @@ -554,6 +554,12 @@ func (s *OpenAIGatewayService) CloseOpenAIWSPool() { } } +func (s *OpenAIGatewayService) InvalidateAgentIdentityWSConnections(accountID int64) { + if pool := s.getOpenAIWSConnPool(); pool != nil { + pool.ClearAccount(accountID) + } +} + func (s *OpenAIGatewayService) logOpenAIWSModeBootstrap() { if s == nil || s.cfg == nil { return diff --git a/backend/internal/service/openai_quota_service.go b/backend/internal/service/openai_quota_service.go index c736768b72..735a580570 100644 --- a/backend/internal/service/openai_quota_service.go +++ b/backend/internal/service/openai_quota_service.go @@ -24,6 +24,8 @@ import ( // errors.Is still matches it by identity since ResetCredit returns this var. var ErrSparkShadowResetNotSupported = infraerrors.New(http.StatusConflict, "SPARK_SHADOW_RESET_NOT_SUPPORTED", "spark shadow account does not support credit reset; reset the parent account") +var ErrAgentIdentityResetNotSupported = infraerrors.New(http.StatusConflict, "AGENT_IDENTITY_RESET_NOT_SUPPORTED", "agent identity does not support rate-limit reset credit consumption") + // Endpoints used by the OpenAI/ChatGPT/Codex quota query and reset feature. const ( chatGPTUsageURL = "https://chatgpt.com/backend-api/wham/usage" @@ -120,6 +122,7 @@ type OpenAIQuotaService struct { tokenProvider *OpenAITokenProvider privacyClientFactory PrivacyClientFactory agentIdentityTaskMu sync.Mutex + agentIdentityWS agentIdentityWSConnectionInvalidator } // NewOpenAIQuotaService constructs a quota service. token provider is required — @@ -241,6 +244,9 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( if acc.IsShadow() { return nil, ErrSparkShadowResetNotSupported } + if acc.IsOpenAIAgentIdentity() { + return nil, ErrAgentIdentityResetNotSupported + } } accessToken, chatGPTAccountID, proxyURL, fedRAMP, err := s.prepareUpstreamCall(ctx, accountID) @@ -260,10 +266,8 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( callCtx, cancel := context.WithTimeout(ctx, openaiQuotaUpstreamTimeout) defer cancel() - agentIdentity := s.isAgentIdentityAccount(ctx, accountID) - var payload OpenAIQuotaResetResult - for recovered := false; ; { + for { headers, headerErr := s.buildCodexQuotaHeaders(callCtx, accountID, accessToken, chatGPTAccountID, fedRAMP) if headerErr != nil { return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "failed to build upstream authentication: %v", headerErr) @@ -279,13 +283,6 @@ func (s *OpenAIQuotaService) ResetCredit(ctx context.Context, accountID int64) ( return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_RESET_REQUEST_FAILED", "upstream request failed: %v", err) } if !resp.IsSuccessState() { - if agentIdentity && !recovered && isAgentIdentityTaskInvalidHTTPResponse(resp.StatusCode, []byte(resp.String())) { - recovered = true - if err := s.recoverAgentIdentityTask(ctx, accountID); err != nil { - return nil, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_AUTH_FAILED", "agent identity task recovery failed: %v", err) - } - continue - } status := resp.StatusCode body := truncate(s.redactQuotaErrorBody(callCtx, accountID, resp.String()), 240) slog.Warn("openai_quota_reset_failed", "account_id", accountID, "status", status, "body", body) @@ -394,7 +391,7 @@ func (s *OpenAIQuotaService) recoverAgentIdentityTask(ctx context.Context, accou if !account.IsOpenAIAgentIdentity() { return nil } - return ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, account, account.GetCredential("task_id")) + return ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, account, account.GetCredential("task_id")) } func (s *OpenAIQuotaService) isAgentIdentityAccount(ctx context.Context, accountID int64) bool { @@ -436,7 +433,7 @@ func (s *OpenAIQuotaService) buildCodexQuotaHeaders(ctx context.Context, account if !account.IsOpenAIAgentIdentity() { return headers, nil } - if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, nil, &s.agentIdentityTaskMu, account, ""); err != nil { + if err := ensureAgentIdentityTaskForAccount(ctx, s.accountRepo, s.agentIdentityWS, &s.agentIdentityTaskMu, account, ""); err != nil { return nil, err } key, err := agentIdentityKeyFromAccount(account) diff --git a/backend/internal/service/openai_quota_spark_window_test.go b/backend/internal/service/openai_quota_spark_window_test.go index 99bfe15ca1..4e5fbc4a84 100644 --- a/backend/internal/service/openai_quota_spark_window_test.go +++ b/backend/internal/service/openai_quota_spark_window_test.go @@ -176,6 +176,23 @@ func TestResetCreditShadowRejected(t *testing.T) { "shadow ResetCredit 应映射为 409 Conflict 而非 500") } +func TestResetCreditAgentIdentityRejectedBeforeUpstream(t *testing.T) { + account := &Account{ + ID: 201, + Platform: PlatformOpenAI, + Type: AccountTypeOAuth, + Credentials: map[string]any{ + "auth_mode": OpenAIAuthModeAgentIdentity, + }, + } + repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{account.ID: account}} + svc := &OpenAIQuotaService{accountRepo: repo} + + _, err := svc.ResetCredit(context.Background(), account.ID) + require.ErrorIs(t, err, ErrAgentIdentityResetNotSupported) + require.Equal(t, http.StatusConflict, infraerrors.Code(err)) +} + // ── Part B: prepareUpstreamCall 影子 resolve ────────────────────────────── // TestPrepareUpstreamCallShadowResolve 验证影子账号(200)QueryUsage 时: @@ -306,13 +323,16 @@ func TestQueryUsageAgentIdentityRecoversInvalidTaskOnce(t *testing.T) { openAIAgentIdentityAuthAPIBaseURL = srv.URL t.Cleanup(func() { openAIAgentIdentityAuthAPIBaseURL = oldBase }) + invalidator := &agentIdentityWSInvalidationRecorder{} svc := NewOpenAIQuotaService(repo, nil, nil, newQuotaRedirectingFactory(srv)) + svc.agentIdentityWS = invalidator usage, err := svc.QueryUsage(context.Background(), account.ID) require.NoError(t, err) require.NotNil(t, usage) require.Equal(t, 2, usageCalls) require.Equal(t, 1, registerCalls) require.Equal(t, "task-quota-new", account.GetCredential("task_id")) + require.Equal(t, []int64{account.ID}, invalidator.accountIDs) } func TestParseOpenAIRateLimitResetCreditDetails_CompatibleContainers(t *testing.T) { diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index 7258ff05a3..8c20af661b 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -131,8 +131,65 @@ func ProvideOpenAIQuotaService( proxyRepo ProxyRepository, tokenProvider *OpenAITokenProvider, privacyClientFactory PrivacyClientFactory, + openAIGatewayService *OpenAIGatewayService, ) *OpenAIQuotaService { - return NewOpenAIQuotaService(accountRepo, proxyRepo, tokenProvider, privacyClientFactory) + service := NewOpenAIQuotaService(accountRepo, proxyRepo, tokenProvider, privacyClientFactory) + service.agentIdentityWS = openAIGatewayService + return service +} + +func ProvideAccountUsageService( + accountRepo AccountRepository, + usageLogRepo UsageLogRepository, + usageFetcher ClaudeUsageFetcher, + geminiQuotaService *GeminiQuotaService, + antigravityQuotaFetcher *AntigravityQuotaFetcher, + grokQuotaFetcher *GrokQuotaFetcher, + openAIQuotaService *OpenAIQuotaService, + cache *UsageCache, + identityCache IdentityCache, + tlsFPProfileService *TLSFingerprintProfileService, + openAIGatewayService *OpenAIGatewayService, +) *AccountUsageService { + service := NewAccountUsageService( + accountRepo, + usageLogRepo, + usageFetcher, + geminiQuotaService, + antigravityQuotaFetcher, + grokQuotaFetcher, + openAIQuotaService, + cache, + identityCache, + tlsFPProfileService, + ) + service.agentIdentityWS = openAIGatewayService + return service +} + +func ProvideAccountTestService( + accountRepo AccountRepository, + geminiTokenProvider *GeminiTokenProvider, + claudeTokenProvider *ClaudeTokenProvider, + grokTokenProvider *GrokTokenProvider, + antigravityGatewayService *AntigravityGatewayService, + httpUpstream HTTPUpstream, + cfg *config.Config, + tlsFPProfileService *TLSFingerprintProfileService, + openAIGatewayService *OpenAIGatewayService, +) *AccountTestService { + service := NewAccountTestService( + accountRepo, + geminiTokenProvider, + claudeTokenProvider, + grokTokenProvider, + antigravityGatewayService, + httpUpstream, + cfg, + tlsFPProfileService, + ) + service.agentIdentityWS = openAIGatewayService + return service } func ProvideGrokQuotaService( @@ -601,8 +658,8 @@ var ProviderSet = wire.NewSet( ProvideClaudeTokenProvider, NewAntigravityGatewayService, ProvideRateLimitService, - NewAccountUsageService, - NewAccountTestService, + ProvideAccountUsageService, + ProvideAccountTestService, ProvideSettingService, NewDataManagementService, ProvideBackupService, From f09d63f54eed0d724c2c3120f7c4dddbdfc779a5 Mon Sep 17 00:00:00 2001 From: haruka <1628615876@qq.com> Date: Tue, 14 Jul 2026 18:31:06 +0800 Subject: [PATCH 21/83] fix(frontend): address Codex config review feedback --- frontend/src/components/keys/UseKeyModal.vue | 39 ++++++------- .../keys/__tests__/UseKeyModal.spec.ts | 56 ++++--------------- .../src/i18n/locales/en/admin/channels.ts | 2 +- frontend/src/i18n/locales/en/dashboard.ts | 10 ++-- .../src/i18n/locales/zh/admin/channels.ts | 2 +- frontend/src/i18n/locales/zh/dashboard.ts | 10 ++-- 6 files changed, 44 insertions(+), 75 deletions(-) diff --git a/frontend/src/components/keys/UseKeyModal.vue b/frontend/src/components/keys/UseKeyModal.vue index 87983f94cc..726b01b60c 100644 --- a/frontend/src/components/keys/UseKeyModal.vue +++ b/frontend/src/components/keys/UseKeyModal.vue @@ -563,35 +563,29 @@ name = "OpenAI" base_url = "${baseUrl}" wire_api = "responses" requires_openai_auth = false -env_key = "SUB2API_API_KEY" http_headers = { "x-openai-actor-authorization" = "local-image-extension" } [features] -image_generation = true goals = true` + // auth.json content + const authContent = `{ + "OPENAI_API_KEY": "${apiKey}" +}` + return [ { path: `${configDir}/config.toml`, content: configContent, hint: t('keys.useKeyModal.openai.configTomlHint') }, - generateCodexAPIKeyEnvironment(apiKey, isWindows) + { + path: `${configDir}/auth.json`, + content: authContent + } ] } -function generateCodexAPIKeyEnvironment(apiKey: string, isWindows: boolean): FileConfig { - return isWindows - ? { - path: 'PowerShell', - content: `$env:SUB2API_API_KEY="${apiKey}"` - } - : { - path: 'Terminal', - content: `export SUB2API_API_KEY="${apiKey}"` - } -} - function generateGrokFiles(baseUrl: string, apiKey: string): FileConfig[] { const isWindows = activeTab.value === 'windows' const configDir = isWindows ? '%userprofile%\\.grok' : '~/.grok' @@ -620,7 +614,7 @@ function generateOpenAIWsFiles(baseUrl: string, apiKey: string): FileConfig[] { const isWindows = activeTab.value === 'windows' const configDir = isWindows ? '%userprofile%\\.codex' : '~/.codex' - // config.toml content with the Responses WebSocket transport enabled + // config.toml content with WebSocket v2 const configContent = `model_provider = "OpenAI" model = "gpt-5.5" review_model = "gpt-5.5" @@ -635,20 +629,27 @@ base_url = "${baseUrl}" wire_api = "responses" supports_websockets = true requires_openai_auth = false -env_key = "SUB2API_API_KEY" http_headers = { "x-openai-actor-authorization" = "local-image-extension" } [features] -image_generation = true +responses_websockets_v2 = true goals = true` + // auth.json content + const authContent = `{ + "OPENAI_API_KEY": "${apiKey}" +}` + return [ { path: `${configDir}/config.toml`, content: configContent, hint: t('keys.useKeyModal.openai.configTomlHint') }, - generateCodexAPIKeyEnvironment(apiKey, isWindows) + { + path: `${configDir}/auth.json`, + content: authContent + } ] } diff --git a/frontend/src/components/keys/__tests__/UseKeyModal.spec.ts b/frontend/src/components/keys/__tests__/UseKeyModal.spec.ts index 4e216de8da..da890f3d0e 100644 --- a/frontend/src/components/keys/__tests__/UseKeyModal.spec.ts +++ b/frontend/src/components/keys/__tests__/UseKeyModal.spec.ts @@ -78,7 +78,7 @@ describe('UseKeyModal', () => { expect(parsed.provider.grok.models['gpt-5.6']).toBeUndefined() }) - it('renders API key mode and local image generation in OpenAI Codex config', () => { + it('renders minimal image executor authorization in OpenAI Codex config', () => { const wrapper = mount(UseKeyModal, { props: { show: true, @@ -108,16 +108,17 @@ describe('UseKeyModal', () => { expect(configToml).not.toContain('model_context_window') expect(configToml).not.toContain('model_auto_compact_token_limit') expect(configToml).toContain('requires_openai_auth = false') - expect(configToml).toContain('env_key = "SUB2API_API_KEY"') expect(configToml).toContain('http_headers = { "x-openai-actor-authorization" = "local-image-extension" }') + expect(configToml).not.toContain('env_key') + expect(configToml).not.toContain('image_generation') expect(configToml).not.toContain('supports_websockets') expect(configToml).not.toContain('responses_websockets_v2') - expect(configToml).toContain('[features]\nimage_generation = true\ngoals = true') - expect(codeBlocks).toContain('export SUB2API_API_KEY="sk-test"') - expect(wrapper.text()).not.toContain('auth.json') + expect(configToml).toContain('[features]\ngoals = true') + expect(codeBlocks).toContain('{\n "OPENAI_API_KEY": "sk-test"\n}') + expect(wrapper.text()).toContain('auth.json') }) - it('renders API key mode and current WebSocket settings in OpenAI Codex config', async () => { + it('renders minimal image executor authorization in OpenAI Codex WebSocket config', async () => { const wrapper = mount(UseKeyModal, { props: { show: true, @@ -155,46 +156,13 @@ describe('UseKeyModal', () => { expect(configToml).not.toContain('model_context_window') expect(configToml).not.toContain('model_auto_compact_token_limit') expect(configToml).toContain('requires_openai_auth = false') - expect(configToml).toContain('env_key = "SUB2API_API_KEY"') expect(configToml).toContain('http_headers = { "x-openai-actor-authorization" = "local-image-extension" }') + expect(configToml).not.toContain('env_key') + expect(configToml).not.toContain('image_generation') expect(configToml).toContain('supports_websockets = true') - expect(configToml).not.toContain('responses_websockets_v2') - expect(configToml).toContain('[features]\nimage_generation = true\ngoals = true') - expect(codeBlocks).toContain('export SUB2API_API_KEY="sk-test"') - expect(wrapper.text()).not.toContain('auth.json') - }) - - it('renders a PowerShell API key command for Codex on Windows', async () => { - const wrapper = mount(UseKeyModal, { - props: { - show: true, - apiKey: 'sk-test', - baseUrl: 'https://example.com/v1', - platform: 'openai' - }, - global: { - stubs: { - BaseDialog: { - template: '
' - }, - Icon: { - template: '' - } - } - } - }) - - const windowsTab = wrapper.findAll('button').find( - (button) => button.text().trim() === 'Windows' - ) - - expect(windowsTab).toBeDefined() - await windowsTab!.trigger('click') - await nextTick() - - const codeBlocks = wrapper.findAll('pre code').map((code) => code.text()) - expect(codeBlocks).toContain('$env:SUB2API_API_KEY="sk-test"') - expect(wrapper.text()).not.toContain('auth.json') + expect(configToml).toContain('[features]\nresponses_websockets_v2 = true\ngoals = true') + expect(codeBlocks).toContain('{\n "OPENAI_API_KEY": "sk-test"\n}') + expect(wrapper.text()).toContain('auth.json') }) it('renders GPT-5.4 mini entry in OpenCode config', async () => { diff --git a/frontend/src/i18n/locales/en/admin/channels.ts b/frontend/src/i18n/locales/en/admin/channels.ts index eaeacc73b4..07a24d0fd5 100644 --- a/frontend/src/i18n/locales/en/admin/channels.ts +++ b/frontend/src/i18n/locales/en/admin/channels.ts @@ -155,7 +155,7 @@ export default { webSearchEmulationHint: '⚠️ When enabled, all accounts in this channel\'s Anthropic groups will intercept web_search requests. Use with caution.', webSearchEmulationGlobalDisabled: 'Please enable the global switch first in Settings → Gateway → Web Search Emulation', codexImageGenerationBridge: 'Codex Image Generation Bridge', - codexImageGenerationBridgeHint: 'Hosted image bridge for non-Responses Lite requests only. It may inject the image_generation tool into Codex /responses text requests; Responses Lite uses the client-side image executor instead.', + codexImageGenerationBridgeHint: 'When enabled, Codex /responses text requests in OpenAI groups may be automatically given the image_generation tool. Keep off unless the routed accounts support image generation.', bedrockCCCompat: 'Bedrock CC Compatibility', bedrockCCCompatHint: '⚠️ When enabled, requests to Bedrock accounts in this channel will be transformed for Claude Code compatibility (thinking type conversion, tool_use ID sanitization).', basicSettings: 'Basic Settings', diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts index 3d70935a05..816f6bd440 100644 --- a/frontend/src/i18n/locales/en/dashboard.ts +++ b/frontend/src/i18n/locales/en/dashboard.ts @@ -136,16 +136,16 @@ export default { noGroupTitle: 'Please assign a group first', noGroupDescription: 'This API key has not been assigned to a group. Please click the group column in the key list to assign one before viewing the configuration.', openai: { - description: 'Set SUB2API_API_KEY before starting Codex, then add the config.toml settings below. Responses Lite image generation uses Codex\'s local image executor; hosted force injection applies only to non-Responses Lite requests.', + description: 'Add the following configuration files to your Codex CLI config directory.', configTomlHint: 'Make sure the following content is at the beginning of the config.toml file', - note: 'Make sure ~/.codex exists, set the environment variable before Codex/Desktop starts, then fully restart the client and create a new thread so the image tool is registered.', - noteWindows: 'Make sure %userprofile%\\.codex exists, set the environment variable before Codex/Desktop starts, then fully restart the client and create a new thread so the image tool is registered.', + note: 'Make sure the config directory exists. macOS/Linux users can run mkdir -p ~/.codex to create it.', + noteWindows: 'Press Win+R and enter %userprofile%\\.codex to open the config directory. Create it manually if it does not exist.', }, cliTabs: { claudeCode: 'Claude Code', geminiCli: 'Gemini CLI', - codexCli: 'Codex (API Key Mode)', - codexCliWs: 'Codex (API Key Mode, WebSocket)', + codexCli: 'Codex CLI', + codexCliWs: 'Codex CLI (WebSocket)', grokCli: 'Grok CLI', opencode: 'OpenCode', }, diff --git a/frontend/src/i18n/locales/zh/admin/channels.ts b/frontend/src/i18n/locales/zh/admin/channels.ts index b0b3717f64..93890e25b0 100644 --- a/frontend/src/i18n/locales/zh/admin/channels.ts +++ b/frontend/src/i18n/locales/zh/admin/channels.ts @@ -155,7 +155,7 @@ export default { webSearchEmulationHint: '⚠️ 开启后该渠道下所有 Anthropic 分组的账号将自动拦截 web_search 请求,请谨慎操作', webSearchEmulationGlobalDisabled: '请先在系统设置 → 网关 → Web Search 模拟中启用全局开关', codexImageGenerationBridge: 'Codex 图片生成桥接', - codexImageGenerationBridgeHint: '仅用于非 Responses Lite 请求的服务端图片桥接,可向 Codex /responses 文本请求注入 image_generation 工具;Responses Lite 改用客户端图片执行器。', + codexImageGenerationBridgeHint: '开启后,OpenAI 分组的 Codex /responses 文本请求可能会被自动注入 image_generation 工具。仅在路由账号支持图片生成时开启。', bedrockCCCompat: 'Bedrock CC 兼容', bedrockCCCompatHint: '⚠️ 开启后,该渠道下 Bedrock 账号的请求将进行 Claude Code 兼容处理(thinking 类型转换、tool_use ID 清理)', basicSettings: '基础设置', diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts index 7472ec781c..a268919612 100644 --- a/frontend/src/i18n/locales/zh/dashboard.ts +++ b/frontend/src/i18n/locales/zh/dashboard.ts @@ -136,17 +136,17 @@ export default { noGroupDescription: '此 API 密钥尚未分配分组,请先在密钥列表中点击分组列进行分配,然后才能查看使用配置。', openai: { - description: '启动 Codex 前先设置 SUB2API_API_KEY,再添加以下 config.toml 配置。Responses Lite 生图使用 Codex 本地图片执行器;服务端强制注入仅用于非 Responses Lite 请求。', + description: '将以下配置文件添加到 Codex CLI 配置目录中。', configTomlHint: '请确保以下内容位于 config.toml 文件的开头部分', - note: '请确保 ~/.codex 目录存在,并在 Codex/Desktop 启动前设置环境变量;随后完全重启客户端并新建会话,以重新注册图片工具。', + note: '请确保配置目录存在。macOS/Linux 用户可运行 mkdir -p ~/.codex 创建目录。', noteWindows: - '请确保 %userprofile%\\.codex 目录存在,并在 Codex/Desktop 启动前设置环境变量;随后完全重启客户端并新建会话,以重新注册图片工具。' + '按 Win+R,输入 %userprofile%\\.codex 打开配置目录。如目录不存在,请先手动创建。' }, cliTabs: { claudeCode: 'Claude Code', geminiCli: 'Gemini CLI', - codexCli: 'Codex(API Key 模式)', - codexCliWs: 'Codex(API Key 模式,WebSocket)', + codexCli: 'Codex CLI', + codexCliWs: 'Codex CLI (WebSocket)', grokCli: 'Grok CLI', opencode: 'OpenCode' }, From 2157ee344bff8d88cb1548116848d5b6add56842 Mon Sep 17 00:00:00 2001 From: bestony Date: Tue, 14 Jul 2026 19:18:53 +0800 Subject: [PATCH 22/83] feat(keys): add optional ID column on /keys page Expose API key ID in the keys table column settings so users can show or hide it. Hidden by default; bump column-settings version so existing preferences also keep ID hidden until toggled on. --- frontend/src/i18n/locales/en/dashboard.ts | 1 + frontend/src/i18n/locales/zh/dashboard.ts | 1 + frontend/src/views/user/KeysView.vue | 12 ++++++-- .../src/views/user/__tests__/KeysView.spec.ts | 29 ++++++++++++++++--- 4 files changed, 36 insertions(+), 7 deletions(-) diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts index 3edf99158a..17181419f2 100644 --- a/frontend/src/i18n/locales/en/dashboard.ts +++ b/frontend/src/i18n/locales/en/dashboard.ts @@ -85,6 +85,7 @@ export default { editKey: 'Edit API Key', deleteKey: 'Delete API Key', deleteConfirmMessage: "Are you sure you want to delete '{name}'? This action cannot be undone.", + id: 'ID', apiKey: 'API Key', group: 'Group', currentConcurrency: 'Current Concurrency', diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts index 6b689cdf18..ac7d668f8a 100644 --- a/frontend/src/i18n/locales/zh/dashboard.ts +++ b/frontend/src/i18n/locales/zh/dashboard.ts @@ -85,6 +85,7 @@ export default { editKey: '编辑密钥', deleteKey: '删除密钥', deleteConfirmMessage: "确定要删除 '{name}' 吗?此操作无法撤销。", + id: 'ID', apiKey: 'API 密钥', group: '分组', currentConcurrency: '当前并发', diff --git a/frontend/src/views/user/KeysView.vue b/frontend/src/views/user/KeysView.vue index 161dccef88..0ade68dd8a 100644 --- a/frontend/src/views/user/KeysView.vue +++ b/frontend/src/views/user/KeysView.vue @@ -90,6 +90,10 @@ default-sort-order="desc" @sort="handleSort" > + + + +