mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
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.
This commit is contained in:
1 parent
ba81e8d42a
commit
a234e3b41d
5 files changed
+93
-12
No files matched your search
@@ -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
|
||||
|
||||
@@ -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(`{}`))
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
Reference in new issue
Block a user