From 232fe83207f5ccfab471b5dd7ade3e87e0dfc2ff Mon Sep 17 00:00:00 2001 From: Huan-zhaojun <111294954+Huan-zhaojun@users.noreply.github.com> Date: Fri, 24 Jul 2026 16:46:24 +0800 Subject: [PATCH] feat(account): mark SSO invalid on session blocked and quota blocked-user MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Map definitive upstream dead-account signals to provider.ErrUnauthorized so import identity sync and Web quota refresh persist reauthRequired (UI: 失效) and drop accounts from scheduling. - Session Parse: status=blocked (no identity) → ErrUnauthorized - Web rate-limits: HTTP 403 body with blocked-user / user is blocked → ErrUnauthorized - Keep generic missing-identity and non-blocked 403 as non-invalidating failures - Add sessionidentity Parse tests and Web quota blocked/generic 403 tests --- .../application/account/provider_links.go | 4 +- .../infra/provider/sessionidentity/session.go | 8 ++- .../provider/sessionidentity/session_test.go | 46 +++++++++++++ backend/internal/infra/provider/web/quota.go | 13 ++++ .../internal/infra/provider/web/quota_test.go | 66 +++++++++++++++++++ 5 files changed, 135 insertions(+), 2 deletions(-) create mode 100644 backend/internal/infra/provider/sessionidentity/session_test.go diff --git a/backend/internal/application/account/provider_links.go b/backend/internal/application/account/provider_links.go index 5108bc04..31919ece 100644 --- a/backend/internal/application/account/provider_links.go +++ b/backend/internal/application/account/provider_links.go @@ -16,7 +16,9 @@ type providerLinkRepository interface { } // SyncAccountIdentity 尽力补充 Web/Console 的稳定上游身份,并据此建立高可信弱关联。 -// 只有明确的 401 会将当前 Provider 账号移出号池;其他同步失败不影响健康状态。 +// Session unauthenticated / blocked、HTTP 401 等映射为 ErrUnauthorized 时, +// 会将当前 Provider 账号标为 reauthRequired(管理端「失效」)并移出调度; +// 其他同步失败不影响健康状态。 func (s *Service) SyncAccountIdentity(ctx context.Context, id uint64) error { _, err, _ := s.identitySyncs.Do(fmt.Sprintf("%d", id), func() (any, error) { return nil, s.syncAccountIdentity(ctx, id) diff --git a/backend/internal/infra/provider/sessionidentity/session.go b/backend/internal/infra/provider/sessionidentity/session.go index 4938c4d6..168fc7a2 100644 --- a/backend/internal/infra/provider/sessionidentity/session.go +++ b/backend/internal/infra/provider/sessionidentity/session.go @@ -105,9 +105,15 @@ func Parse(body []byte) (provider.AccountIdentity, error) { identity.Email = strings.TrimSpace(identity.Email) identity.TeamID = strings.TrimSpace(identity.TeamID) if identity.UserID == "" && identity.Email == "" { - if strings.EqualFold(strings.TrimSpace(value.Status), "unauthenticated") { + status := strings.TrimSpace(value.Status) + // unauthenticated / blocked 均表示当前 SSO 对上游不可用,统一映射为 ErrUnauthorized, + // 以便导入与身份同步路径将账号标为 reauthRequired(管理端「失效」)并移出调度。 + if strings.EqualFold(status, "unauthenticated") { return provider.AccountIdentity{}, provider.ErrUnauthorized } + if strings.EqualFold(status, "blocked") { + return provider.AccountIdentity{}, fmt.Errorf("%w: session status blocked", provider.ErrUnauthorized) + } return provider.AccountIdentity{}, fmt.Errorf("Grok Session 缺少账号身份") } return identity, nil diff --git a/backend/internal/infra/provider/sessionidentity/session_test.go b/backend/internal/infra/provider/sessionidentity/session_test.go new file mode 100644 index 00000000..a26a30bd --- /dev/null +++ b/backend/internal/infra/provider/sessionidentity/session_test.go @@ -0,0 +1,46 @@ +package sessionidentity + +import ( + "errors" + "testing" + + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +func TestParseBlockedSessionIsUnauthorized(t *testing.T) { + t.Parallel() + _, err := Parse([]byte(`{"status":"blocked"}`)) + if !errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("err = %v, want ErrUnauthorized", err) + } +} + +func TestParseUnauthenticatedSessionIsUnauthorized(t *testing.T) { + t.Parallel() + _, err := Parse([]byte(`{"status":"unauthenticated"}`)) + if !errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("err = %v, want ErrUnauthorized", err) + } +} + +func TestParseMissingIdentityWithoutStatusStaysGeneric(t *testing.T) { + t.Parallel() + _, err := Parse([]byte(`{}`)) + if err == nil || errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("err = %v, want generic missing-identity error", err) + } +} + +func TestParseAuthenticatedSession(t *testing.T) { + t.Parallel() + identity, err := Parse([]byte(`{ + "status":"authenticated", + "session":{"userId":"user-1","email":"a@example.com","organizationId":"org-1"} + }`)) + if err != nil { + t.Fatal(err) + } + if identity.UserID != "user-1" || identity.Email != "a@example.com" || identity.TeamID != "org-1" { + t.Fatalf("identity = %#v", identity) + } +} diff --git a/backend/internal/infra/provider/web/quota.go b/backend/internal/infra/provider/web/quota.go index 44befbf6..56d29302 100644 --- a/backend/internal/infra/provider/web/quota.go +++ b/backend/internal/infra/provider/web/quota.go @@ -10,6 +10,7 @@ import ( "io" "math" "net/http" + "strings" "time" "github.com/chenyme/grok2api/backend/internal/domain/account" @@ -172,6 +173,11 @@ func (a *Adapter) SyncQuotaMode(ctx context.Context, credential account.Credenti if response.StatusCode == http.StatusUnauthorized { return account.QuotaWindow{}, provider.ErrUnauthorized } + // 403 + blocked-user 与对话封号同源;映射为 ErrUnauthorized 以便额度同步将账号标为失效。 + // 其它 403(如临时 anti-bot)保持普通错误,避免误杀。 + if response.StatusCode == http.StatusForbidden && bodyLooksLikeAccountBlocked(body) { + return account.QuotaWindow{}, fmt.Errorf("%w: account blocked", provider.ErrUnauthorized) + } return account.QuotaWindow{}, fmt.Errorf("Grok Web 额度接口返回 %d", response.StatusCode) } a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) @@ -474,3 +480,10 @@ func parseQuotaBreakdown(message []byte) (account.QuotaBreakdown, bool) { } return result, true } + + +// bodyLooksLikeAccountBlocked 识别额度接口上明确的账号封禁响应(与 gateway AccountBlocked 同信号)。 +func bodyLooksLikeAccountBlocked(body []byte) bool { + text := strings.ToLower(string(body)) + return strings.Contains(text, "blocked-user") || strings.Contains(text, "user is blocked") +} diff --git a/backend/internal/infra/provider/web/quota_test.go b/backend/internal/infra/provider/web/quota_test.go index abf70c51..41312d83 100644 --- a/backend/internal/infra/provider/web/quota_test.go +++ b/backend/internal/infra/provider/web/quota_test.go @@ -143,6 +143,72 @@ func TestSyncQuotaStopsAfterFirstUnauthorizedMode(t *testing.T) { } } + +func TestSyncQuotaBlockedForbiddenIsUnauthorized(t *testing.T) { + var calls atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + calls.Add(1) + writer.Header().Set("Content-Type", "application/json") + writer.WriteHeader(http.StatusForbidden) + _, _ = writer.Write([]byte(`{"code":7,"message":"User is blocked [WKE=unauthorized:blocked-user]","details":[]}`)) + })) + defer server.Close() + + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("blocked-sso") + if err != nil { + t.Fatal(err) + } + adapter := NewAdapter(Config{ + BaseURL: server.URL, StatsigMode: "manual", StatsigManualValue: "test-signature", + }, infraegress.NewManager(egressRepositoryStub{}, cipher), cipher, nil, nil) + _, err = adapter.SyncQuota(context.Background(), account.Credential{ID: 4, WebTier: account.WebTierAuto, EncryptedAccessToken: encrypted}) + if !errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("err = %v, want ErrUnauthorized", err) + } + // manual Statsig mode does not invalidate/retry; SyncQuota stops after the first unauthorized mode. + if calls.Load() != 1 { + t.Fatalf("blocked credential made %d quota requests, want 1", calls.Load()) + } +} + +func TestSyncQuotaGenericForbiddenIsNotUnauthorized(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Type", "application/json") + writer.WriteHeader(http.StatusForbidden) + _, _ = writer.Write([]byte(`{"message":"temporary rejection"}`)) + })) + defer server.Close() + + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("generic-sso") + if err != nil { + t.Fatal(err) + } + adapter := NewAdapter(Config{ + BaseURL: server.URL, StatsigMode: "manual", StatsigManualValue: "test-signature", + }, infraegress.NewManager(egressRepositoryStub{}, cipher), cipher, nil, nil) + _, err = adapter.SyncQuota(context.Background(), account.Credential{ID: 5, WebTier: account.WebTierAuto, EncryptedAccessToken: encrypted}) + if err == nil || errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("err = %v, want generic forbidden error", err) + } +} + +func TestBodyLooksLikeAccountBlocked(t *testing.T) { + if !bodyLooksLikeAccountBlocked([]byte(`{"code":7,"message":"User is blocked [WKE=unauthorized:blocked-user]"}`)) { + t.Fatal("expected blocked body to match") + } + if bodyLooksLikeAccountBlocked([]byte(`{"message":"temporary rejection"}`)) { + t.Fatal("expected generic body not to match") + } +} + func TestInferWebTierFromUpstreamQuota(t *testing.T) { tests := []struct { name string