fix(gateway): enforce composite model ownership in legacy scheduling

This commit is contained in:
wucm667 committed 2026-09-23 15:29:11 +08:00
1 parent e878ab710f
commit 453b796df0
2 files changed
+133

No files matched your search

@@ -3927,3 +3927,126 @@ func TestOpenAIGatewayService_SelectAccountWithScheduler_SubscriptionPriorityWai
require.Equal(t, int64(38011), selection.WaitPlan.AccountID)
require.Equal(t, openAIAccountScheduleLayerLoadBalance, decision.Layer)
}
func TestOpenAIGatewayService_SelectAccountWithScheduler_LegacyAccountModelRouteExcludesNonOwner(t *testing.T) {
resetOpenAIAdvancedSchedulerSettingCacheForTest()
ctx := context.Background()
groupID := int64(1010713)
owner := Account{
ID: 371031, Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 10,
GroupIDs: []int64{groupID},
Credentials: map[string]any{"model_mapping": map[string]any{"team-alias": "gpt-5.1"}},
// WS transport must be resolvable for the websocket sub-case so the
// ownership filter, not transport admission, is the behavior under test.
Extra: map[string]any{"responses_websockets_v2_enabled": true},
}
nonOwner := Account{
ID: 371032, Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 0,
GroupIDs: []int64{groupID},
Extra: map[string]any{"responses_websockets_v2_enabled": true},
}
repo := schedulerTestOpenAIAccountRepo{accounts: []Account{owner, nonOwner}}
ownership, err := (&GatewayService{accountRepo: repo}).resolveCompositeModelOwnership(ctx, groupID, "team-alias")
require.NoError(t, err)
require.Equal(t, CompositeModelOwnership{TargetPlatform: PlatformOpenAI, Matched: true}, ownership)
ctx = WithCompositeRouteDecision(ctx, CompositeRouteDecision{
Matched: true, Source: CompositeRouteSourceAccount, GroupID: groupID,
PublicModel: "team-alias", TargetPlatform: ownership.TargetPlatform, UpstreamModel: "team-alias",
})
for _, tt := range []struct {
name string
requiredTransport OpenAIUpstreamTransport
sessionHash string
sessionBindings map[string]int64
}{
{name: "initial filter excludes non owner", requiredTransport: OpenAIUpstreamTransportAny},
{name: "initial filter excludes non owner for websocket transport", requiredTransport: OpenAIUpstreamTransportResponsesWebsocket},
{name: "non owner sticky hit is rejected", requiredTransport: OpenAIUpstreamTransportAny, sessionHash: "non-owner", sessionBindings: map[string]int64{"openai:non-owner": nonOwner.ID}},
} {
t.Run(tt.name, func(t *testing.T) {
cfg := &config.Config{}
cfg.Gateway.OpenAIWS.Enabled = true
cfg.Gateway.OpenAIWS.APIKeyEnabled = true
cfg.Gateway.OpenAIWS.ResponsesWebsockets = true
svc := &OpenAIGatewayService{
accountRepo: repo,
cache: &schedulerTestGatewayCache{sessionBindings: tt.sessionBindings},
cfg: cfg,
rateLimitService: newOpenAIAdvancedSchedulerRateLimitService("false"),
concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{}),
}
require.Nil(t, svc.getOpenAIAccountScheduler(ctx), "test precondition: advanced scheduler disabled")
selection, _, selectErr := svc.SelectAccountWithScheduler(
ctx, &groupID, "", tt.sessionHash, "team-alias", nil, tt.requiredTransport, false,
)
require.NoError(t, selectErr)
require.NotNil(t, selection)
require.NotNil(t, selection.Account)
require.Equal(t, owner.ID, selection.Account.ID)
if selection.ReleaseFunc != nil {
selection.ReleaseFunc()
}
})
}
}
func TestOpenAIGatewayService_SelectAccountWithScheduler_LegacyAccountModelRouteDBRecheckFailsOverToOwner(t *testing.T) {
resetOpenAIAdvancedSchedulerSettingCacheForTest()
ctx := context.Background()
groupID := int64(1010714)
mapping := map[string]any{"model_mapping": map[string]any{"team-alias": "gpt-5.1"}}
stalePrimary := &Account{
ID: 371041, Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 0,
GroupIDs: []int64{groupID}, Credentials: mapping,
}
staleBackup := &Account{
ID: 371042, Platform: PlatformOpenAI, Type: AccountTypeAPIKey,
Status: StatusActive, Schedulable: true, Concurrency: 1, Priority: 10,
GroupIDs: []int64{groupID}, Credentials: mapping,
}
dbPrimary := *stalePrimary
dbPrimary.Credentials = nil
dbBackup := *staleBackup
repo := schedulerTestOpenAIAccountRepo{accounts: []Account{dbPrimary, dbBackup}}
ctx = WithCompositeRouteDecision(ctx, CompositeRouteDecision{
Matched: true, Source: CompositeRouteSourceAccount, GroupID: groupID,
PublicModel: "team-alias", TargetPlatform: PlatformOpenAI, UpstreamModel: "team-alias",
})
acquiredIDs, releasedIDs := []int64{}, []int64{}
cfg := &config.Config{RunMode: config.RunModeStandard}
svc := &OpenAIGatewayService{
accountRepo: repo,
cfg: cfg,
rateLimitService: newOpenAIAdvancedSchedulerRateLimitService("false"),
schedulerSnapshot: &SchedulerSnapshotService{cache: &openAISnapshotCacheStub{
snapshotAccounts: []*Account{stalePrimary, staleBackup},
accountsByID: map[int64]*Account{stalePrimary.ID: stalePrimary, staleBackup.ID: staleBackup},
}},
concurrencyService: NewConcurrencyService(schedulerTestConcurrencyCache{
acquiredIDs: &acquiredIDs, releasedIDs: &releasedIDs,
}),
}
require.Nil(t, svc.getOpenAIAccountScheduler(ctx), "test precondition: advanced scheduler disabled")
selection, _, err := svc.SelectAccountWithScheduler(
ctx, &groupID, "", "", "team-alias", nil, OpenAIUpstreamTransportAny, false,
)
require.NoError(t, err)
require.NotNil(t, selection)
require.NotNil(t, selection.Account)
require.Equal(t, dbBackup.ID, selection.Account.ID)
if containsInt64(acquiredIDs, dbPrimary.ID) {
require.Contains(t, releasedIDs, dbPrimary.ID)
}
require.Contains(t, acquiredIDs, dbBackup.ID)
if selection.ReleaseFunc != nil {
selection.ReleaseFunc()
}
}
@@ -392,6 +392,16 @@ func openAICompatibleAccountEligibilityFailureReasonBeforeProfit(ctx context.Con
if account == nil {
return "account_nil"
}
// account_model composite routes publish an alias that only accounts with an
// explicit model mapping own. Both scheduler modes (advanced and legacy) must
// enforce ownership before any priority/sticky/transport consideration; a
// non-owner would forward the raw public alias and get model_not_found or
// hit an unrelated same-name upstream model.
if source, ok := CompositeRouteSourceFromContext(ctx); ok && source == CompositeRouteSourceAccount {
if publicModel, modelOK := RequestedPublicModelFromContext(ctx); modelOK && !explicitModelMappingClaims(*account, publicModel) {
return "account_model_not_owned"
}
}
if account.Platform != platform || !account.IsOpenAICompatible() {
return "platform_mismatch"
}