mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 16:02:12 +00:00
fix: video job retry can bypass client key account scope
Every other account-selection path (text chat, image generation, voice, voice websocket) threads the requesting client key's AccountScope through to beginSelectionSessionForKey. The video job's background retry/recovery worker (runVideoJob) used the unscoped beginSelectionSession instead, so once the job's originally pinned account failed, the fallback search for a replacement ignored the client key's provider/tier restrictions entirely. A client key restricted to e.g. Super-tier accounts could end up consuming a Free-tier (or wrong-provider) account's quota purely because its pinned account hit a transient failure, silently widening access beyond what the key was configured to allow. media.Job already stores ClientKeyID, so the fix looks up that key and passes its AccountScope into beginSelectionSessionForKey, matching every other selection path. Added a regression test (TestVideoRetryDoesNotEscapeClientKeyAccountScope) that fails against the prior code (confirmed: the out-of-scope account was used) and passes with the fix.
This commit is contained in:
1 parent
7c889a960e
commit
31bbe64dc9
2 files changed
+118
-1
No files matched your search
@@ -531,6 +531,22 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
|
||||
quotaMode := videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), job.Quality)
|
||||
quotaRefreshGroup := s.providers.QuotaRefreshGroup(route.Provider, route.UpstreamModel)
|
||||
// The initial creation path (selectSchedulableEligibleMediaRouteWithQuotaMode,
|
||||
// called from CreateVideoJob) always scopes account selection to the
|
||||
// requesting client key's AccountScope. A retry here must not silently
|
||||
// widen that: falling back to the unscoped account pool would let a key
|
||||
// restricted to e.g. free-tier/web-only accounts consume a premium or
|
||||
// console/build-only account's quota purely because its originally
|
||||
// pinned account had a transient failure.
|
||||
accountScope := clientkey.AccountScope{}
|
||||
if job.ClientKeyID > 0 {
|
||||
key, keyErr := s.clientKeys.Get(ctx, job.ClientKeyID)
|
||||
if keyErr != nil {
|
||||
s.failVideoJob(ctx, job, "client_key_unavailable", keyErr, 0, nil)
|
||||
return
|
||||
}
|
||||
accountScope = key.AccountScope()
|
||||
}
|
||||
attemptPolicy := s.videoAttemptPolicy()
|
||||
excluded := make(map[uint64]bool)
|
||||
forbiddenEgressRetried := make(map[uint64]bool)
|
||||
@@ -564,7 +580,7 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
|
||||
}
|
||||
if lease == nil {
|
||||
if selection == nil {
|
||||
selection, err = s.selector.beginSelectionSession(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false)
|
||||
selection, err = s.selector.beginSelectionSessionForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false, accountScope)
|
||||
}
|
||||
if err == nil {
|
||||
lease, err = selection.Acquire(ctx, excluded, false)
|
||||
|
||||
@@ -900,3 +900,104 @@ func TestVideoWebForbiddenRetriesPinnedAccountOnceThenFailsOver(t *testing.T) {
|
||||
t.Fatalf("unclassified failed job = %#v", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// The initial creation path (CreateVideoJob) always scopes account selection
|
||||
// to the requesting client key's AccountScope. This confirms the retry path
|
||||
// inside runVideoJob does not silently widen that scope when the originally
|
||||
// pinned account fails: a key restricted to Super-tier accounts must never
|
||||
// fail over to a Free-tier account, even though one is available in the pool.
|
||||
func TestVideoRetryDoesNotEscapeClientKeyAccountScope(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "video-retry-scope.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer database.Close()
|
||||
if err := database.InitializeSchema(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
accountRepo := relational.NewAccountRepository(database)
|
||||
modelRepo := relational.NewModelRepository(database)
|
||||
auditRepo := relational.NewAuditRepository(database)
|
||||
mediaRepo := relational.NewMediaJobRepository(database)
|
||||
keyRepo := relational.NewClientKeyRepository(database)
|
||||
key, err := keyRepo.Create(ctx, clientkey.Key{
|
||||
Name: "video-scope-test", Prefix: "video-scope-test", SecretHash: strings.Repeat("b", 64),
|
||||
EncryptedSecret: "encrypted", Enabled: true, RPMLimit: 60, MaxConcurrent: 4,
|
||||
// Restricted to Super-tier Web accounts only.
|
||||
ProviderScope: clientkey.ProviderScopeWeb, TierScope: clientkey.TierScopeSuper,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
createAccount := func(name string, tier account.WebTier, priority int) account.Credential {
|
||||
credential, _, createErr := accountRepo.UpsertByIdentity(ctx, account.Credential{
|
||||
Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, WebTier: tier,
|
||||
Name: name, SourceKey: name, EncryptedAccessToken: name + "-token", ExpiresAt: time.Now().Add(time.Hour),
|
||||
Enabled: true, AuthStatus: account.AuthStatusActive, Priority: priority, MaxConcurrent: 1,
|
||||
})
|
||||
if createErr != nil {
|
||||
t.Fatal(createErr)
|
||||
}
|
||||
return credential
|
||||
}
|
||||
// pinned is the Super-tier account the job was originally created against
|
||||
// (in scope); outOfScope is a Free-tier account that must never be used
|
||||
// for this key, even as a failover target.
|
||||
pinned := createAccount("pinned-super", account.WebTierSuper, 200)
|
||||
outOfScope := createAccount("free-out-of-scope", account.WebTierBasic, 100)
|
||||
if err := modelRepo.UpsertDiscovered(ctx, account.ProviderWeb, []string{"grok-imagine-video"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, accountID := range []uint64{pinned.ID, outOfScope.ID} {
|
||||
if err := modelRepo.ReplaceAccountCapabilities(ctx, accountID, []string{"grok-imagine-video"}, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
route, err := modelRepo.GetByProviderUpstream(ctx, account.ProviderWeb, "grok-imagine-video")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// The pinned account always fails (forbidden), forcing the retry path to
|
||||
// look for a replacement. Without the fix, that replacement search ignores
|
||||
// the client key's scope entirely and would pick the Free-tier account.
|
||||
adapter := &videoCreateFailoverAdapter{
|
||||
failures: map[uint64]int{pinned.ID: 999},
|
||||
status: http.StatusForbidden,
|
||||
}
|
||||
registry := provider.NewRegistry(adapter)
|
||||
sticky := memory.NewStickyStore()
|
||||
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
|
||||
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
|
||||
service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(keyRepo, nil, nil, 60, 4, nil), registry, selector, nil, 3)
|
||||
service.ConfigureMedia(mediaRepo, 1)
|
||||
service.UpdateVideoMaxAttempts(3)
|
||||
|
||||
now := time.Now().UTC()
|
||||
job := media.Job{
|
||||
ID: "video_scope_retry", RequestID: "request-video-scope-retry", ClientKeyID: key.ID, ClientKeyName: key.Name,
|
||||
AccountID: pinned.ID, AccountName: pinned.Name, Provider: string(account.ProviderWeb),
|
||||
Model: route.PublicID, ModelRouteID: route.ID, UpstreamModel: route.UpstreamModel,
|
||||
Operation: provider.VideoOperationGenerate, Prompt: "test", Seconds: 5, Quality: "720p",
|
||||
Status: media.StatusInProgress, InputJSON: `{}`, CreatedAt: now, UpdatedAt: now,
|
||||
}
|
||||
if err := mediaRepo.CreateMediaJob(ctx, job); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.runVideoJob(ctx, job, route)
|
||||
|
||||
for _, attemptedAccountID := range adapter.Attempts() {
|
||||
if attemptedAccountID == outOfScope.ID {
|
||||
t.Fatalf("out-of-scope Free-tier account %d was used for a key scoped to Super tier only", outOfScope.ID)
|
||||
}
|
||||
}
|
||||
stored, err := mediaRepo.GetMediaJob(ctx, job.ID, job.ClientKeyID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored.Status != media.StatusFailed {
|
||||
t.Fatalf("expected the job to fail rather than complete via an out-of-scope account, got %#v", stored)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user