mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 08:01:07 +00:00
feat(account): mark SSO invalid on session blocked and quota blocked-user
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
This commit is contained in:
1 parent
4fcc97d939
commit
232fe83207
5 files changed
+135
-2
No files matched your search
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user