diff --git a/README.md b/README.md index 9225dbab..73e1b98b 100644 --- a/README.md +++ b/README.md @@ -224,6 +224,8 @@ After first sign-in, change the administrator password and remove `bootstrapAdmi Imports accept UTF-8 BOM. Bulk quota sync, Build credential renewal, Web→Build/Console conversion, account tools, and cleanup report live progress. +Build refresh tokens may rotate when renewed. Do not actively share one Build credential between grok2api, the official CLI, another gateway, or another independent client: one client can consume a token that another client still holds. Authorize each active client separately, or transfer the credential only after the previous client has stopped using it. + Web account tools can accept the terms, set a random birthday corresponding to an age of 20–40, and enable NSFW. Completed steps are recorded and skipped on later runs. Automatic deletion of old `reauthRequired` accounts is available but disabled by default. Active inference leases and video jobs are protected. diff --git a/README.zh-CN.md b/README.zh-CN.md index e3351922..552d3aef 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -225,6 +225,8 @@ pnpm dev 导入兼容 UTF-8 BOM。批量额度同步、Build 凭据续期、Web→Build/Console 转换、账号工具和账号清理均显示实时进度。 +Build Refresh Token 在续期时可能发生轮换。请勿让 grok2api、官方 CLI、其他网关或独立客户端同时使用同一份 Build 凭据,否则其中一个客户端可能消费另一个客户端仍在保存的旧 Token。建议为每个活跃客户端分别授权;如需迁移凭据,应先停止旧客户端继续使用。 + Web 账号工具支持接受协议、设置对应 20–40 岁的随机生日和开启 NSFW;已完成步骤会记录并在后续执行时跳过。 系统支持自动删除长期处于 `reauthRequired` 的账号,默认关闭;存在活动推理租约或视频任务的账号不会被删除。 diff --git a/backend/internal/application/account/credential_refresh_test.go b/backend/internal/application/account/credential_refresh_test.go index 8cff482c..d57ec653 100644 --- a/backend/internal/application/account/credential_refresh_test.go +++ b/backend/internal/application/account/credential_refresh_test.go @@ -84,6 +84,29 @@ func TestEnsureCredentialPreservesBotFlagWhenRefreshedTokenCannotBeInspected(t * } } +func TestEnsureCredentialPersistsRotatedTokenAfterRequestCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + now := time.Date(2026, 7, 11, 12, 0, 0, 0, time.UTC) + service, credential, adapter := newCredentialRefreshTestService(t, now) + service.now = func() time.Time { return now } + adapter.afterRefresh = cancel + + refreshed, err := service.EnsureCredential(ctx, credential, true) + if err != nil { + t.Fatalf("refresh after request cancellation = %v", err) + } + if refreshed.EncryptedAccessToken != "access-1" || refreshed.EncryptedRefreshToken != "refresh-1" { + t.Fatalf("refreshed credential = %#v", refreshed) + } + stored, err := service.accounts.Get(context.Background(), credential.ID) + if err != nil { + t.Fatal(err) + } + if stored.EncryptedAccessToken != "access-1" || stored.EncryptedRefreshToken != "refresh-1" || stored.LastRefreshAt == nil { + t.Fatalf("rotated credential was not persisted: %#v", stored) + } +} + func TestEnsureCredentialCollapsesConcurrentForcedRefreshes(t *testing.T) { ctx := context.Background() now := time.Date(2026, 7, 11, 12, 0, 0, 0, time.UTC) @@ -446,6 +469,162 @@ func TestCredentialRefreshFailureDistinguishesTransientAndPermanent(t *testing.T } } +func TestCredentialRefreshRejectsFalsePermanentClassification(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + service, credential, adapter := newCredentialRefreshTestService(t, now) + service.now = func() time.Time { return now.Add(2 * time.Hour) } + adapter.refreshErr = &provider.CredentialRefreshError{Status: 401, Code: "invalid_client", Message: "Client authentication failed", Permanent: true} + + current := credential + for attempt := 0; attempt < credentialUnclassifiedAuthLimit+1; attempt++ { + service.clearRefreshState(credential.ID) + if _, err := service.EnsureCredential(ctx, current, true); err == nil { + t.Fatal("refresh unexpectedly succeeded") + } + var err error + current, err = service.accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + } + if current.RefreshPermanent || current.RefreshUnclassifiedAuthCount != 0 || current.AuthStatus != accountdomain.AuthStatusActive || current.RefreshDueAt == nil || current.RefreshDueAt.Before(service.now().Add(credentialConfigurationRetry)) { + t.Fatalf("configuration error was treated as an account rejection: %#v", current) + } +} + +func TestCredentialRefreshConvergesRepeatedUnclassifiedAuthRejectionAfterExpiry(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + service, credential, adapter := newCredentialRefreshTestService(t, now) + service.now = func() time.Time { return now } + adapter.refreshErr = &provider.CredentialRefreshError{Status: 401, Code: "oauth_http_401", Message: "Unauthorized"} + + current := credential + for attempt := 1; attempt <= credentialUnclassifiedAuthLimit; attempt++ { + service.clearRefreshState(credential.ID) + if _, err := service.EnsureCredential(ctx, current, true); err == nil { + t.Fatalf("refresh attempt %d unexpectedly succeeded", attempt) + } + var err error + current, err = service.accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if current.AuthStatus != accountdomain.AuthStatusActive || current.RefreshPermanent || current.RefreshUnclassifiedAuthCount != attempt { + t.Fatalf("attempt %d state = %#v", attempt, current) + } + } + + service.now = func() time.Time { return credential.ExpiresAt.Add(time.Minute) } + service.clearRefreshState(credential.ID) + if _, err := service.EnsureCredential(ctx, current, true); err == nil { + t.Fatal("expired unclassified rejection unexpectedly succeeded") + } + converged, err := service.accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if converged.AuthStatus != accountdomain.AuthStatusReauthRequired || converged.RefreshPermanent || converged.RefreshUnclassifiedAuthCount != credentialUnclassifiedAuthLimit+1 { + t.Fatalf("unclassified rejection did not converge safely: %#v", converged) + } + + adapter.refreshErr = nil + service.clearRefreshState(credential.ID) + recovered, err := service.ensureCredential(ctx, converged, ensureCredentialOptions{force: true, bypassCooldown: true, retryPermanentOnce: true}) + if err != nil { + t.Fatalf("manual refresh did not recover unclassified reauth state: %v", err) + } + if recovered.AuthStatus != accountdomain.AuthStatusActive || recovered.RefreshPermanent || recovered.RefreshUnclassifiedAuthCount != 0 { + t.Fatalf("manual recovery state = %#v", recovered) + } +} + +func TestCredentialRefreshUnclassifiedAuthCountResetsOnDifferentFailureAndSuccess(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + service, credential, adapter := newCredentialRefreshTestService(t, now) + service.now = func() time.Time { return now } + current := credential + + adapter.refreshErr = &provider.CredentialRefreshError{Status: 400, Code: "oauth_http_400"} + for attempt := 1; attempt <= 2; attempt++ { + service.clearRefreshState(credential.ID) + if _, err := service.EnsureCredential(ctx, current, true); err == nil { + t.Fatal("unclassified refresh unexpectedly succeeded") + } + var err error + current, err = service.accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + } + if current.RefreshUnclassifiedAuthCount != 2 { + t.Fatalf("unclassified count = %d", current.RefreshUnclassifiedAuthCount) + } + + adapter.refreshErr = &provider.CredentialRefreshError{Status: 503, Code: "temporarily_unavailable"} + service.clearRefreshState(credential.ID) + if _, err := service.EnsureCredential(ctx, current, true); err == nil { + t.Fatal("transient refresh unexpectedly succeeded") + } + var err error + current, err = service.accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if current.RefreshUnclassifiedAuthCount != 0 || current.AuthStatus != accountdomain.AuthStatusActive { + t.Fatalf("different failure did not reset unclassified count: %#v", current) + } + + adapter.refreshErr = &provider.CredentialRefreshError{Status: 400, Code: "oauth_http_400"} + service.clearRefreshState(credential.ID) + if _, err := service.EnsureCredential(ctx, current, true); err == nil { + t.Fatal("unclassified refresh unexpectedly succeeded") + } + current, err = service.accounts.Get(ctx, credential.ID) + if err != nil { + t.Fatal(err) + } + if current.RefreshUnclassifiedAuthCount != 1 { + t.Fatalf("new unclassified sequence count = %d", current.RefreshUnclassifiedAuthCount) + } + + adapter.refreshErr = nil + service.clearRefreshState(credential.ID) + recovered, err := service.EnsureCredential(ctx, current, true) + if err != nil { + t.Fatalf("successful refresh failed: %v", err) + } + if recovered.RefreshUnclassifiedAuthCount != 0 || recovered.RefreshFailureCount != 0 || recovered.AuthStatus != accountdomain.AuthStatusActive { + t.Fatalf("successful refresh did not clear rejection state: %#v", recovered) + } +} + +func TestHistoricalNonTerminalPermanentStateCanRefreshAgain(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + service, credential, adapter := newCredentialRefreshTestService(t, now) + service.now = func() time.Time { return now } + if err := service.accounts.UpdateCredentialRefreshFailure(ctx, credential.ID, repository.CredentialRefreshFailure{ + Count: 1, RetryAt: now, Status: 400, Code: "oauth_http_400", Message: "historical status-only classification", Permanent: true, + }); err != nil { + t.Fatal(err) + } + stuck, err := service.accounts.Get(ctx, credential.ID) + if err != nil || !stuck.RefreshPermanent { + t.Fatalf("historical state = %#v err=%v", stuck, err) + } + + recovered, err := service.EnsureCredential(ctx, stuck, true) + if err != nil { + t.Fatalf("historical non-terminal state did not retry: %v", err) + } + if recovered.RefreshPermanent || recovered.LastRefreshErrorCode != "" || adapter.refreshCount.Load() != 1 { + t.Fatalf("recovered credential = %#v count=%d", recovered, adapter.refreshCount.Load()) + } +} + func TestCredentialDecryptFailedAllowsRetryAfterKeyRecovery(t *testing.T) { ctx := context.Background() now := time.Now().UTC() @@ -661,6 +840,7 @@ type credentialRefreshAdapter struct { billing accountdomain.Billing billingErr error refreshErr error + afterRefresh func() } func (a *credentialRefreshAdapter) Provider() accountdomain.Provider { @@ -690,7 +870,10 @@ func (a *credentialRefreshAdapter) RefreshCredential(ctx context.Context, _ acco if a.refreshErr != nil { return provider.RefreshedCredential{}, a.refreshErr } - return provider.RefreshedCredential{EncryptedAccessToken: fmt.Sprintf("access-%d", count), EncryptedRefreshToken: fmt.Sprintf("refresh-%d", count), ExpiresAt: time.Now().UTC().Add(time.Hour)}, nil + if a.afterRefresh != nil { + a.afterRefresh() + } + return provider.RefreshedCredential{EncryptedAccessToken: fmt.Sprintf("access-%d", count), EncryptedRefreshToken: fmt.Sprintf("refresh-%d", count), ExpiresAt: time.Now().UTC().Add(time.Hour), RefreshTokenRotated: true}, nil } func (a *credentialRefreshAdapter) ForwardResponse(context.Context, provider.ResponseResourceRequest) (*provider.Response, error) { diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 64773a2e..bfb1843f 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -58,7 +58,9 @@ const ( credentialRefreshTimeout time.Duration = 30 * time.Second credentialRefreshStateTTL time.Duration = 5 * time.Second credentialStateWriteTimeout time.Duration = 5 * time.Second + credentialConfigurationRetry time.Duration = 30 * time.Minute credentialRefreshBatchSize = 100 + credentialUnclassifiedAuthLimit = 5 managedTaskWorkerCeiling = 50 quotaRefreshQueueSize = 4096 quotaRefreshTimeout = 30 * time.Second @@ -2459,7 +2461,7 @@ func (s *Service) ensureCredential(ctx context.Context, value accountdomain.Cred refreshed, err := adapter.RefreshCredential(ctx, latest) if err != nil { persistCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), credentialRefreshStateTTL) - s.recordCredentialRefreshFailure(persistCtx, latest, err, !options.retryPermanentOnce) + s.recordCredentialRefreshFailure(persistCtx, latest, err, !options.retryPermanentOnce, release != nil) cancel() return nil, err } @@ -2469,8 +2471,19 @@ func (s *Service) ensureCredential(ctx context.Context, value accountdomain.Cred if metadata := s.credentialMetadata(riskCredential); metadata.BuildBotFlagInspected { botFlagSource = metadata.BuildBotFlagSource } - updated, err := s.accounts.UpdateTokens(ctx, latest.ID, refreshed.EncryptedAccessToken, refreshed.EncryptedRefreshToken, refreshed.ExpiresAt, botFlagSource) + persistCtx, cancelPersist := context.WithTimeout(context.WithoutCancel(ctx), credentialStateWriteTimeout) + updated, err := s.accounts.UpdateTokens(persistCtx, latest.ID, refreshed.EncryptedAccessToken, refreshed.EncryptedRefreshToken, refreshed.ExpiresAt, botFlagSource) + cancelPersist() if err != nil { + s.logger.Error("credential_refresh_token_write_failed", + "account_id", latest.ID, + "provider", latest.Provider, + "refresh_token_rotated", refreshed.RefreshTokenRotated, + "egress_node_id", latest.EgressNodeID, + "build_api_fallback_marked", latest.BuildAPIFallback, + "distributed_lock", release != nil, + "error", err, + ) return nil, err } s.invalidateBuildBotFlagCache() @@ -2552,7 +2565,7 @@ func (s *Service) clearRefreshState(accountID uint64) { s.refreshMu.Unlock() } -func (s *Service) recordCredentialRefreshFailure(ctx context.Context, credential accountdomain.Credential, refreshErr error, preservePermanent bool) { +func (s *Service) recordCredentialRefreshFailure(ctx context.Context, credential accountdomain.Credential, refreshErr error, preservePermanent, distributedLock bool) { if errors.Is(refreshErr, context.Canceled) || errors.Is(refreshErr, context.DeadlineExceeded) && errors.Is(ctx.Err(), context.Canceled) { return } @@ -2580,17 +2593,33 @@ func (s *Service) recordCredentialRefreshFailure(ctx context.Context, credential errorCode = "oauth_timeout" errorMessage = "OAuth request timed out" } - // 真正的 OAuth 永久失败(invalid_grant 等)只能由成功换 token 清除。 - // credential_decrypt_failed 是可恢复本地错误:不得被旧 permanent 粘住,也不得把本次可恢复失败抬升为永久。 - if permanent && isRecoverableRefreshErrorCode(errorCode) { + // Defend against adapters or historical rows that classified every OAuth + // 400/401 as terminal. Only explicit credential-specific terminal codes may + // stop future refresh attempts. + if permanent && !provider.IsPermanentCredentialRefreshErrorCode(errorCode) { permanent = false } + // 真正的 OAuth 永久失败(invalid_grant 等)只能由成功换 token 清除。 + // 非终态错误不得被旧的 status-only permanent 分类粘住。 if preservePermanent && credential.RefreshPermanent && !isRecoverableRefreshErrorCode(credential.LastRefreshErrorCode) && !isRecoverableRefreshErrorCode(errorCode) { permanent = true } now := s.now() + unclassifiedAuthFailure := provider.IsUnclassifiedCredentialAuthRejection(errorStatus, errorCode) + configurationError := provider.IsCredentialRefreshConfigurationErrorCode(errorCode) + unclassifiedAuthFailureCount := 0 + if unclassifiedAuthFailure { + unclassifiedAuthFailureCount = 1 + if credential.LastRefreshErrorStatus == errorStatus && strings.EqualFold(strings.TrimSpace(credential.LastRefreshErrorCode), strings.TrimSpace(errorCode)) { + unclassifiedAuthFailureCount = credential.RefreshUnclassifiedAuthCount + 1 + } + } retryAt := now.Add(credentialRefreshBackoff(credential.ID, failureCount, retryAfter)) + if configurationError && retryAt.Before(now.Add(credentialConfigurationRetry)) { + retryAt = now.Add(credentialConfigurationRetry) + } accessTokenAlive := credential.EncryptedAccessToken != "" && !credential.ExpiresAt.IsZero() && credential.ExpiresAt.After(now) + requiresReauth := unclassifiedAuthFailure && !accessTokenAlive && unclassifiedAuthFailureCount >= credentialUnclassifiedAuthLimit if permanent && accessTokenAlive { // refresh token 已永久失效时,提前重试没有意义;到 access token 到期时再完成失效收敛。 retryAt = credential.ExpiresAt @@ -2598,11 +2627,31 @@ func (s *Service) recordCredentialRefreshFailure(ctx context.Context, credential retryAt = now } if err := s.accounts.UpdateCredentialRefreshFailure(ctx, credential.ID, repository.CredentialRefreshFailure{ - Count: failureCount, RetryAt: retryAt, Status: errorStatus, Code: errorCode, + Count: failureCount, UnclassifiedAuthFailureCount: unclassifiedAuthFailureCount, + RetryAt: retryAt, Status: errorStatus, Code: errorCode, Message: errorMessage, Response: errorResponse, Permanent: permanent, }); err != nil { s.logger.Warn("credential_refresh_state_write_failed", "account_id", credential.ID, "error", err) } + s.logger.Warn("credential_refresh_failed", + "account_id", credential.ID, + "provider", credential.Provider, + "http_status", errorStatus, + "error_code", errorCode, + "error_message", errorMessage, + "permanent", permanent, + "failure_count", failureCount, + "unclassified_auth_failure", unclassifiedAuthFailure, + "unclassified_auth_failure_count", unclassifiedAuthFailureCount, + "configuration_error", configurationError, + "requires_reauth", requiresReauth, + "retry_at", retryAt, + "access_token_alive", accessTokenAlive, + "refresh_token_rotated", false, + "egress_node_id", credential.EgressNodeID, + "build_api_fallback_marked", credential.BuildAPIFallback, + "distributed_lock", distributedLock, + ) if permanent && accessTokenAlive { s.logger.Warn("credential_refresh_permanent_but_token_alive", "account_id", credential.ID, "error_code", errorCode, "expires_at", credential.ExpiresAt, "retry_at", retryAt) s.WakeCredentialRefresh() @@ -2614,6 +2663,19 @@ func (s *Service) recordCredentialRefreshFailure(ctx context.Context, credential } return } + if requiresReauth { + if err := s.MarkReauthRequired(ctx, credential.ID, "OAuth refresh repeatedly rejected without a classifiable error"); err != nil { + s.logger.Warn("credential_refresh_unclassified_reauth_mark_failed", "account_id", credential.ID, "error", err) + return + } + s.logger.Warn("credential_refresh_unclassified_reauth_required", + "account_id", credential.ID, + "http_status", errorStatus, + "error_code", errorCode, + "failure_count", unclassifiedAuthFailureCount, + ) + return + } s.logger.Warn("credential_refresh_deferred", "account_id", credential.ID, "failure_count", failureCount, "retry_at", retryAt, "error_code", errorCode) s.WakeCredentialRefresh() } @@ -2682,12 +2744,7 @@ func (s *Service) resolvePermanentRefreshFailure(ctx context.Context, credential // isRecoverableRefreshErrorCode 标识“永久标记可被后续成功刷新清除”的本地/临时错误。 func isRecoverableRefreshErrorCode(code string) bool { - switch strings.TrimSpace(code) { - case "credential_decrypt_failed": - return true - default: - return false - } + return !provider.IsPermanentCredentialRefreshErrorCode(code) } func credentialRefreshBackoff(accountID uint64, failureCount int, retryAfter time.Duration) time.Duration { diff --git a/backend/internal/domain/account/account.go b/backend/internal/domain/account/account.go index 57c84e42..9a7047ed 100644 --- a/backend/internal/domain/account/account.go +++ b/backend/internal/domain/account/account.go @@ -141,13 +141,16 @@ type Credential struct { RefreshDueAt *time.Time LastRefreshAt *time.Time RefreshFailureCount int - LastRefreshErrorStatus int - LastRefreshErrorCode string - LastRefreshErrorMessage string - LastRefreshErrorResponse string - RefreshPermanent bool - Enabled bool - AuthStatus AuthStatus + // RefreshUnclassifiedAuthCount counts consecutive OAuth 400/401 rejections + // that cannot be classified from a machine-readable error code. + RefreshUnclassifiedAuthCount int + LastRefreshErrorStatus int + LastRefreshErrorCode string + LastRefreshErrorMessage string + LastRefreshErrorResponse string + RefreshPermanent bool + Enabled bool + AuthStatus AuthStatus // ReauthMarkedAt 仅在切入 reauthRequired 时写入;恢复 active 时清空。自动清理以该时刻为 minAge 锚点。 ReauthMarkedAt *time.Time Priority int @@ -206,23 +209,24 @@ type Credential struct { // CredentialMaterial contains the encrypted provider secrets and refresh // metadata loaded only after routing selects an account. type CredentialMaterial struct { - AccountID uint64 - Provider Provider - AuthType AuthType - OIDCClientID string - EncryptedAccessToken string - EncryptedRefreshToken string - EncryptedCloudflareCookie string - ExpiresAt time.Time - RefreshDueAt *time.Time - LastRefreshAt *time.Time - RefreshFailureCount int - LastRefreshErrorStatus int - LastRefreshErrorCode string - LastRefreshErrorMessage string - LastRefreshErrorResponse string - RefreshPermanent bool - UpdatedAt time.Time + AccountID uint64 + Provider Provider + AuthType AuthType + OIDCClientID string + EncryptedAccessToken string + EncryptedRefreshToken string + EncryptedCloudflareCookie string + ExpiresAt time.Time + RefreshDueAt *time.Time + LastRefreshAt *time.Time + RefreshFailureCount int + RefreshUnclassifiedAuthCount int + LastRefreshErrorStatus int + LastRefreshErrorCode string + LastRefreshErrorMessage string + LastRefreshErrorResponse string + RefreshPermanent bool + UpdatedAt time.Time } // ApplyTo merges credential material into the matching routing account. @@ -241,6 +245,7 @@ func (m CredentialMaterial) ApplyTo(value Credential) (Credential, bool) { value.RefreshDueAt = m.RefreshDueAt value.LastRefreshAt = m.LastRefreshAt value.RefreshFailureCount = m.RefreshFailureCount + value.RefreshUnclassifiedAuthCount = m.RefreshUnclassifiedAuthCount value.LastRefreshErrorStatus = m.LastRefreshErrorStatus value.LastRefreshErrorCode = m.LastRefreshErrorCode value.LastRefreshErrorMessage = m.LastRefreshErrorMessage diff --git a/backend/internal/infra/persistence/relational/account_auto_clean_test.go b/backend/internal/infra/persistence/relational/account_auto_clean_test.go index e315ae17..2fb711fb 100644 --- a/backend/internal/infra/persistence/relational/account_auto_clean_test.go +++ b/backend/internal/infra/persistence/relational/account_auto_clean_test.go @@ -8,6 +8,7 @@ import ( accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" "github.com/chenyme/grok2api/backend/internal/domain/media" + "github.com/chenyme/grok2api/backend/internal/repository" ) func TestDeleteAutoCleanReauthBatchSkipsActiveMediaJobs(t *testing.T) { @@ -39,6 +40,20 @@ func TestDeleteAutoCleanReauthBatchSkipsActiveMediaJobs(t *testing.T) { if err != nil { t.Fatal(err) } + ambiguous, _, err := repo.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, Name: "ambiguous", SourceKey: "ambiguous", + EncryptedAccessToken: testEncryptedToken, Enabled: true, AuthStatus: accountdomain.AuthStatusReauthRequired, + ReauthMarkedAt: ptrTime(now.Add(-2 * time.Hour)), + }) + if err != nil { + t.Fatal(err) + } + if err := repo.UpdateCredentialRefreshFailure(ctx, ambiguous.ID, repository.CredentialRefreshFailure{ + Count: 5, UnclassifiedAuthFailureCount: 5, RetryAt: now, + Status: 401, Code: "oauth_http_401", Message: "Unauthorized", + }); err != nil { + t.Fatal(err) + } key := clientKeyModel{Name: "auto-clean-key", Prefix: "auto-clean-key", SecretHash: testSecretHash, EncryptedSecret: testEncryptedToken, Enabled: true, RPMLimit: 60, MaxConcurrent: 4} if err := database.db.WithContext(ctx).Create(&key).Error; err != nil { @@ -61,7 +76,7 @@ func TestDeleteAutoCleanReauthBatchSkipsActiveMediaJobs(t *testing.T) { if err != nil { t.Fatal(err) } - deleted, err := repo.DeleteAutoCleanReauthCandidates(ctx, now.Add(-time.Hour), false, []uint64{blocked.ID, free.ID}) + deleted, err := repo.DeleteAutoCleanReauthCandidates(ctx, now.Add(-time.Hour), false, []uint64{blocked.ID, free.ID, ambiguous.ID}) if err != nil { t.Fatal(err) } @@ -74,6 +89,9 @@ func TestDeleteAutoCleanReauthBatchSkipsActiveMediaJobs(t *testing.T) { if _, err := repo.Get(ctx, blocked.ID); err != nil { t.Fatalf("blocked account should remain: %v", err) } + if _, err := repo.Get(ctx, ambiguous.ID); err != nil { + t.Fatalf("unclassified refresh reauth account should remain: %v", err) + } if _, err := repo.Get(ctx, free.ID); err == nil { t.Fatal("free account should be deleted") } diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index 8783a09a..bd0c4b3a 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -45,16 +45,17 @@ const ( accountPaidBillingSignals = `(` + accountPaidPlanSignal + ` OR billing.monthly_limit > 0 OR billing.on_demand_cap > 0 OR billing.on_demand_used > 0 OR billing.prepaid_balance > 0)` accountPaidBillingPredicate = `EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND ` + accountPaidBillingSignals + `)` // 仅 grok_build 的管理员确认 Super entitlement;与 domain.IsBuildSuper 对齐。 - accountBuildSuperEntitledPredicate = `(provider_accounts.provider = 'grok_build' AND provider_accounts.build_super_entitled = TRUE)` - accountBuildSuperPredicate = `(` + accountPaidBillingPredicate + ` OR ` + accountBuildSuperEntitledPredicate + `)` - accountInferredFreeBillingSignal = `(TRIM(billing.plan_code) = '' AND TRIM(billing.plan_name) = '' AND billing.synced_at IS NOT NULL AND billing.monthly_limit = 0 AND billing.used = 0 AND billing.on_demand_cap = 0 AND billing.on_demand_used = 0 AND billing.prepaid_balance = 0 AND billing.credit_usage_percent = 0)` - accountFreeBillingSignal = `(` + accountFreePlanSignal + ` OR ` + accountInferredFreeBillingSignal + `)` - accountFreeSignalPredicate = `(provider_accounts.provider = 'grok_build' AND (LOWER(TRIM(provider_accounts.observed_model)) LIKE '%-build-free' OR EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND ` + accountFreeBillingSignal + `)))` - accountRecoveryPredicate = `EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status IN ('exhausted', 'probing'))` - providerQuotaExhaustedPredicate = `((provider_accounts.provider = 'grok_web' AND ((EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly' AND quota.remaining > 0)) OR (NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))) OR (provider_accounts.provider = 'grok_console' AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'console') AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'console' AND quota.remaining > 0)))` - accountTypeSortExpression = `CASE WHEN provider_accounts.provider = 'grok_web' THEN COALESCE((SELECT profile.tier FROM web_account_profiles profile WHERE profile.account_id = provider_accounts.id), 'auto') WHEN ` + accountBuildSuperPredicate + ` THEN 'paid' WHEN ` + accountFreeSignalPredicate + ` THEN 'free' ELSE 'unknown' END` - accountStatusSortExpression = `CASE WHEN provider_accounts.enabled = FALSE THEN 4 WHEN provider_accounts.auth_status = 'reauthRequired' THEN 5 WHEN EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status = 'probing') THEN 3 WHEN EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status = 'exhausted') OR ` + providerQuotaExhaustedPredicate + ` THEN 2 WHEN provider_accounts.cooldown_until > CURRENT_TIMESTAMP THEN 1 ELSE 0 END` - missingConsoleAccountPredicate = `NOT EXISTS (SELECT 1 FROM provider_accounts AS console_account WHERE console_account.provider = ? AND console_account.source_key = ('console-' || provider_accounts.source_key))` + accountBuildSuperEntitledPredicate = `(provider_accounts.provider = 'grok_build' AND provider_accounts.build_super_entitled = TRUE)` + accountBuildSuperPredicate = `(` + accountPaidBillingPredicate + ` OR ` + accountBuildSuperEntitledPredicate + `)` + accountInferredFreeBillingSignal = `(TRIM(billing.plan_code) = '' AND TRIM(billing.plan_name) = '' AND billing.synced_at IS NOT NULL AND billing.monthly_limit = 0 AND billing.used = 0 AND billing.on_demand_cap = 0 AND billing.on_demand_used = 0 AND billing.prepaid_balance = 0 AND billing.credit_usage_percent = 0)` + accountFreeBillingSignal = `(` + accountFreePlanSignal + ` OR ` + accountInferredFreeBillingSignal + `)` + accountFreeSignalPredicate = `(provider_accounts.provider = 'grok_build' AND (LOWER(TRIM(provider_accounts.observed_model)) LIKE '%-build-free' OR EXISTS (SELECT 1 FROM account_billing_snapshots billing WHERE billing.account_id = provider_accounts.id AND ` + accountFreeBillingSignal + `)))` + accountRecoveryPredicate = `EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status IN ('exhausted', 'probing'))` + providerQuotaExhaustedPredicate = `((provider_accounts.provider = 'grok_web' AND ((EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly' AND quota.remaining > 0)) OR (NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'weekly') AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id) AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.remaining > 0)))) OR (provider_accounts.provider = 'grok_console' AND EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'console') AND NOT EXISTS (SELECT 1 FROM account_quota_windows quota WHERE quota.account_id = provider_accounts.id AND quota.mode = 'console' AND quota.remaining > 0)))` + accountTypeSortExpression = `CASE WHEN provider_accounts.provider = 'grok_web' THEN COALESCE((SELECT profile.tier FROM web_account_profiles profile WHERE profile.account_id = provider_accounts.id), 'auto') WHEN ` + accountBuildSuperPredicate + ` THEN 'paid' WHEN ` + accountFreeSignalPredicate + ` THEN 'free' ELSE 'unknown' END` + accountStatusSortExpression = `CASE WHEN provider_accounts.enabled = FALSE THEN 4 WHEN provider_accounts.auth_status = 'reauthRequired' THEN 5 WHEN EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status = 'probing') THEN 3 WHEN EXISTS (SELECT 1 FROM account_quota_recovery recovery WHERE recovery.account_id = provider_accounts.id AND recovery.status = 'exhausted') OR ` + providerQuotaExhaustedPredicate + ` THEN 2 WHEN provider_accounts.cooldown_until > CURRENT_TIMESTAMP THEN 1 ELSE 0 END` + accountUnclassifiedRefreshReauthPredicate = `NOT EXISTS (SELECT 1 FROM account_credentials credential WHERE credential.account_id = provider_accounts.id AND credential.refresh_permanent = FALSE AND credential.refresh_unclassified_auth_failures > 0)` + missingConsoleAccountPredicate = `NOT EXISTS (SELECT 1 FROM provider_accounts AS console_account WHERE console_account.provider = ? AND console_account.source_key = ('console-' || provider_accounts.source_key))` ) func (r *AccountRepository) List(ctx context.Context, input repository.AccountListQuery) ([]account.Credential, int64, error) { @@ -1713,6 +1714,7 @@ func (r *AccountRepository) ListAutoCleanReauthCandidates(ctx context.Context, m query := r.db.db.WithContext(ctx).Model(&accountModel{}). Select("id"). Where("auth_status = ? AND reauth_marked_at IS NOT NULL AND reauth_marked_at < ?", account.AuthStatusReauthRequired, markedBefore.UTC()). + Where(accountUnclassifiedRefreshReauthPredicate). Where("NOT EXISTS (SELECT 1 FROM media_jobs job WHERE job.account_id = provider_accounts.id AND job.status IN ?)", []string{string(media.StatusQueued), string(media.StatusInProgress)}) if afterID > 0 { query = query.Where("id > ?", afterID) @@ -1744,7 +1746,8 @@ func (r *AccountRepository) DeleteAutoCleanReauthCandidates(ctx context.Context, var lockedIDs []uint64 lockQuery := tx.Model(&accountModel{}).Clauses(clause.Locking{Strength: "UPDATE"}). - Where("id IN ? AND auth_status = ? AND reauth_marked_at IS NOT NULL AND reauth_marked_at < ?", deletable, account.AuthStatusReauthRequired, markedBefore.UTC()) + Where("id IN ? AND auth_status = ? AND reauth_marked_at IS NOT NULL AND reauth_marked_at < ?", deletable, account.AuthStatusReauthRequired, markedBefore.UTC()). + Where(accountUnclassifiedRefreshReauthPredicate) if !includeDisabled { lockQuery = lockQuery.Where("enabled = ?", true) } @@ -1759,7 +1762,8 @@ func (r *AccountRepository) DeleteAutoCleanReauthCandidates(ctx context.Context, if len(lockedIDs) == 0 { return nil } - deletion := tx.Where("id IN ? AND auth_status = ? AND reauth_marked_at IS NOT NULL AND reauth_marked_at < ?", lockedIDs, account.AuthStatusReauthRequired, markedBefore.UTC()) + deletion := tx.Where("id IN ? AND auth_status = ? AND reauth_marked_at IS NOT NULL AND reauth_marked_at < ?", lockedIDs, account.AuthStatusReauthRequired, markedBefore.UTC()). + Where(accountUnclassifiedRefreshReauthPredicate) if !includeDisabled { deletion = deletion.Where("enabled = ?", true) } @@ -1936,7 +1940,7 @@ func (r *AccountRepository) UpdateTokens(ctx context.Context, id uint64, accessT updates := map[string]any{ "encrypted_primary": accessToken, "expires_at": expiresAt, "refresh_due_at": refreshDueAt, "build_bot_flag_source": normalizeBuildBotFlagSource(account.Provider(providerRow.Provider), buildBotFlagSource), - "last_refresh_at": now, "refresh_failures": 0, "last_refresh_error_status": 0, "last_refresh_error": "", "last_refresh_error_message": "", "last_refresh_error_response": "", "refresh_permanent": false, "updated_at": now, + "last_refresh_at": now, "refresh_failures": 0, "refresh_unclassified_auth_failures": 0, "last_refresh_error_status": 0, "last_refresh_error": "", "last_refresh_error_message": "", "last_refresh_error_response": "", "refresh_permanent": false, "updated_at": now, } if refreshToken != "" { updates["encrypted_refresh"] = refreshToken @@ -2047,7 +2051,8 @@ func (r *AccountRepository) NextCredentialRefreshDueAt(ctx context.Context) (*ti func (r *AccountRepository) UpdateCredentialRefreshFailure(ctx context.Context, id uint64, failure repository.CredentialRefreshFailure) error { err := r.db.db.WithContext(ctx).Model(&accountCredentialModel{}).Where("account_id = ?", id).Updates(map[string]any{ "refresh_due_at": failure.RetryAt.UTC(), "refresh_failures": max(0, failure.Count), - "last_refresh_error_status": max(0, failure.Status), "last_refresh_error": truncate(failure.Code, 100), + "refresh_unclassified_auth_failures": max(0, failure.UnclassifiedAuthFailureCount), + "last_refresh_error_status": max(0, failure.Status), "last_refresh_error": truncate(failure.Code, 100), "last_refresh_error_message": truncate(failure.Message, 512), "last_refresh_error_response": truncate(failure.Response, 4096), "refresh_permanent": failure.Permanent, "updated_at": time.Now().UTC(), }).Error diff --git a/backend/internal/infra/persistence/relational/mapping.go b/backend/internal/infra/persistence/relational/mapping.go index 52db977d..e54dc606 100644 --- a/backend/internal/infra/persistence/relational/mapping.go +++ b/backend/internal/infra/persistence/relational/mapping.go @@ -26,6 +26,7 @@ func toAccountDomain(value accountModel) account.Credential { var expiresAt time.Time var refreshDueAt, lastRefreshAt *time.Time var refreshFailures int + var refreshUnclassifiedAuthFailures int var lastRefreshErrorStatus int var lastRefreshError string var lastRefreshErrorMessage string @@ -47,6 +48,7 @@ func toAccountDomain(value accountModel) account.Credential { refreshDueAt = value.Credential.RefreshDueAt lastRefreshAt = value.Credential.LastRefreshAt refreshFailures = value.Credential.RefreshFailures + refreshUnclassifiedAuthFailures = value.Credential.RefreshUnclassifiedAuthFailures lastRefreshErrorStatus = value.Credential.LastRefreshErrorStatus lastRefreshError = value.Credential.LastRefreshError lastRefreshErrorMessage = value.Credential.LastRefreshErrorMessage @@ -80,7 +82,7 @@ func toAccountDomain(value accountModel) account.Credential { UserID: value.UserID, TeamID: value.TeamID, SourceKey: value.SourceKey, OIDCClientID: clientID, EncryptedAccessToken: encryptedPrimary, EncryptedRefreshToken: encryptedRefresh, EncryptedCloudflareCookie: encryptedCloudflareCookie, ExpiresAt: expiresAt, RefreshDueAt: refreshDueAt, LastRefreshAt: lastRefreshAt, - RefreshFailureCount: refreshFailures, LastRefreshErrorStatus: lastRefreshErrorStatus, LastRefreshErrorCode: lastRefreshError, LastRefreshErrorMessage: lastRefreshErrorMessage, LastRefreshErrorResponse: lastRefreshErrorResponse, RefreshPermanent: refreshPermanent, + RefreshFailureCount: refreshFailures, RefreshUnclassifiedAuthCount: refreshUnclassifiedAuthFailures, LastRefreshErrorStatus: lastRefreshErrorStatus, LastRefreshErrorCode: lastRefreshError, LastRefreshErrorMessage: lastRefreshErrorMessage, LastRefreshErrorResponse: lastRefreshErrorResponse, RefreshPermanent: refreshPermanent, Enabled: value.Enabled, AuthStatus: account.AuthStatus(value.AuthStatus), ReauthMarkedAt: value.ReauthMarkedAt, Priority: value.Priority, MaxConcurrent: value.MaxConcurrent, MinimumRemaining: value.MinimumRemaining, FailureCount: value.FailureCount, CooldownUntil: value.CooldownUntil, LastError: value.LastError, LastUsedAt: value.LastUsedAt, @@ -104,7 +106,7 @@ func toCredentialMaterialDomain(value accountCredentialModel, provider account.P EncryptedAccessToken: value.EncryptedPrimary, EncryptedRefreshToken: value.EncryptedRefresh, EncryptedCloudflareCookie: value.EncryptedCloudflareCookie, ExpiresAt: expiresAt, RefreshDueAt: value.RefreshDueAt, LastRefreshAt: value.LastRefreshAt, - RefreshFailureCount: value.RefreshFailures, LastRefreshErrorStatus: value.LastRefreshErrorStatus, LastRefreshErrorCode: value.LastRefreshError, LastRefreshErrorMessage: value.LastRefreshErrorMessage, LastRefreshErrorResponse: value.LastRefreshErrorResponse, + RefreshFailureCount: value.RefreshFailures, RefreshUnclassifiedAuthCount: value.RefreshUnclassifiedAuthFailures, LastRefreshErrorStatus: value.LastRefreshErrorStatus, LastRefreshErrorCode: value.LastRefreshError, LastRefreshErrorMessage: value.LastRefreshErrorMessage, LastRefreshErrorResponse: value.LastRefreshErrorResponse, RefreshPermanent: value.RefreshPermanent, UpdatedAt: value.UpdatedAt, } } @@ -169,7 +171,7 @@ func fromAccountCredentialDomain(value account.Credential) accountCredentialMode EncryptedPrimary: value.EncryptedAccessToken, EncryptedRefresh: value.EncryptedRefreshToken, EncryptedCloudflareCookie: value.EncryptedCloudflareCookie, ExpiresAt: expiresAt, RefreshDueAt: refreshDueAt, LastRefreshAt: value.LastRefreshAt, - RefreshFailures: value.RefreshFailureCount, LastRefreshErrorStatus: value.LastRefreshErrorStatus, LastRefreshError: value.LastRefreshErrorCode, LastRefreshErrorMessage: value.LastRefreshErrorMessage, LastRefreshErrorResponse: value.LastRefreshErrorResponse, RefreshPermanent: value.RefreshPermanent, + RefreshFailures: value.RefreshFailureCount, RefreshUnclassifiedAuthFailures: value.RefreshUnclassifiedAuthCount, LastRefreshErrorStatus: value.LastRefreshErrorStatus, LastRefreshError: value.LastRefreshErrorCode, LastRefreshErrorMessage: value.LastRefreshErrorMessage, LastRefreshErrorResponse: value.LastRefreshErrorResponse, RefreshPermanent: value.RefreshPermanent, BuildBotFlagSource: normalizeBuildBotFlagSource(value.Provider, value.BuildBotFlagSource), UpdatedAt: time.Now().UTC(), } diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index 676ca6d0..953f4744 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -67,24 +67,25 @@ type accountModel struct { func (accountModel) TableName() string { return "provider_accounts" } type accountCredentialModel struct { - AccountID uint64 `gorm:"primaryKey"` - AuthType string `gorm:"size:16;not null;check:chk_account_credentials_auth_type,auth_type IN ('oauth','sso')"` - ClientID string `gorm:"size:255;check:chk_account_credentials_client_id,length(client_id) <= 255"` - EncryptedPrimary string `gorm:"type:text;not null;default:'';check:chk_account_credentials_secret,((auth_type = 'oauth' AND (encrypted_primary <> '' OR encrypted_refresh <> '')) OR (auth_type = 'sso' AND encrypted_primary <> '' AND encrypted_refresh = '')) AND length(encrypted_primary) <= 65536 AND length(encrypted_refresh) <= 65536"` - EncryptedRefresh string `gorm:"type:text;not null;default:''"` - EncryptedCloudflareCookie string `gorm:"type:text;not null;default:'';check:chk_account_credentials_cf_cookie,length(encrypted_cloudflare_cookie) <= 65536"` - ExpiresAt *time.Time - RefreshDueAt *time.Time - LastRefreshAt *time.Time - RefreshFailures int `gorm:"not null;default:0;check:chk_account_credentials_refresh_failures,refresh_failures >= 0"` - LastRefreshErrorStatus int `gorm:"not null;default:0;check:chk_account_credentials_refresh_error_status,last_refresh_error_status >= 0"` - LastRefreshError string `gorm:"size:100;not null;default:'';check:chk_account_credentials_refresh_error,length(last_refresh_error) <= 100"` - LastRefreshErrorMessage string `gorm:"size:512;not null;default:'';check:chk_account_credentials_refresh_error_message,length(last_refresh_error_message) <= 512"` - LastRefreshErrorResponse string `gorm:"size:4096;not null;default:'';check:chk_account_credentials_refresh_error_response,length(last_refresh_error_response) <= 4096"` - RefreshPermanent bool `gorm:"not null;default:false"` - BuildBotFlagSource int `gorm:"not null;default:0;check:chk_account_credentials_build_bot_flag_source,build_bot_flag_source IN (0,1,2)"` - UpdatedAt time.Time `gorm:"not null"` - Account *accountModel `gorm:"foreignKey:AccountID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` + AccountID uint64 `gorm:"primaryKey"` + AuthType string `gorm:"size:16;not null;check:chk_account_credentials_auth_type,auth_type IN ('oauth','sso')"` + ClientID string `gorm:"size:255;check:chk_account_credentials_client_id,length(client_id) <= 255"` + EncryptedPrimary string `gorm:"type:text;not null;default:'';check:chk_account_credentials_secret,((auth_type = 'oauth' AND (encrypted_primary <> '' OR encrypted_refresh <> '')) OR (auth_type = 'sso' AND encrypted_primary <> '' AND encrypted_refresh = '')) AND length(encrypted_primary) <= 65536 AND length(encrypted_refresh) <= 65536"` + EncryptedRefresh string `gorm:"type:text;not null;default:''"` + EncryptedCloudflareCookie string `gorm:"type:text;not null;default:'';check:chk_account_credentials_cf_cookie,length(encrypted_cloudflare_cookie) <= 65536"` + ExpiresAt *time.Time + RefreshDueAt *time.Time + LastRefreshAt *time.Time + RefreshFailures int `gorm:"not null;default:0;check:chk_account_credentials_refresh_failures,refresh_failures >= 0"` + RefreshUnclassifiedAuthFailures int `gorm:"not null;default:0;check:chk_account_credentials_refresh_unclassified_auth_failures,refresh_unclassified_auth_failures >= 0"` + LastRefreshErrorStatus int `gorm:"not null;default:0;check:chk_account_credentials_refresh_error_status,last_refresh_error_status >= 0"` + LastRefreshError string `gorm:"size:100;not null;default:'';check:chk_account_credentials_refresh_error,length(last_refresh_error) <= 100"` + LastRefreshErrorMessage string `gorm:"size:512;not null;default:'';check:chk_account_credentials_refresh_error_message,length(last_refresh_error_message) <= 512"` + LastRefreshErrorResponse string `gorm:"size:4096;not null;default:'';check:chk_account_credentials_refresh_error_response,length(last_refresh_error_response) <= 4096"` + RefreshPermanent bool `gorm:"not null;default:false"` + BuildBotFlagSource int `gorm:"not null;default:0;check:chk_account_credentials_build_bot_flag_source,build_bot_flag_source IN (0,1,2)"` + UpdatedAt time.Time `gorm:"not null"` + Account *accountModel `gorm:"foreignKey:AccountID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` } func (accountCredentialModel) TableName() string { return "account_credentials" } diff --git a/backend/internal/infra/persistence/relational/repository_test.go b/backend/internal/infra/persistence/relational/repository_test.go index 42dfb1e2..2d141b49 100644 --- a/backend/internal/infra/persistence/relational/repository_test.go +++ b/backend/internal/infra/persistence/relational/repository_test.go @@ -501,7 +501,7 @@ func TestFreshSchemaContract(t *testing.T) { } } assertTableColumns(t, database, "provider_accounts", []string{"provider", "source_key", "auth_status", "build_api_fallback", "build_route_mode", "build_super_entitled"}, []string{"oidc_client_id", "expires_at", "encrypted_access_token", "encrypted_refresh_token"}) - assertTableColumns(t, database, "account_credentials", []string{"account_id", "auth_type", "client_id", "encrypted_primary", "encrypted_refresh", "expires_at", "refresh_due_at", "last_refresh_at", "refresh_failures", "last_refresh_error_status", "last_refresh_error", "last_refresh_error_message", "last_refresh_error_response", "refresh_permanent"}, nil) + assertTableColumns(t, database, "account_credentials", []string{"account_id", "auth_type", "client_id", "encrypted_primary", "encrypted_refresh", "expires_at", "refresh_due_at", "last_refresh_at", "refresh_failures", "refresh_unclassified_auth_failures", "last_refresh_error_status", "last_refresh_error", "last_refresh_error_message", "last_refresh_error_response", "refresh_permanent"}, nil) assertTableColumns(t, database, "web_account_profiles", []string{"account_id", "tier", "synced_at", "nsfw_enabled_at"}, nil) assertTableColumns(t, database, "admin_sessions", nil, []string{"revoked_at"}) assertTableColumns(t, database, "account_model_capabilities", []string{"account_id", "upstream_model"}, []string{"provider", "synced_at"}) @@ -528,6 +528,49 @@ func TestFreshSchemaContract(t *testing.T) { } } +func TestInitializeSchemaAddsUnclassifiedAuthFailureCountWithoutLosingCredentialState(t *testing.T) { + ctx := context.Background() + database := openTestDatabase(t) + repo := NewAccountRepository(database) + now := time.Now().UTC() + created, _, err := repo.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "legacy-refresh", SourceKey: "legacy-refresh", + EncryptedAccessToken: "preserved-access", EncryptedRefreshToken: "preserved-refresh", + ExpiresAt: now.Add(time.Hour), AuthStatus: account.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + if err := repo.UpdateCredentialRefreshFailure(ctx, created.ID, repository.CredentialRefreshFailure{ + Count: 3, UnclassifiedAuthFailureCount: 3, RetryAt: now.Add(10 * time.Minute), + Status: 401, Code: "oauth_http_401", Message: "Unauthorized", + }); err != nil { + t.Fatal(err) + } + if err := database.withSQLiteForeignKeysDisabled(ctx, func() error { + if err := database.db.WithContext(ctx).Migrator().DropConstraint(&accountCredentialModel{}, "chk_account_credentials_refresh_unclassified_auth_failures"); err != nil { + return err + } + return database.db.WithContext(ctx).Migrator().DropColumn(&accountCredentialModel{}, "RefreshUnclassifiedAuthFailures") + }); err != nil { + t.Fatal(err) + } + + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + if !database.db.WithContext(ctx).Migrator().HasColumn(&accountCredentialModel{}, "RefreshUnclassifiedAuthFailures") { + t.Fatal("refresh_unclassified_auth_failures column was not restored") + } + stored, err := repo.Get(ctx, created.ID) + if err != nil { + t.Fatal(err) + } + if stored.EncryptedAccessToken != "preserved-access" || stored.EncryptedRefreshToken != "preserved-refresh" || stored.RefreshFailureCount != 3 || stored.LastRefreshErrorStatus != 401 || stored.LastRefreshErrorCode != "oauth_http_401" || stored.RefreshUnclassifiedAuthCount != 0 { + t.Fatalf("credential state after schema upgrade = %#v", stored) + } +} + func TestSchemaRejectsInvalidPersistentValues(t *testing.T) { database := openTestDatabase(t) ctx := context.Background() diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index cc628919..49b5afef 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -845,7 +845,7 @@ func (a *Adapter) RefreshCredential(ctx context.Context, credential account.Cred if err != nil { return provider.RefreshedCredential{}, err } - return provider.RefreshedCredential{EncryptedAccessToken: accessEncrypted, EncryptedRefreshToken: refreshEncrypted, ExpiresAt: tokens.ExpiresAt}, nil + return provider.RefreshedCredential{EncryptedAccessToken: accessEncrypted, EncryptedRefreshToken: refreshEncrypted, ExpiresAt: tokens.ExpiresAt, RefreshTokenRotated: tokens.RefreshTokenRotated}, nil } func (a *Adapter) StartDeviceAuthorization(ctx context.Context) (provider.DeviceAuthorization, error) { diff --git a/backend/internal/infra/provider/cli/oauth.go b/backend/internal/infra/provider/cli/oauth.go index d09dda8e..21b2afa8 100644 --- a/backend/internal/infra/provider/cli/oauth.go +++ b/backend/internal/infra/provider/cli/oauth.go @@ -81,16 +81,17 @@ func (c *oauthClient) refreshWithClientID(ctx context.Context, refreshToken, cli form := url.Values{"grant_type": {"refresh_token"}, "client_id": {firstNonEmpty(clientID, c.clientID)}, "refresh_token": {refreshToken}} value, err := c.exchange(ctx, form, refreshToken, false) if errors.Is(err, provider.ErrAuthorizationDenied) { - return tokenPayload{}, &provider.CredentialRefreshError{Code: "refresh_denied", Message: "OAuth authorization was denied", Permanent: true, Cause: err} + return tokenPayload{}, &provider.CredentialRefreshError{Code: "refresh_denied", Message: "OAuth authorization was denied", Cause: err} } return value, err } type tokenPayload struct { - AccessToken string - RefreshToken string - ExpiresAt time.Time - IDToken string + AccessToken string + RefreshToken string + ExpiresAt time.Time + IDToken string + RefreshTokenRotated bool } func (c *oauthClient) exchange(ctx context.Context, form url.Values, fallbackRefresh string, deviceFlow bool) (tokenPayload, error) { @@ -130,7 +131,7 @@ func (c *oauthClient) exchange(ctx context.Context, form url.Values, fallbackRef } return tokenPayload{}, &provider.CredentialRefreshError{ Status: resp.StatusCode, Code: oauthError.Code, Message: oauthError.Message, Response: oauthError.Response, - Permanent: resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusUnauthorized, + Permanent: provider.IsPermanentCredentialRefreshErrorCode(oauthError.Code), RetryAfter: parseOAuthRetryAfter(resp.Header.Get("Retry-After")), } } @@ -144,12 +145,13 @@ func (c *oauthClient) exchange(ctx context.Context, form url.Values, fallbackRef return tokenPayload{}, fmt.Errorf("解析 xAI OAuth 响应: %w", err) } if value.AccessToken == "" { - return tokenPayload{}, &provider.CredentialRefreshError{Status: resp.StatusCode, Code: "missing_access_token", Message: "OAuth response did not contain access_token", Permanent: true} + return tokenPayload{}, &provider.CredentialRefreshError{Status: resp.StatusCode, Code: "missing_access_token", Message: "OAuth response did not contain access_token"} } if value.ExpiresIn <= 0 { value.ExpiresIn = 3600 } - return tokenPayload{AccessToken: value.AccessToken, RefreshToken: firstNonEmpty(value.RefreshToken, fallbackRefresh), ExpiresAt: time.Now().UTC().Add(time.Duration(value.ExpiresIn) * time.Second), IDToken: value.IDToken}, nil + rotated := strings.TrimSpace(value.RefreshToken) != "" && strings.TrimSpace(value.RefreshToken) != strings.TrimSpace(fallbackRefresh) + return tokenPayload{AccessToken: value.AccessToken, RefreshToken: firstNonEmpty(value.RefreshToken, fallbackRefresh), ExpiresAt: time.Now().UTC().Add(time.Duration(value.ExpiresIn) * time.Second), IDToken: value.IDToken, RefreshTokenRotated: rotated}, nil } type oauthErrorDetails struct { diff --git a/backend/internal/infra/provider/cli/oauth_test.go b/backend/internal/infra/provider/cli/oauth_test.go index 8d9c6654..871664df 100644 --- a/backend/internal/infra/provider/cli/oauth_test.go +++ b/backend/internal/infra/provider/cli/oauth_test.go @@ -4,15 +4,18 @@ import ( "context" "encoding/base64" "errors" + accountapp "github.com/chenyme/grok2api/backend/internal/application/account" + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/infra/persistence/relational" + "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/security" "io" "net/http" + "net/http/httptest" + "path/filepath" "strings" "testing" "time" - - accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" - "github.com/chenyme/grok2api/backend/internal/infra/provider" - "github.com/chenyme/grok2api/backend/internal/infra/security" ) func TestPrepareImportedCredentialRefreshesRTOnlySeed(t *testing.T) { @@ -64,6 +67,75 @@ func TestPrepareImportedCredentialRefreshesRTOnlySeed(t *testing.T) { } } +func TestCredentialRefreshCallsOAuthAndPersistsRotationEndToEnd(t *testing.T) { + ctx := context.Background() + requests := 0 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + requests++ + if err := request.ParseForm(); err != nil { + t.Errorf("parse form: %v", err) + writer.WriteHeader(http.StatusBadRequest) + return + } + if request.Form.Get("grant_type") != "refresh_token" || request.Form.Get("refresh_token") != "original-rt" || request.Form.Get("client_id") != "custom-client" { + t.Errorf("form = %#v", request.Form) + writer.WriteHeader(http.StatusBadRequest) + return + } + writer.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(writer, `{"access_token":"fresh-access","refresh_token":"rotated-rt","expires_in":3600}`) + })) + t.Cleanup(server.Close) + + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "oauth-refresh-e2e.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + accessEncrypted, err := cipher.Encrypt("old-access") + if err != nil { + t.Fatal(err) + } + refreshEncrypted, err := cipher.Encrypt("original-rt") + if err != nil { + t.Fatal(err) + } + adapter := NewAdapter(Config{}, cipher) + adapter.oauth.http = server.Client() + adapter.oauth.tokenURL = server.URL + repository := relational.NewAccountRepository(database) + credential, _, err := repository.UpsertByIdentity(ctx, accountdomain.Credential{ + Provider: accountdomain.ProviderBuild, AuthType: accountdomain.AuthTypeOAuth, Name: "oauth-e2e", SourceKey: "oauth-e2e", OIDCClientID: "custom-client", + EncryptedAccessToken: accessEncrypted, EncryptedRefreshToken: refreshEncrypted, ExpiresAt: time.Now().UTC().Add(time.Hour), Enabled: true, AuthStatus: accountdomain.AuthStatusActive, + }) + if err != nil { + t.Fatal(err) + } + service := accountapp.NewService(repository, nil, nil, nil, provider.NewRegistry(adapter), cipher, nil) + refreshed, err := service.EnsureCredential(ctx, credential, true) + if err != nil { + t.Fatal(err) + } + storedAccess, err := cipher.Decrypt(refreshed.EncryptedAccessToken) + if err != nil { + t.Fatal(err) + } + storedRefresh, err := cipher.Decrypt(refreshed.EncryptedRefreshToken) + if err != nil { + t.Fatal(err) + } + if requests != 1 || storedAccess != "fresh-access" || storedRefresh != "rotated-rt" || refreshed.LastRefreshAt == nil { + t.Fatalf("requests=%d access=%q refresh=%q credential=%#v", requests, storedAccess, storedRefresh, refreshed) + } +} + func TestOAuthDeviceFlowMatchesOfficialWireContract(t *testing.T) { version := "0.2.111" requests := 0 @@ -141,8 +213,11 @@ func TestOAuthRefreshClassifiesPermanentAndTransientFailures(t *testing.T) { response string }{ {name: "transient upstream", status: http.StatusServiceUnavailable, body: `{"error":"temporarily_unavailable"}`, retryAfter: "7", code: "temporarily_unavailable"}, + {name: "bad request is not inherently permanent", status: http.StatusBadRequest, body: `{"error":"temporarily_unavailable","error_description":"Try another egress"}`, code: "temporarily_unavailable", message: "Try another egress"}, + {name: "unauthorized client is configuration scoped", status: http.StatusUnauthorized, body: `{"error":"invalid_client","error_description":"Client authentication failed"}`, code: "invalid_client", message: "Client authentication failed"}, {name: "invalid grant", status: http.StatusBadRequest, body: `{"error":"invalid_grant","error_description":"Refresh token has expired","message":"Access denied","request_id":"req-123","refresh_token":"must-not-leak"}`, permanent: true, code: "invalid_grant", message: "Refresh token has expired · Access denied", response: `"refresh_token":"[REDACTED]"`}, - {name: "nested error", status: http.StatusBadRequest, body: `{"error":{"code":"invalid_client","message":"Client rejected","detail":"Application disabled"}}`, permanent: true, code: "invalid_client", message: "Client rejected · Application disabled", response: `"detail":"Application disabled"`}, + {name: "nested error", status: http.StatusBadRequest, body: `{"error":{"code":"invalid_client","message":"Client rejected","detail":"Application disabled"}}`, code: "invalid_client", message: "Client rejected · Application disabled", response: `"detail":"Application disabled"`}, + {name: "explicit revoked refresh token", status: http.StatusUnauthorized, body: `{"error":"refresh_token_revoked"}`, permanent: true, code: "refresh_token_revoked"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -179,6 +254,18 @@ func TestOAuthRefreshClassifiesPermanentAndTransientFailures(t *testing.T) { } } +func TestOAuthRefreshTreatsMalformedSuccessAsRetryable(t *testing.T) { + httpClient := &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) { + return oauthResponse(http.StatusOK, `{"expires_in":3600}`), nil + })} + client := newOAuthClient(httpClient, nil) + _, err := client.refresh(context.Background(), "refresh") + var refreshErr *provider.CredentialRefreshError + if !errors.As(err, &refreshErr) || refreshErr.Code != "missing_access_token" || refreshErr.Permanent { + t.Fatalf("error = %#v", err) + } +} + func TestOAuthScopeMatchesOfficialPersonalAccountContract(t *testing.T) { values := strings.Fields(defaultOAuthScope) want := []string{ diff --git a/backend/internal/infra/provider/credential_refresh_test.go b/backend/internal/infra/provider/credential_refresh_test.go new file mode 100644 index 00000000..479a4738 --- /dev/null +++ b/backend/internal/infra/provider/credential_refresh_test.go @@ -0,0 +1,29 @@ +package provider + +import ( + "net/http" + "testing" +) + +func TestIsUnclassifiedCredentialAuthRejection(t *testing.T) { + tests := []struct { + name string + status int + code string + want bool + }{ + {name: "opaque bad request", status: http.StatusBadRequest, code: "oauth_http_400", want: true}, + {name: "unknown unauthorized", status: http.StatusUnauthorized, code: "challenge_required", want: true}, + {name: "invalid grant is terminal", status: http.StatusBadRequest, code: "invalid_grant"}, + {name: "invalid client is configuration", status: http.StatusUnauthorized, code: "invalid_client"}, + {name: "temporary oauth condition", status: http.StatusBadRequest, code: "temporarily_unavailable"}, + {name: "server failure", status: http.StatusServiceUnavailable, code: "unknown", want: false}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := IsUnclassifiedCredentialAuthRejection(test.status, test.code); got != test.want { + t.Fatalf("IsUnclassifiedCredentialAuthRejection(%d, %q) = %t, want %t", test.status, test.code, got, test.want) + } + }) + } +} diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index a4e5c125..652a3b4c 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -276,6 +276,70 @@ func (e *CredentialRefreshError) Unwrap() error { return e.Cause } +// IsPermanentCredentialRefreshErrorCode reports credential-specific terminal +// failures. HTTP status alone is intentionally insufficient: OAuth gateways +// also use 400/401 for temporary policy, client, and infrastructure errors. +func IsPermanentCredentialRefreshErrorCode(code string) bool { + switch normalizeCredentialRefreshErrorCode(code) { + case "invalid_grant", + "invalid_refresh_token", + "refresh_token_invalid", + "refresh_token_expired", + "refresh_token_revoked", + "refresh_token_reused", + "refresh_token_reuse", + "token_reused", + "token_reuse_detected", + "expired_token", + "revoked_token", + "token_revoked", + "missing_refresh_token": + return true + default: + return false + } +} + +// IsCredentialRefreshConfigurationErrorCode reports OAuth failures caused by +// this gateway's client/request configuration rather than by one account's +// refresh token. These errors should be retried conservatively and surfaced to +// operators, but must not mark an individual account reauthRequired. +func IsCredentialRefreshConfigurationErrorCode(code string) bool { + switch normalizeCredentialRefreshErrorCode(code) { + case "invalid_client", "unauthorized_client", "invalid_request", "invalid_scope", "unsupported_grant_type": + return true + default: + return false + } +} + +// IsUnclassifiedCredentialAuthRejection reports a 400/401 response that is +// neither a known terminal refresh-token error, a known client configuration +// error, nor an explicitly retryable OAuth condition. Repeated occurrences can +// eventually require operator reauthorization without claiming the refresh +// token was definitively revoked. +func IsUnclassifiedCredentialAuthRejection(status int, code string) bool { + if status != http.StatusBadRequest && status != http.StatusUnauthorized { + return false + } + if IsPermanentCredentialRefreshErrorCode(code) || IsCredentialRefreshConfigurationErrorCode(code) { + return false + } + switch normalizeCredentialRefreshErrorCode(code) { + case "authorization_pending", "slow_down", "temporarily_unavailable", "server_error", + "rate_limited", "rate_limit_exceeded", "too_many_requests", "oauth_timeout", + "oauth_transport_error", "oauth_unavailable": + return false + default: + return true + } +} + +func normalizeCredentialRefreshErrorCode(code string) string { + normalized := strings.ToLower(strings.TrimSpace(code)) + return strings.ReplaceAll(normalized, "-", "_") +} + // ResponseResourceRequest describes a common upstream request to a Responses resource endpoint. type ResponseResourceRequest struct { Credential account.Credential @@ -594,6 +658,10 @@ type RefreshedCredential struct { EncryptedAccessToken string EncryptedRefreshToken string ExpiresAt time.Time + // RefreshTokenRotated reports that the OAuth response explicitly returned + // a different refresh token. It is diagnostic metadata only; token values + // must never be logged. + RefreshTokenRotated bool } // Adapter defines only Provider identity; concrete capabilities are registered through small interfaces as needed. diff --git a/backend/internal/repository/account.go b/backend/internal/repository/account.go index 707c7425..4b68c3e1 100644 --- a/backend/internal/repository/account.go +++ b/backend/internal/repository/account.go @@ -38,13 +38,14 @@ type BuildBotFlagSourceUpdate struct { // latest failed OAuth refresh. Response must already be redacted by the // provider adapter before it reaches persistence. type CredentialRefreshFailure struct { - Count int - RetryAt time.Time - Status int - Code string - Message string - Response string - Permanent bool + Count int + UnclassifiedAuthFailureCount int + RetryAt time.Time + Status int + Code string + Message string + Response string + Permanent bool } // LinkedDeleteResolution is the server-side expansion of root deletes with optional linked peers.