From a234e3b41d3cac9bfbde29f7c22dd02ca52df027 Mon Sep 17 00:00:00 2001 From: Huan-zhaojun <111294954+Huan-zhaojun@users.noreply.github.com> Date: Fri, 24 Jul 2026 20:42:37 +0800 Subject: [PATCH] fix(web,session): prefer block signals before identity and Statsig retry Treat session status blocked/unauthenticated before accepting identity fields. On Web chat and quota 403, classify blocked-user body before Statsig invalidation retry so definitive ban signals are not dropped. --- .../infra/provider/sessionidentity/session.go | 18 +++++----- .../provider/sessionidentity/session_test.go | 16 +++++++++ backend/internal/infra/provider/web/chat.go | 27 +++++++++++++- backend/internal/infra/provider/web/quota.go | 8 +++-- .../internal/infra/provider/web/quota_test.go | 36 +++++++++++++++++++ 5 files changed, 93 insertions(+), 12 deletions(-) diff --git a/backend/internal/infra/provider/sessionidentity/session.go b/backend/internal/infra/provider/sessionidentity/session.go index 168fc7a2..5fb54b5a 100644 --- a/backend/internal/infra/provider/sessionidentity/session.go +++ b/backend/internal/infra/provider/sessionidentity/session.go @@ -96,6 +96,15 @@ func Parse(body []byte) (provider.AccountIdentity, error) { if err := json.Unmarshal(body, &value); err != nil { return provider.AccountIdentity{}, fmt.Errorf("解析 Grok Session: %w", err) } + // unauthenticated / blocked 表示当前 SSO 对上游不可用,必须在采纳身份字段之前判定, + // 避免 status=blocked 仍携带 userId/email 时被当成有效身份继续调度。 + status := strings.TrimSpace(value.Status) + 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) + } identity := provider.AccountIdentity{ UserID: firstNonEmpty(value.Session.UserID, value.User.ID, value.User.UserID, value.User.Sub, value.ID, value.UserID, value.Sub), Email: firstNonEmpty(value.Session.Email, value.User.Email, value.Email), @@ -105,15 +114,6 @@ func Parse(body []byte) (provider.AccountIdentity, error) { identity.Email = strings.TrimSpace(identity.Email) identity.TeamID = strings.TrimSpace(identity.TeamID) if identity.UserID == "" && identity.Email == "" { - 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 index a26a30bd..78f11f2a 100644 --- a/backend/internal/infra/provider/sessionidentity/session_test.go +++ b/backend/internal/infra/provider/sessionidentity/session_test.go @@ -15,6 +15,14 @@ func TestParseBlockedSessionIsUnauthorized(t *testing.T) { } } +func TestParseBlockedSessionWithIdentityFieldsIsUnauthorized(t *testing.T) { + t.Parallel() + _, err := Parse([]byte(`{"status":"blocked","userId":"user-1","email":"a@example.com","session":{"userId":"user-1","email":"a@example.com"}}`)) + if !errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("err = %v, want ErrUnauthorized even when identity fields are present", err) + } +} + func TestParseUnauthenticatedSessionIsUnauthorized(t *testing.T) { t.Parallel() _, err := Parse([]byte(`{"status":"unauthenticated"}`)) @@ -23,6 +31,14 @@ func TestParseUnauthenticatedSessionIsUnauthorized(t *testing.T) { } } +func TestParseUnauthenticatedSessionWithIdentityFieldsIsUnauthorized(t *testing.T) { + t.Parallel() + _, err := Parse([]byte(`{"status":"unauthenticated","userId":"user-1","email":"a@example.com"}`)) + if !errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("err = %v, want ErrUnauthorized even when identity fields are present", err) + } +} + func TestParseMissingIdentityWithoutStatusStaysGeneric(t *testing.T) { t.Parallel() _, err := Parse([]byte(`{}`)) diff --git a/backend/internal/infra/provider/web/chat.go b/backend/internal/infra/provider/web/chat.go index 29adfac2..865ea2e1 100644 --- a/backend/internal/infra/provider/web/chat.go +++ b/backend/internal/infra/provider/web/chat.go @@ -185,10 +185,35 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response previous = currentPrevious if upstream.StatusCode < 200 || upstream.StatusCode >= 300 { if upstream.StatusCode == http.StatusForbidden { + // 先读正文:blocked-user 必须直接交给 gateway 标失效,禁止 Statsig 重试吞掉首包。 + body, readErr := io.ReadAll(io.LimitReader(upstream.Body, 4<<20)) + _ = upstream.Body.Close() + if readErr != nil { + lease.Release() + return nil, readErr + } + if bodyLooksLikeAccountBlocked(body) { + return &provider.Response{ + StatusCode: upstream.StatusCode, Status: upstream.Status, Header: http.Header(upstream.Header), + UpstreamURL: responseUpstreamURL(upstream), + Body: &releaseBody{ReadCloser: io.NopCloser(bytes.NewReader(body)), release: func() { + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, upstream.StatusCode, nil) + lease.Release() + }}, + }, nil + } if attempt == 0 && a.invalidateSignedStatsig(http.MethodPost, statsigTarget) { - a.releaseStatsigRetry(upstream, lease) + lease.Release() continue } + return &provider.Response{ + StatusCode: upstream.StatusCode, Status: upstream.Status, Header: http.Header(upstream.Header), + UpstreamURL: responseUpstreamURL(upstream), + Body: &releaseBody{ReadCloser: io.NopCloser(bytes.NewReader(body)), release: func() { + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, upstream.StatusCode, nil) + lease.Release() + }}, + }, nil } return &provider.Response{ StatusCode: upstream.StatusCode, Status: upstream.Status, Header: http.Header(upstream.Header), diff --git a/backend/internal/infra/provider/web/quota.go b/backend/internal/infra/provider/web/quota.go index 56d29302..f211bca0 100644 --- a/backend/internal/infra/provider/web/quota.go +++ b/backend/internal/infra/provider/web/quota.go @@ -162,6 +162,11 @@ func (a *Adapter) SyncQuotaMode(ctx context.Context, credential account.Credenti return account.QuotaWindow{}, err } if response.StatusCode == http.StatusForbidden { + // 封号正文优先于 Statsig 重试:首包 blocked-user 不得因 invalidate 被丢弃。 + if bodyLooksLikeAccountBlocked(body) { + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) + return account.QuotaWindow{}, fmt.Errorf("%w: account blocked", provider.ErrUnauthorized) + } if attempt == 0 && a.invalidateSignedStatsig(http.MethodPost, endpoint) { continue } @@ -173,8 +178,7 @@ 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)保持普通错误,避免误杀。 + // 循环内已处理封号 403;此处兜底防止路径遗漏。 if response.StatusCode == http.StatusForbidden && bodyLooksLikeAccountBlocked(body) { return account.QuotaWindow{}, fmt.Errorf("%w: account blocked", provider.ErrUnauthorized) } diff --git a/backend/internal/infra/provider/web/quota_test.go b/backend/internal/infra/provider/web/quota_test.go index 41312d83..ad1f775b 100644 --- a/backend/internal/infra/provider/web/quota_test.go +++ b/backend/internal/infra/provider/web/quota_test.go @@ -175,6 +175,42 @@ func TestSyncQuotaBlockedForbiddenIsUnauthorized(t *testing.T) { } } +func TestSyncQuotaBlockedForbiddenSkipsStatsigRetryInURLMode(t *testing.T) { + var rateLimitCalls atomic.Int64 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + // URL mode may also probe the base URL for Statsig meta; only count quota endpoint. + if request.URL.Path == "/rest/rate-limits" { + rateLimitCalls.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":[]}`)) + return + } + http.NotFound(writer, request) + })) + 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-url") + if err != nil { + t.Fatal(err) + } + // URL mode would invalidate Statsig and retry unless blocked body is classified first. + adapter := NewAdapter(Config{ + BaseURL: server.URL, StatsigMode: "url", StatsigSignerURL: "https://signer.example/sign", + }, infraegress.NewManager(egressRepositoryStub{}, cipher), cipher, nil, nil) + _, err = adapter.SyncQuota(context.Background(), account.Credential{ID: 6, WebTier: account.WebTierAuto, EncryptedAccessToken: encrypted}) + if !errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("err = %v, want ErrUnauthorized", err) + } + if rateLimitCalls.Load() != 1 { + t.Fatalf("blocked credential made %d rate-limits requests, want 1 (no Statsig retry)", rateLimitCalls.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")