From 0a1a0b9140fb0d925fdfc2d7a379e94fe5e876f8 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 01:54:48 +0800 Subject: [PATCH 01/26] feat: validate gateway account identity and explicit group bindings Refs #959. Store gateway accounts under an account-only platform with a new_api/sub2api credential kind. Validate create, update and import before writes, enforce OAuth-only membership policy in shared repository binding paths, and keep scheduling and forwarding closed pending the complete four-protocol contract. Add management, DTO, repository and isolated database regression sources; dynamic validation is remote CI only. --- .../workflows/issue959-gateway-regression.yml | 18 +- backend/internal/domain/constants.go | 3 + .../internal/handler/admin/account_data.go | 5 +- .../admin/account_gateway_data_test.go | 24 +++ .../internal/handler/admin/account_handler.go | 4 +- .../handler/dto/account_mapper_redact_test.go | 11 ++ backend/internal/repository/account_repo.go | 30 ++- .../gateway_account_group_bindings_test.go | 40 ++++ ...way_account_management_integration_test.go | 57 ++++++ backend/internal/repository/group_repo.go | 52 ++++- .../oauth_degradation_group_bindings.go | 53 ++++- .../oauth_degradation_group_bindings_test.go | 2 +- backend/internal/service/account.go | 5 + backend/internal/service/account_service.go | 35 ++++ .../internal/service/account_test_service.go | 3 + backend/internal/service/admin_account.go | 59 +++++- .../service/antigravity_gateway_claude.go | 3 + .../service/antigravity_gateway_gemini.go | 3 + .../service/antigravity_gateway_upstream.go | 3 + backend/internal/service/gateway_account.go | 100 ++++++++++ .../gateway_account_management_test.go | 186 ++++++++++++++++++ backend/internal/service/gateway_forward.go | 3 + .../service/gemini_messages_compat_service.go | 6 + .../openai_gateway_chat_completions.go | 3 + .../service/openai_gateway_count_tokens.go | 6 + .../service/openai_gateway_forward.go | 3 + .../service/openai_gateway_messages.go | 3 + 27 files changed, 699 insertions(+), 21 deletions(-) create mode 100644 backend/internal/handler/admin/account_gateway_data_test.go create mode 100644 backend/internal/repository/gateway_account_group_bindings_test.go create mode 100644 backend/internal/repository/gateway_account_management_integration_test.go create mode 100644 backend/internal/service/gateway_account_management_test.go diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index 4d605ddd5661..7fc1f308a202 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -7,6 +7,12 @@ on: paths: - 'backend/internal/domain/constants.go' - 'backend/internal/service/**' + - 'backend/internal/handler/admin/account*' + - 'backend/internal/handler/dto/account_mapper_redact_test.go' + - 'backend/internal/repository/account_repo.go' + - 'backend/internal/repository/group_repo.go' + - 'backend/internal/repository/gateway_account*' + - 'backend/internal/repository/oauth_degradation_group_bindings*' - 'backend/internal/repository/concurrency_cache*' - 'backend/internal/repository/integration_harness_test.go' - 'backend/go.mod' @@ -66,8 +72,8 @@ jobs: shell: bash run: | set -euo pipefail - go test -race -tags=unit ./internal/service \ - -run '^Test(GatewayIdentity|GatewayUsage|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots)' \ + go test -race -tags=unit ./internal/service ./internal/handler/admin ./internal/handler/dto ./internal/repository \ + -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots)' \ -count=1 -v -timeout=10m 2>&1 | tee ../evidence/unit-race.log if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/unit-race.log; then exit 1 @@ -75,18 +81,24 @@ jobs: grep -F -- '--- PASS: TestGatewayUsageWritersSnapshotRequestTarget' ../evidence/unit-race.log grep -F -- '--- PASS: TestNewAPIGatewayCostsFollowRequestTargetWithoutSharedWrites' ../evidence/unit-race.log grep -F -- '--- PASS: TestUsagePlatformSnapshotsSelectedAccount' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayManagementForwardingRemainsClosed' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayManagementRepositoryBindingGuard' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayDataImportIdentityValidation' ../evidence/unit-race.log + grep -F -- '--- PASS: TestAccountGatewayDTORedactsCallingKey' ../evidence/unit-race.log - name: Shared account slots against isolated Redis working-directory: backend shell: bash run: | set -euo pipefail go test -race -tags=integration ./internal/repository \ - -run '^TestConcurrencyCacheSuite$/^TestGatewayTargetsShareAccountConcurrency$' \ + -run '^Test(ConcurrencyCacheSuite|AccountRepoSuite)$/^TestGateway(TargetsShareAccountConcurrency|ManagementAtomicMembershipAndOAuthExclusion)$' \ -count=1 -v -timeout=10m 2>&1 | tee ../evidence/concurrency-redis.log if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/concurrency-redis.log; then exit 1 fi grep -F -- '--- PASS: TestConcurrencyCacheSuite/TestGatewayTargetsShareAccountConcurrency' ../evidence/concurrency-redis.log + grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayManagementAtomicMembershipAndOAuthExclusion' ../evidence/concurrency-redis.log - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go index 760ab31c37aa..718087c50f27 100644 --- a/backend/internal/domain/constants.go +++ b/backend/internal/domain/constants.go @@ -44,6 +44,9 @@ const ( PlatformComposite = "composite" ) +// PlatformGateway is an account-only identity, never a request or group platform. +const PlatformGateway = "gateway" + // Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。 // 存储于 credentials["account_mode"],决定 base_url 预设与额度监控方式。 const ( diff --git a/backend/internal/handler/admin/account_data.go b/backend/internal/handler/admin/account_data.go index 84161ab27039..f2a8f559fef9 100644 --- a/backend/internal/handler/admin/account_data.go +++ b/backend/internal/handler/admin/account_data.go @@ -830,6 +830,9 @@ func validateDataProxy(item DataProxy) error { } func validateDataAccount(item DataAccount) error { + if err := service.ValidateGatewayAccountIdentity(item.Platform, item.Type, item.Credentials); err != nil { + return err + } if strings.TrimSpace(item.Name) == "" { return errors.New("account name is required") } @@ -843,7 +846,7 @@ func validateDataAccount(item DataAccount) error { return errors.New("account credentials is required") } switch item.Type { - case service.AccountTypeOAuth, service.AccountTypeSetupToken, service.AccountTypeAPIKey, service.AccountTypeUpstream: + case service.AccountTypeOAuth, service.AccountTypeSetupToken, service.AccountTypeAPIKey, service.AccountTypeUpstream, service.AccountTypeGateway: default: return fmt.Errorf("account type is invalid: %s", item.Type) } diff --git a/backend/internal/handler/admin/account_gateway_data_test.go b/backend/internal/handler/admin/account_gateway_data_test.go new file mode 100644 index 000000000000..840a9aa8cd74 --- /dev/null +++ b/backend/internal/handler/admin/account_gateway_data_test.go @@ -0,0 +1,24 @@ +package admin + +import ( + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin/binding" + "github.com/stretchr/testify/require" +) + +func TestGatewayDataImportIdentityValidation(t *testing.T) { + item := DataAccount{Name: "Gateway import fixture", Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Credentials: map[string]any{"upstream_kind": "sub2api", "base_url": "https://import.example", "api_key": "synthetic-key"}} + require.NoError(t, validateDataAccount(item)) + require.NoError(t, binding.Validator.ValidateStruct(CreateAccountRequest{Name: item.Name, Platform: item.Platform, Type: item.Type, Credentials: item.Credentials})) + require.NoError(t, binding.Validator.ValidateStruct(UpdateAccountRequest{Type: item.Type})) + item.Platform = service.PlatformOpenAI + require.Error(t, validateDataAccount(item)) + item.Platform = service.PlatformGateway + item.Credentials["upstream_kind"] = "unknown" + require.Error(t, validateDataAccount(item)) + item.Type = service.AccountTypeAPIKey + require.Error(t, validateDataAccount(item)) +} diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index c9379ff13156..858ed72e44f0 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -148,7 +148,7 @@ type CreateAccountRequest struct { Name string `json:"name" binding:"required"` Notes *string `json:"notes"` Platform string `json:"platform" binding:"required"` - Type string `json:"type" binding:"required,oneof=oauth setup-token apikey upstream bedrock service_account"` + Type string `json:"type" binding:"required,oneof=oauth setup-token apikey upstream bedrock service_account gateway"` Credentials map[string]any `json:"credentials" binding:"required"` Extra map[string]any `json:"extra"` ProxyID *int64 `json:"proxy_id"` @@ -170,7 +170,7 @@ type UpdateAccountRequest struct { Platform string `json:"platform"` Name string `json:"name"` Notes *string `json:"notes"` - Type string `json:"type" binding:"omitempty,oneof=oauth setup-token apikey upstream bedrock service_account"` + Type string `json:"type" binding:"omitempty,oneof=oauth setup-token apikey upstream bedrock service_account gateway"` Credentials map[string]any `json:"credentials"` Extra map[string]any `json:"extra"` ProxyID *int64 `json:"proxy_id"` diff --git a/backend/internal/handler/dto/account_mapper_redact_test.go b/backend/internal/handler/dto/account_mapper_redact_test.go index 44354844eb84..ec897f6431a2 100644 --- a/backend/internal/handler/dto/account_mapper_redact_test.go +++ b/backend/internal/handler/dto/account_mapper_redact_test.go @@ -11,6 +11,17 @@ import ( "github.com/Wei-Shaw/sub2api/internal/service" ) +func TestAccountGatewayDTORedactsCallingKey(t *testing.T) { + account := &service.Account{Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example", "api_key": "synthetic-gateway-secret"}} + got := AccountFromServiceShallow(account) + require.Equal(t, "new_api", got.Credentials["upstream_kind"]) + require.True(t, got.CredentialsStatus["has_api_key"]) + raw, err := json.Marshal(got) + require.NoError(t, err) + require.NotContains(t, string(raw), "synthetic-gateway-secret") +} + func TestAccountFromServiceShallow_RedactsSensitiveCredentials(t *testing.T) { src := &service.Account{ ID: 42, diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index b72964834b3d..3f925f57fbc7 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -179,6 +179,12 @@ func createAccountRecord(ctx context.Context, client *dbent.Client, account *ser if account == nil { return service.ErrAccountNilInput } + if err := service.ValidateGatewayAccountIdentity(account.Platform, account.Type, account.Credentials); err != nil { + return err + } + if account.IsGateway() { + account.Schedulable = false + } account.Extra = copyJSONMap(account.Extra) delete(account.Extra, service.OAuthDegradationActionExtraKey) @@ -344,6 +350,9 @@ func (r *accountRepository) CreateWithAccountGroups(ctx context.Context, account return err } + if err := validateGatewayGroupBindings(ctx, txClient, account, groupIDs); err != nil { + return err + } if err := createAccountRecord(ctx, txClient, account); err != nil { return err } @@ -656,6 +665,9 @@ func (r *accountRepository) updateLockedAccount( explicitRateSyncEnabled *bool, explicitRateMultiplier *float64, ) (*dbent.Account, error) { + if err := service.ValidateGatewayAccountIdentity(account.Platform, account.Type, account.Credentials); err != nil { + return nil, err + } extra, err := lockAndMergeAccountProbeExtra(ctx, client, account, explicitProbeEnabled, explicitRateSyncEnabled) if err != nil { return nil, err @@ -695,6 +707,9 @@ func (r *accountRepository) updateLockedAccount( if !preserveOAuthErrorScheduling && (!accounttimer.PreserveSchedulable(ctx) || account.Status == service.StatusError) { builder.SetSchedulable(schedulable) } + if account.IsGateway() { + builder.SetSchedulable(false) + } if explicitRateMultiplier != nil { builder.SetRateMultiplier(*explicitRateMultiplier) @@ -2594,6 +2609,8 @@ func (r *accountRepository) schedulableAccountsQuery(now time.Time) *dbent.Accou Where( dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true), + dbaccount.TypeNEQ(service.AccountTypeGateway), + dbaccount.PlatformNEQ(service.PlatformGateway), tempUnschedulablePredicate(), notExpiredPredicate(now), dbaccount.Or(dbaccount.OverloadUntilIsNil(), dbaccount.OverloadUntilLTE(now)), @@ -2652,6 +2669,7 @@ func (r *accountRepository) ListSchedulableCapacityByGroupIDs(ctx context.Contex AND a.deleted_at IS NULL AND a.status = $2 AND a.schedulable = TRUE + AND a.type <> 'gateway' AND a.platform <> 'gateway' AND (a.temp_unschedulable_until IS NULL OR a.temp_unschedulable_until <= $3) AND (a.expires_at IS NULL OR a.expires_at > $3 OR a.auto_pause_on_expired = FALSE) AND (a.overload_until IS NULL OR a.overload_until <= $3) @@ -2700,6 +2718,8 @@ func (r *accountRepository) ListSchedulableByPlatform(ctx context.Context, platf dbaccount.PlatformEQ(platform), dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true), + dbaccount.TypeNEQ(service.AccountTypeGateway), + dbaccount.PlatformNEQ(service.PlatformGateway), tempUnschedulablePredicate(), notExpiredPredicate(now), dbaccount.Or(dbaccount.OverloadUntilIsNil(), dbaccount.OverloadUntilLTE(now)), @@ -2734,6 +2754,8 @@ func (r *accountRepository) ListSchedulableByPlatforms(ctx context.Context, plat dbaccount.PlatformIn(platforms...), dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true), + dbaccount.TypeNEQ(service.AccountTypeGateway), + dbaccount.PlatformNEQ(service.PlatformGateway), tempUnschedulablePredicate(), notExpiredPredicate(now), dbaccount.Or(dbaccount.OverloadUntilIsNil(), dbaccount.OverloadUntilLTE(now)), @@ -2754,6 +2776,8 @@ func (r *accountRepository) ListSchedulableUngroupedByPlatform(ctx context.Conte dbaccount.PlatformEQ(platform), dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true), + dbaccount.TypeNEQ(service.AccountTypeGateway), + dbaccount.PlatformNEQ(service.PlatformGateway), dbaccount.Not(dbaccount.HasAccountGroups()), tempUnschedulablePredicate(), notExpiredPredicate(now), @@ -2778,6 +2802,8 @@ func (r *accountRepository) ListSchedulableUngroupedByPlatforms(ctx context.Cont dbaccount.PlatformIn(platforms...), dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true), + dbaccount.TypeNEQ(service.AccountTypeGateway), + dbaccount.PlatformNEQ(service.PlatformGateway), dbaccount.Not(dbaccount.HasAccountGroups()), tempUnschedulablePredicate(), notExpiredPredicate(now), @@ -2829,6 +2855,8 @@ func (r *accountRepository) ListModelAvailabilityCandidates( preds := []dbpredicate.Account{ dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true), + dbaccount.TypeNEQ(service.AccountTypeGateway), + dbaccount.PlatformNEQ(service.PlatformGateway), dbaccount.PlatformIn(platforms...), } if !includeGrouped { @@ -4047,7 +4075,7 @@ func (r *accountRepository) queryAccountsByGroup(ctx context.Context, groupID in preds = append(preds, dbaccount.PlatformIn(opts.platforms...)) } if opts.schedulable { - preds = append(preds, dbaccount.SchedulableEQ(true)) + preds = append(preds, dbaccount.SchedulableEQ(true), dbaccount.TypeNEQ(service.AccountTypeGateway), dbaccount.PlatformNEQ(service.PlatformGateway)) if !opts.ignoreTransientState { now := time.Now() preds = append(preds, diff --git a/backend/internal/repository/gateway_account_group_bindings_test.go b/backend/internal/repository/gateway_account_group_bindings_test.go new file mode 100644 index 000000000000..98786948ea0d --- /dev/null +++ b/backend/internal/repository/gateway_account_group_bindings_test.go @@ -0,0 +1,40 @@ +package repository + +import ( + "context" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestGatewayManagementRepositoryBindingGuard(t *testing.T) { + for _, policy := range []string{"explicit-mixed", "oauth-only", "missing", "invalid-platform"} { + t.Run(policy, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { _ = db.Close() }() + mock.ExpectQuery(`SELECT COALESCE\(extra,.*FROM accounts.*FOR NO KEY UPDATE`).WithArgs(int64(959)). + WillReturnRows(sqlmock.NewRows([]string{"extra", "platform", "type"}).AddRow(`{}`, service.PlatformGateway, service.AccountTypeGateway)) + rows := sqlmock.NewRows([]string{"id", "platform", "require_oauth_only"}).AddRow(1, service.PlatformOpenAI, false) + switch policy { + case "explicit-mixed": + rows.AddRow(2, service.PlatformAnthropic, false) + case "oauth-only": + rows.AddRow(2, service.PlatformComposite, true) + case "invalid-platform": + rows.AddRow(2, service.PlatformGateway, false) + } + mock.ExpectQuery(`SELECT id,platform,require_oauth_only FROM groups`).WithArgs("[1,2]").WillReturnRows(rows) + ids, err := lockOAuthDegradationGroupBindings(context.Background(), db, 959, []int64{1, 2}) + if policy == "explicit-mixed" { + require.NoError(t, err) + require.Equal(t, []int64{1, 2}, ids) + } else { + require.ErrorIs(t, err, service.ErrGatewayAccountGroup) + } + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/backend/internal/repository/gateway_account_management_integration_test.go b/backend/internal/repository/gateway_account_management_integration_test.go new file mode 100644 index 000000000000..c445714c8c96 --- /dev/null +++ b/backend/internal/repository/gateway_account_management_integration_test.go @@ -0,0 +1,57 @@ +//go:build integration + +package repository + +import "github.com/Wei-Shaw/sub2api/internal/service" + +func (s *AccountRepoSuite) TestGatewayManagementAtomicMembershipAndOAuthExclusion() { + openai, err := s.client.Group.Create().SetName("gateway-openai").SetPlatform(service.PlatformOpenAI).Save(s.ctx) + s.Require().NoError(err) + anthropic, err := s.client.Group.Create().SetName("gateway-anthropic").SetPlatform(service.PlatformAnthropic).Save(s.ctx) + s.Require().NoError(err) + composite, err := s.client.Group.Create().SetName("gateway-composite").SetPlatform(service.PlatformComposite).Save(s.ctx) + s.Require().NoError(err) + oauth, err := s.client.Group.Create().SetName("gateway-oauth-only").SetPlatform(service.PlatformComposite).SetRequireOauthOnly(true).Save(s.ctx) + s.Require().NoError(err) + a := &service.Account{Name: "gateway-account", Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Status: service.StatusActive, Schedulable: true, Concurrency: 2, + Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example", "api_key": "synthetic-key"}} + s.Require().NoError(s.repo.CreateWithAccountGroups(s.ctx, a, []service.AccountGroup{ + {GroupID: openai.ID, Priority: 1}, {GroupID: anthropic.ID, Priority: 2}, {GroupID: composite.ID, Priority: 3}, + })) + stored, err := s.repo.GetByID(s.ctx, a.ID) + s.Require().NoError(err) + s.False(stored.Schedulable) + s.Equal("new_api", stored.Credentials["upstream_kind"]) + s.ElementsMatch([]int64{openai.ID, anthropic.ID, composite.ID}, stored.GroupIDs) + // A manual/stale flag cannot leak this incomplete type into any eligible pool. + s.Require().NoError(s.repo.SetSchedulable(s.ctx, a.ID, true)) + candidates, err := s.repo.ListSchedulableByGroupID(s.ctx, openai.ID) + s.Require().NoError(err) + s.Empty(candidates) + candidates, err = s.repo.ListSchedulable(s.ctx) + s.Require().NoError(err) + for _, candidate := range candidates { + s.NotEqual(a.ID, candidate.ID) + } + s.Error(s.repo.BindGroups(s.ctx, a.ID, []int64{openai.ID, oauth.ID})) + s.Error(s.repo.AddToGroup(s.ctx, a.ID, oauth.ID, 1)) + groups := newGroupRepositoryWithSQL(s.client, s.repo.sql) + s.Error(groups.BindAccountsToGroup(s.ctx, oauth.ID, []int64{a.ID})) + rejected := *a + rejected.ID = 0 + rejected.Name = "rejected-gateway" + s.Error(s.repo.CreateWithAccountGroups(s.ctx, &rejected, []service.AccountGroup{{GroupID: oauth.ID, Priority: 1}})) + s.Zero(rejected.ID, "rejected group policy is checked before inserting the account") + stored, err = s.repo.GetByID(s.ctx, a.ID) + s.Require().NoError(err) + s.ElementsMatch([]int64{openai.ID, anthropic.ID, composite.ID}, stored.GroupIDs, "rejection preserves prior explicit memberships") + s.Require().NoError(s.repo.BindGroups(s.ctx, a.ID, []int64{anthropic.ID})) + stored, err = s.repo.GetByID(s.ctx, a.ID) + s.Require().NoError(err) + s.Equal([]int64{anthropic.ID}, stored.GroupIDs, "removal does not infer other platform memberships") + group, err := groups.GetByID(s.ctx, anthropic.ID) + s.Require().NoError(err) + group.RequireOAuthOnly = true + s.ErrorIs(groups.Update(s.ctx, group), service.ErrGatewayAccountGroup, "group edits cannot strand a gateway in an OAuth-only group") +} diff --git a/backend/internal/repository/group_repo.go b/backend/internal/repository/group_repo.go index 64a73c4d5f9e..17008625b5db 100644 --- a/backend/internal/repository/group_repo.go +++ b/backend/internal/repository/group_repo.go @@ -237,7 +237,7 @@ func (r *groupRepository) CreateFromSource(ctx context.Context, groupIn *service JOIN accounts a ON a.id = ag.account_id WHERE ag.group_id = $1 AND a.deleted_at IS NULL - AND (NOT $3 OR a.type <> $4) + AND (NOT $3 OR (a.type <> $4 AND a.type <> 'gateway' AND a.platform <> 'gateway')) ON CONFLICT (account_id, group_id) DO NOTHING`, sourceGroupID, groupIn.ID, @@ -289,11 +289,53 @@ func (r *groupRepository) GetByIDLite(ctx context.Context, id int64) (*service.G } func (r *groupRepository) Update(ctx context.Context, groupIn *service.Group) error { + client := r.client + var gatewayTx *dbent.Tx + if groupIn.RequireOAuthOnly { + var err error + gatewayTx, err = client.Tx(ctx) + if err != nil && !errors.Is(err, dbent.ErrTxStarted) { + return err + } + if gatewayTx != nil { + defer func() { _ = gatewayTx.Rollback() }() + client = gatewayTx.Client() + } + // Membership writers hold FOR SHARE on this group. Serialize an OAuth + // restriction edit with them so neither side can bypass the new policy. + rows, err := client.QueryContext(ctx, `SELECT id FROM groups WHERE id=$1 AND deleted_at IS NULL FOR UPDATE`, groupIn.ID) + if err != nil { + return err + } + found := rows.Next() + rowErr := rows.Err() + _ = rows.Close() + if rowErr != nil { + return rowErr + } + if !found { + return service.ErrGroupNotFound + } + rows, err = client.QueryContext(ctx, `SELECT 1 FROM account_groups ag JOIN accounts a ON a.id=ag.account_id + WHERE ag.group_id=$1 AND a.deleted_at IS NULL AND (a.type='gateway' OR a.platform='gateway') LIMIT 1`, groupIn.ID) + if err != nil { + return err + } + hasGateway := rows.Next() + rowErr = rows.Err() + _ = rows.Close() + if rowErr != nil { + return rowErr + } + if hasGateway { + return service.ErrGatewayAccountGroup + } + } modelPricing, err := json.Marshal(groupIn.ModelPricing) if err != nil { return fmt.Errorf("marshal group model pricing: %w", err) } - builder := r.client.Group.UpdateOneID(groupIn.ID). + builder := client.Group.UpdateOneID(groupIn.ID). SetName(groupIn.Name). SetDescription(groupIn.Description). SetPlatform(groupIn.Platform). @@ -459,6 +501,12 @@ func (r *groupRepository) Update(ctx context.Context, groupIn *service.Group) er return translatePersistenceError(err, service.ErrGroupNotFound, service.ErrGroupExists) } groupIn.UpdatedAt = updated.UpdatedAt + if gatewayTx != nil { + if err := enqueueSchedulerOutbox(ctx, client, service.SchedulerOutboxEventGroupChanged, nil, &groupIn.ID, nil); err != nil { + return err + } + return gatewayTx.Commit() + } if err := enqueueSchedulerOutbox(ctx, r.sql, service.SchedulerOutboxEventGroupChanged, nil, &groupIn.ID, nil); err != nil { logger.LegacyPrintf("repository.group", "[SchedulerOutbox] enqueue group update failed: group=%d err=%v", groupIn.ID, err) } diff --git a/backend/internal/repository/oauth_degradation_group_bindings.go b/backend/internal/repository/oauth_degradation_group_bindings.go index ee8d39e26cca..a20a8f742458 100644 --- a/backend/internal/repository/oauth_degradation_group_bindings.go +++ b/backend/internal/repository/oauth_degradation_group_bindings.go @@ -2,6 +2,7 @@ package repository import ( "context" + "encoding/json" "github.com/Wei-Shaw/sub2api/internal/service" ) @@ -10,7 +11,7 @@ import ( // Degradation removes native bindings once; later administrator edits may restore // them. The historical action must never filter an ordinary binding save. func lockOAuthDegradationGroupBindings(ctx context.Context, exec sqlExecutor, accountID int64, proposed []int64) ([]int64, error) { - rows, err := exec.QueryContext(ctx, `SELECT COALESCE(extra,'{}'::jsonb) FROM accounts WHERE id=$1 AND deleted_at IS NULL FOR NO KEY UPDATE`, accountID) + rows, err := exec.QueryContext(ctx, `SELECT COALESCE(extra,'{}'::jsonb), platform, type FROM accounts WHERE id=$1 AND deleted_at IS NULL FOR NO KEY UPDATE`, accountID) if err != nil { return nil, err } @@ -22,8 +23,54 @@ func lockOAuthDegradationGroupBindings(ctx context.Context, exec sqlExecutor, ac return nil, service.ErrAccountNotFound } var raw []byte - if err := rows.Scan(&raw); err != nil { + var platform, kind string + if err := rows.Scan(&raw, &platform, &kind); err != nil { return nil, err } - return proposed, rows.Err() + if err := rows.Err(); err != nil { + return nil, err + } + if err := rows.Close(); err != nil { + return nil, err + } + return proposed, validateGatewayGroupBindings(ctx, exec, &service.Account{Platform: platform, Type: kind}, proposed) +} + +// Recheck live policy under a shared group lock, including indirect writers +// (scoped admin, quality and AI moves) that do not call the usual binding API. +func validateGatewayGroupBindings(ctx context.Context, exec sqlExecutor, a *service.Account, ids []int64) error { + if a == nil || (!a.IsGateway() && a.Platform != service.PlatformGateway) || len(ids) == 0 { + return nil + } + encoded, err := json.Marshal(ids) + if err != nil { + return err + } + rows, err := exec.QueryContext(ctx, `SELECT id,platform,require_oauth_only FROM groups + WHERE id IN (SELECT value::bigint FROM jsonb_array_elements_text($1::jsonb)) AND deleted_at IS NULL + ORDER BY id FOR SHARE`, string(encoded)) + if err != nil { + return err + } + defer func() { _ = rows.Close() }() + seen := make(map[int64]bool, len(ids)) + for rows.Next() { + var group service.Group + if err := rows.Scan(&group.ID, &group.Platform, &group.RequireOAuthOnly); err != nil { + return err + } + if err := service.ValidateGatewayAccountGroup(a, &group); err != nil { + return err + } + seen[group.ID] = true + } + if err := rows.Err(); err != nil { + return err + } + for _, id := range ids { + if !seen[id] { + return service.ErrGatewayAccountGroup + } + } + return nil } diff --git a/backend/internal/repository/oauth_degradation_group_bindings_test.go b/backend/internal/repository/oauth_degradation_group_bindings_test.go index 3f6dc4114f33..836eb4aa6ca2 100644 --- a/backend/internal/repository/oauth_degradation_group_bindings_test.go +++ b/backend/internal/repository/oauth_degradation_group_bindings_test.go @@ -10,7 +10,7 @@ import ( func expectOAuthDegradationGroupBindingsAccount(mock sqlmock.Sqlmock, id int64, extra string) { mock.ExpectQuery(`SELECT COALESCE\(extra,.*FROM accounts.*FOR NO KEY UPDATE`).WithArgs(id). - WillReturnRows(sqlmock.NewRows([]string{"extra"}).AddRow(extra)) + WillReturnRows(sqlmock.NewRows([]string{"extra", "platform", "type"}).AddRow(extra, "", "")) } func TestOAuthDegradationAuditDoesNotBlockQualityGroupRestore(t *testing.T) { diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index e945bb11b55a..156af1c2d655 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -276,6 +276,11 @@ func accountLoadPreferenceRate(account *Account, loadRate int) int { } func (a *Account) IsSchedulable() bool { + // Fail closed until the four gateway protocols and their final admission + // checks are implemented together. Manual switches cannot bypass this gate. + if a.IsGateway() || a.Platform == PlatformGateway { + return false + } if !a.IsActive() || !a.Schedulable || a.PerformancePaused { return false } diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index cfea0fb7a4f6..35164e4e4694 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -243,6 +243,12 @@ func NewAccountService(accountRepo AccountRepository, groupRepo GroupRepository) // Create 创建账号 func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) (*Account, error) { + if err := ValidateGatewayAccountIdentity(req.Platform, req.Type, req.Credentials); err != nil { + return nil, err + } + if err := validateGatewayAccountGroups(ctx, &Account{Platform: req.Platform, Type: req.Type}, s.groupRepo, req.GroupIDs); err != nil { + return nil, err + } if err := ValidateModelMappingMode(req.Credentials); err != nil { return nil, err } @@ -276,6 +282,18 @@ func (s *AccountService) Create(ctx context.Context, req CreateAccountRequest) ( account.AutoPauseOnExpired = true } + if account.IsGateway() { + if creator, ok := s.accountRepo.(AccountDuplicateRepository); ok { + groups := make([]AccountGroup, 0, len(req.GroupIDs)) + for i, id := range req.GroupIDs { + groups = append(groups, AccountGroup{GroupID: id, Priority: i + 1}) + } + if err := creator.CreateWithAccountGroups(ctx, account, groups); err != nil { + return nil, err + } + return account, nil + } + } if err := s.accountRepo.Create(ctx, account); err != nil { return nil, fmt.Errorf("create account: %w", err) } @@ -348,6 +366,23 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount } // 更新字段 + if account.IsGateway() || account.Platform == PlatformGateway { + credentials := account.Credentials + if req.Credentials != nil { + credentials = mergeGatewayCredentials(account.Credentials, *req.Credentials) + req.Credentials = &credentials + } + if err := ValidateGatewayAccountIdentity(account.Platform, account.Type, credentials); err != nil { + return nil, err + } + ids := account.GroupIDs + if req.GroupIDs != nil { + ids = *req.GroupIDs + } + if err := validateGatewayAccountGroups(ctx, account, s.groupRepo, ids); err != nil { + return nil, err + } + } if req.Name != nil { account.Name = *req.Name } diff --git a/backend/internal/service/account_test_service.go b/backend/internal/service/account_test_service.go index 35f209da7dc0..dbcaf3c886a2 100644 --- a/backend/internal/service/account_test_service.go +++ b/backend/internal/service/account_test_service.go @@ -401,6 +401,9 @@ func (s *AccountTestService) TestAccountConnection(c *gin.Context, accountID int return s.sendErrorAndEnd(c, "Account not found") } bindAccountTestPlatform(c, account) + if account.gatewayProtocolsPending() { + return s.sendErrorAndEnd(c, ErrGatewayProtocolsPending.Error()) + } recordQualityBatchRoute(c, account, modelID, account.Platform+":"+account.GetAPIProtocol()) if expected, ok := ctx.Value(modelTraceContextKey{}).(modelTraceEnvironment); ok { actual, err := modelTraceEnvironmentForAccount(account, modelID) diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 1cefcfc0b8d1..25f92b84a1c5 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -431,6 +431,9 @@ func normalizeOpenAILongContextBillingUpdateExtra(account *Account, input *Updat // Grok media eligibility helpers live in account_grok_media_eligibility.go. func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]any) (*Account, error) { + if err := ValidateGatewayAccountIdentity(input.Platform, input.Type, input.Credentials); err != nil { + return nil, err + } if err := ValidateOpenAIRequestTimezoneExtra(input.Platform, accountExtra); err != nil { return nil, err } @@ -467,7 +470,7 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an Concurrency: normalizeAccountConcurrency(input.Platform, input.Type, input.Concurrency), Priority: input.Priority, Status: StatusActive, - Schedulable: input.InitialAdmissionPlan == nil, + Schedulable: input.InitialAdmissionPlan == nil && input.Type != AccountTypeGateway, } if input.ProbeEnabled != nil && *input.ProbeEnabled { if !isUpstreamBillingProbeAccount(account) { @@ -517,6 +520,15 @@ func buildAccountForCreate(input *CreateAccountInput, accountExtra map[string]an } func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccountInput) (*Account, error) { + if input == nil { + return nil, ErrAccountNilInput + } + if err := ValidateGatewayAccountIdentity(input.Platform, input.Type, input.Credentials); err != nil { + return nil, err + } + if err := validateGatewayAccountGroups(ctx, &Account{Platform: input.Platform, Type: input.Type}, s.groupRepo, input.GroupIDs); err != nil { + return nil, err + } if err := ValidateAccountCostMultiplierExtra(input.Extra); err != nil { return nil, err } @@ -548,7 +560,7 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou // 绑定分组 groupIDs := input.GroupIDs // 如果没有指定分组,自动绑定对应平台的默认分组 - if len(groupIDs) == 0 && !input.SkipDefaultGroupBind { + if len(groupIDs) == 0 && !input.SkipDefaultGroupBind && input.Type != AccountTypeGateway { defaultGroupName := input.Platform + "-default" groups, err := s.groupRepo.ListActiveByPlatform(ctx, input.Platform) if err == nil { @@ -595,14 +607,18 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou if err := s.ValidateAccountGroupBindings(ctx, groupIDs); err != nil { return nil, err } - if (account.InitialAdmissionPlan != nil || account.InitialAPIKeyDisposition != nil) && s.accountDuplicateRepo != nil { + atomicCreator := s.accountDuplicateRepo + if account.IsGateway() && atomicCreator == nil { + atomicCreator, _ = s.accountRepo.(AccountDuplicateRepository) + } + if (account.IsGateway() || account.InitialAdmissionPlan != nil || account.InitialAPIKeyDisposition != nil) && atomicCreator != nil { // Publish the initially blocked account, its groups and both background // plans atomically; the worker cannot race a partially bound import. groups := make([]AccountGroup, 0, len(groupIDs)) for _, id := range groupIDs { groups = append(groups, AccountGroup{GroupID: id, Priority: 50}) } - if err := s.accountDuplicateRepo.CreateWithAccountGroups(ctx, account, groups); err != nil { + if err := atomicCreator.CreateWithAccountGroups(ctx, account, groups); err != nil { return nil, err } } else { @@ -670,6 +686,16 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if err != nil { return nil, err } + if err := validateGatewayAccountUpdate(account, input); err != nil { + return nil, err + } + gatewayGroupIDs := account.GroupIDs + if input.GroupIDs != nil { + gatewayGroupIDs = *input.GroupIDs + } + if err := validateGatewayAccountGroups(ctx, account, s.groupRepo, gatewayGroupIDs); err != nil { + return nil, err + } if err := prepareVertexAuthModeUpdate(account, input); err != nil { return nil, err } @@ -756,7 +782,11 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U } else if len(input.Credentials) > 0 { // 敏感子键采用"incoming 没提供就保留"的合并语义:前端响应已脱敏, // 全对象 PUT 编辑时不会再带回 token,避免覆盖时清空已有凭证。 - account.Credentials = MergePreservingSensitiveCreds(account.Credentials, input.Credentials) + if account.IsGateway() { + account.Credentials = mergeGatewayCredentials(account.Credentials, input.Credentials) + } else { + account.Credentials = MergePreservingSensitiveCreds(account.Credentials, input.Credentials) + } if err := validateQwenCacheCredentials(account.Credentials); err != nil { return nil, err } @@ -1227,13 +1257,26 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp // 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查共用,避免多次 DB 查询。 var cachedTargets []*Account - if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil || hasExcelBPSProxyUpdates(input.Extra) { + if len(input.Credentials) > 0 || input.ProxyID != nil || input.GroupIDs != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil || hasExcelBPSProxyUpdates(input.Extra) { loaded, err := s.accountRepo.GetByIDs(ctx, input.AccountIDs) if err != nil { return nil, err } cachedTargets = loaded } + for _, account := range cachedTargets { + if account == nil || (!account.IsGateway() && account.Platform != PlatformGateway) { + continue + } + if err := ValidateGatewayAccountIdentity(account.Platform, account.Type, mergeGatewayCredentials(account.Credentials, input.Credentials)); err != nil { + return nil, err + } + if input.GroupIDs != nil { + if err := validateGatewayAccountGroups(ctx, account, s.groupRepo, *input.GroupIDs); err != nil { + return nil, err + } + } + } targetsByID := make(map[int64]*Account, len(cachedTargets)) for _, account := range cachedTargets { if account != nil { @@ -1511,7 +1554,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp } func updatesUpstreamBillingProbeIdentity(credentials map[string]any) bool { - for _, key := range []string{"api_key", "base_url", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} { + for _, key := range []string{"api_key", "base_url", GatewayUpstreamKindCredentialKey, credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} { if _, ok := credentials[key]; ok { return true } @@ -1527,7 +1570,7 @@ func upstreamBillingProbeIdentity(account *Account) map[string]any { if account.ProxyID != nil { identity["proxy_id"] = *account.ProxyID } - for _, key := range []string{"api_key", "base_url", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} { + for _, key := range []string{"api_key", "base_url", GatewayUpstreamKindCredentialKey, credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} { if value, ok := account.Credentials[key]; ok { identity[key] = value } diff --git a/backend/internal/service/antigravity_gateway_claude.go b/backend/internal/service/antigravity_gateway_claude.go index 98232989097a..06d0d261f8fc 100644 --- a/backend/internal/service/antigravity_gateway_claude.go +++ b/backend/internal/service/antigravity_gateway_claude.go @@ -28,6 +28,9 @@ import ( // ├─ 成功 → 正常返回 // └─ 失败 → 设置模型限流 + 清除粘性绑定 → 切换账号 func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte, isStickySession bool) (*ForwardResult, error) { + if account.gatewayProtocolsPending() { + return nil, ErrGatewayProtocolsPending + } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err } diff --git a/backend/internal/service/antigravity_gateway_gemini.go b/backend/internal/service/antigravity_gateway_gemini.go index 3a4b2c5405c3..e15f7089bb0f 100644 --- a/backend/internal/service/antigravity_gateway_gemini.go +++ b/backend/internal/service/antigravity_gateway_gemini.go @@ -42,6 +42,9 @@ func WithForwardGeminiSession(groupID int64, sessionHash string) ForwardGeminiOp } func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Context, account *Account, originalModel string, action string, stream bool, body []byte, isStickySession bool, options ...ForwardGeminiOption) (*ForwardResult, error) { + if account.gatewayProtocolsPending() { + return nil, ErrGatewayProtocolsPending + } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err } diff --git a/backend/internal/service/antigravity_gateway_upstream.go b/backend/internal/service/antigravity_gateway_upstream.go index f2dcb0d2e269..25b3d2e3ba07 100644 --- a/backend/internal/service/antigravity_gateway_upstream.go +++ b/backend/internal/service/antigravity_gateway_upstream.go @@ -19,6 +19,9 @@ import ( // ForwardUpstream 使用 base_url + /v1/messages + 双 header 认证透传上游 Claude 请求 func (s *AntigravityGatewayService) ForwardUpstream(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) { + if account.gatewayProtocolsPending() { + return nil, ErrGatewayProtocolsPending + } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err } diff --git a/backend/internal/service/gateway_account.go b/backend/internal/service/gateway_account.go index 5ae169381165..f22f559fcb06 100644 --- a/backend/internal/service/gateway_account.go +++ b/backend/internal/service/gateway_account.go @@ -2,16 +2,116 @@ package service import ( "context" + "maps" + "net/url" + "strings" "github.com/Wei-Shaw/sub2api/internal/domain" + infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors" ) +// PlatformGateway is reserved for account storage and is excluded from the catalog. +const PlatformGateway = domain.PlatformGateway +const GatewayUpstreamKindCredentialKey = "upstream_kind" + +var ErrGatewayAccountIdentity = infraerrors.BadRequest("INVALID_GATEWAY_ACCOUNT", "gateway accounts require platform/type gateway, upstream_kind new_api or sub2api, a site URL and an API key") +var ErrGatewayAccountGroup = infraerrors.BadRequest("INVALID_GATEWAY_GROUP", "gateway accounts require an existing concrete or composite group that does not require OAuth") +var ErrGatewayProtocolsPending = infraerrors.BadRequest("GATEWAY_PROTOCOLS_PENDING", "gateway scheduling and forwarding are not available yet") + +// ValidateGatewayAccountIdentity reserves an account-only identity. Legacy +// records are neither reclassified nor subjected to new credential validation. +func ValidateGatewayAccountIdentity(platform, accountType string, credentials map[string]any) error { + if platform != PlatformGateway && accountType != AccountTypeGateway { + return nil + } + if platform != PlatformGateway || accountType != AccountTypeGateway { + return ErrGatewayAccountIdentity + } + kind, _ := credentials[GatewayUpstreamKindCredentialKey].(string) + key, _ := credentials["api_key"].(string) + base, _ := credentials["base_url"].(string) + u, err := url.Parse(base) + if (kind != "new_api" && kind != "sub2api") || strings.TrimSpace(key) == "" || strings.ContainsAny(key, "\r\n") || + err != nil || u == nil || (u.Scheme != "https" && u.Scheme != "http") || u.Hostname() == "" || + u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || strings.TrimSpace(base) != base { + return ErrGatewayAccountIdentity + } + return nil +} + +// ValidateGatewayAccountGroup adds only the new type's binding policy. Existing +// account rules remain with their existing callers. No implicit membership is +// created by this check; group IDs must be supplied by the administrator. +func ValidateGatewayAccountGroup(a *Account, group *Group) error { + if a == nil || (!a.IsGateway() && a.Platform != PlatformGateway) { + return nil + } + if !a.IsGateway() || a.Platform != PlatformGateway || group == nil || group.ID <= 0 || + !domain.IsGroupPlatform(group.Platform) || group.RequireOAuthOnly { + return ErrGatewayAccountGroup + } + return nil +} + +func validateGatewayAccountGroups(ctx context.Context, a *Account, repo GroupRepository, ids []int64) error { + if a == nil || (!a.IsGateway() && a.Platform != PlatformGateway) || len(ids) == 0 { + return nil + } + if repo == nil { + return ErrGatewayAccountGroup + } + for _, id := range ids { + if id <= 0 { + return ErrGatewayAccountGroup + } + group, err := repo.GetByID(ctx, id) + if err != nil { + return err + } + if err := ValidateGatewayAccountGroup(a, group); err != nil { + return err + } + } + return nil +} + +func validateGatewayAccountUpdate(a *Account, input *UpdateAccountInput) error { + platform, kind := a.Platform, a.Type + if input.Platform != "" { + platform = input.Platform + } + if input.Type != "" { + kind = input.Type + } + if a.IsGateway() || a.Platform == PlatformGateway || platform == PlatformGateway || kind == AccountTypeGateway { + // Conversion needs a new account, not a platform edit that loses bindings + // or reuses credentials with different ownership/protocol semantics. + if platform != a.Platform || kind != a.Type { + return ErrGatewayAccountIdentity + } + credentials := mergeGatewayCredentials(a.Credentials, input.Credentials) + return ValidateGatewayAccountIdentity(platform, kind, credentials) + } + return nil +} + +func mergeGatewayCredentials(existing, incoming map[string]any) map[string]any { + out := make(map[string]any, len(existing)+len(incoming)) + maps.Copy(out, existing) + maps.Copy(out, incoming) + return out +} + // IsGateway identifies the dedicated cross-platform account type. Existing // apikey/upstream credentials and probe settings never opt an account into it. func (a *Account) IsGateway() bool { return a != nil && a.Type == AccountTypeGateway } +func (a *Account) gatewayProtocolsPending() bool { + return a != nil && (a.IsGateway() || a.Platform == PlatformGateway) +} + // usagePlatformForRequest preserves the selected account's platform for legacy // accounts. A gateway has no single provider: use the handler's request snapshot // (also available after async handoff), then the resolved request/group platform. diff --git a/backend/internal/service/gateway_account_management_test.go b/backend/internal/service/gateway_account_management_test.go new file mode 100644 index 000000000000..4a2d12eb8df2 --- /dev/null +++ b/backend/internal/service/gateway_account_management_test.go @@ -0,0 +1,186 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/stretchr/testify/require" +) + +func gatewayManagementFixture() *Account { + return &Account{ID: 959, Name: "Gateway fixture", Platform: PlatformGateway, Type: AccountTypeGateway, + Status: StatusActive, Schedulable: true, Concurrency: 2, + Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example/tenant", "api_key": "synthetic-key"}} +} + +func TestGatewayManagementIdentityIsAccountOnly(t *testing.T) { + a := gatewayManagementFixture() + require.NoError(t, ValidateGatewayAccountIdentity(a.Platform, a.Type, a.Credentials)) + require.False(t, domain.IsConcretePlatform(PlatformGateway)) + require.False(t, domain.IsGroupPlatform(PlatformGateway)) + for _, kind := range []string{"new_api", "sub2api"} { + a.Credentials["upstream_kind"] = kind + require.NoError(t, ValidateGatewayAccountIdentity(a.Platform, a.Type, a.Credentials)) + } + for _, platform := range []string{PlatformOpenAI, PlatformComposite, ""} { + require.Error(t, ValidateGatewayAccountIdentity(platform, AccountTypeGateway, a.Credentials)) + } + for _, kind := range []string{AccountTypeAPIKey, AccountTypeUpstream, AccountTypeOAuth} { + require.Error(t, ValidateGatewayAccountIdentity(PlatformGateway, kind, a.Credentials)) + require.NoError(t, ValidateGatewayAccountIdentity(PlatformOpenAI, kind, nil), "legacy validation is unchanged") + } + for _, field := range []string{"upstream_kind", "base_url", "api_key"} { + a = gatewayManagementFixture() + delete(a.Credentials, field) + require.Error(t, ValidateGatewayAccountIdentity(a.Platform, a.Type, a.Credentials), field) + } + for _, address := range []string{"relative/path", "ftp://gateway.example", "https://user:secret@gateway.example", "https://gateway.example?api_key=secret", "https://gateway.example/#secret"} { + a = gatewayManagementFixture() + a.Credentials["base_url"] = address + err := ValidateGatewayAccountIdentity(a.Platform, a.Type, a.Credentials) + require.Error(t, err) + require.NotContains(t, err.Error(), "secret", "invalid configuration must not echo credentials") + } +} + +func TestGatewayManagementGroupsAcceptConcreteAndCompositeRejectOAuthOnly(t *testing.T) { + a := gatewayManagementFixture() + for _, platform := range append(domain.ConcretePlatformIDs(), PlatformComposite) { + g := &Group{ID: 1, Platform: platform} + require.NoError(t, ValidateGatewayAccountGroup(a, g), platform) + g.RequireOAuthOnly = true + require.Error(t, ValidateGatewayAccountGroup(a, g), platform) + } + require.Error(t, ValidateGatewayAccountGroup(a, &Group{ID: 1, Platform: PlatformGateway})) + require.Error(t, ValidateGatewayAccountGroup(a, nil)) + require.NoError(t, ValidateGatewayAccountGroup(&Account{Type: AccountTypeAPIKey}, nil), "do not change legacy policy") + // A stored/manual schedulable=true cannot bypass the incomplete protocol gate. + require.False(t, a.IsSchedulable()) +} + +func TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups(t *testing.T) { + for _, oauthOnly := range []bool{false, true} { + repo := &accountRepoStubForBulkUpdate{createID: 959} + groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{ + 1: {ID: 1, Platform: PlatformOpenAI}, 2: {ID: 2, Platform: PlatformAnthropic, RequireOAuthOnly: oauthOnly}, + 3: {ID: 3, Platform: PlatformComposite}, + }} + svc := &adminServiceImpl{accountRepo: repo, groupRepo: groups} + a := gatewayManagementFixture() + created, err := svc.CreateAccount(context.Background(), &CreateAccountInput{Name: a.Name, Platform: a.Platform, Type: a.Type, + Credentials: a.Credentials, Concurrency: 2, GroupIDs: []int64{1, 2, 3}}) + if oauthOnly { + require.Error(t, err) + require.Nil(t, repo.createAccount) + require.Empty(t, repo.bindGroupsCalls) + } else { + require.NoError(t, err) + require.Equal(t, []int64{1, 2, 3}, repo.bindGroupsByAccount[created.ID]) + require.False(t, created.Schedulable) + } + } + // No implicit default lookup even when no group repository was configured. + repo := &accountRepoStubForBulkUpdate{createID: 959} + a := gatewayManagementFixture() + created, err := (&adminServiceImpl{accountRepo: repo}).CreateAccount(context.Background(), &CreateAccountInput{ + Name: a.Name, Platform: a.Platform, Type: a.Type, Credentials: a.Credentials}) + require.NoError(t, err) + require.Empty(t, created.GroupIDs) + require.Empty(t, repo.bindGroupsCalls) +} + +func TestGatewayManagementUpdatePreservesKeyAndRejectsIdentityConversion(t *testing.T) { + a := gatewayManagementFixture() + repo := &accountRepoStubForBulkUpdate{getByIDAccounts: map[int64]*Account{959: a}} + svc := &adminServiceImpl{accountRepo: repo} + updated, err := svc.UpdateAccount(context.Background(), 959, &UpdateAccountInput{ + Name: "Edited gateway", Credentials: map[string]any{"base_url": "https://edited.example"}}) + require.NoError(t, err) + require.Equal(t, "synthetic-key", updated.Credentials["api_key"]) + require.Equal(t, "new_api", updated.Credentials["upstream_kind"]) + for _, input := range []*UpdateAccountInput{{Platform: PlatformOpenAI}, {Type: AccountTypeAPIKey}, {Credentials: map[string]any{"upstream_kind": "unknown"}}} { + repo.updatedAccounts = nil + _, err := svc.UpdateAccount(context.Background(), 959, input) + require.Error(t, err) + require.Empty(t, repo.updatedAccounts) + } + legacy, legacyRepo := newPlatformEditService() + _, err = legacy.UpdateAccount(context.Background(), 7, &UpdateAccountInput{Platform: PlatformGateway, Type: AccountTypeGateway, Credentials: a.Credentials}) + require.Error(t, err) + require.Empty(t, legacyRepo.updatedAccounts) +} + +func TestGatewayManagementAccountServiceRejectsOAuthGroupsBeforeCreate(t *testing.T) { + repo := &accountRepoStubForBulkUpdate{createID: 959} + groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{1: {ID: 1, Platform: PlatformComposite, RequireOAuthOnly: true}}} + a := gatewayManagementFixture() + _, err := NewAccountService(repo, groups).Create(context.Background(), CreateAccountRequest{ + Name: a.Name, Platform: a.Platform, Type: a.Type, Credentials: a.Credentials, GroupIDs: []int64{1}}) + require.Error(t, err) + require.Nil(t, repo.createAccount) +} + +func TestGatewayManagementForwardingRemainsClosed(t *testing.T) { + a := gatewayManagementFixture() + ctx := context.Background() + // Nil services/contexts are deliberate: the guard must run before transport, + // policy evaluation, model parsing, OAuth replay or any other side effects. + _, err := (*GatewayService)(nil).Forward(ctx, nil, a, nil) + require.ErrorIs(t, err, ErrGatewayProtocolsPending) + _, err = (*OpenAIGatewayService)(nil).Forward(ctx, nil, a, nil) + require.ErrorIs(t, err, ErrGatewayProtocolsPending) + _, err = (*OpenAIGatewayService)(nil).ForwardAsAnthropic(ctx, nil, a, nil, "", "") + require.ErrorIs(t, err, ErrGatewayProtocolsPending) + _, err = (*OpenAIGatewayService)(nil).ForwardAsChatCompletions(ctx, nil, a, nil, "", "") + require.ErrorIs(t, err, ErrGatewayProtocolsPending) + _, err = (*GeminiMessagesCompatService)(nil).Forward(ctx, nil, a, nil) + require.ErrorIs(t, err, ErrGatewayProtocolsPending) + _, err = (*GeminiMessagesCompatService)(nil).ForwardNative(ctx, nil, a, "fixture", "generateContent", false, nil) + require.ErrorIs(t, err, ErrGatewayProtocolsPending) + _, err = (*AntigravityGatewayService)(nil).Forward(ctx, nil, a, nil, false) + require.ErrorIs(t, err, ErrGatewayProtocolsPending) + _, err = (*AntigravityGatewayService)(nil).ForwardGemini(ctx, nil, a, "fixture", "generateContent", false, nil, false) + require.ErrorIs(t, err, ErrGatewayProtocolsPending) + _, err = (*AntigravityGatewayService)(nil).ForwardUpstream(ctx, nil, a, nil) + require.ErrorIs(t, err, ErrGatewayProtocolsPending) + require.ErrorIs(t, (*OpenAIGatewayService)(nil).ForwardCountTokensAsAnthropic(ctx, nil, a, nil, ""), ErrGatewayProtocolsPending) + require.ErrorIs(t, (*OpenAIGatewayService)(nil).ForwardResponsesInputTokens(ctx, nil, a, nil), ErrGatewayProtocolsPending) +} + +func TestGatewayManagementUpdateAndBulkRejectOAuthBindingsBeforeWrites(t *testing.T) { + for _, path := range []string{"admin", "account-service", "bulk"} { + t.Run(path, func(t *testing.T) { + a := gatewayManagementFixture() + repo := &accountRepoStubForBulkUpdate{getByIDAccounts: map[int64]*Account{a.ID: a}, getByIDsAccounts: []*Account{a}} + groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{1: {ID: 1, Platform: PlatformOpenAI, RequireOAuthOnly: true}}} + ids := []int64{1} + var err error + switch path { + case "admin": + _, err = (&adminServiceImpl{accountRepo: repo, groupRepo: groups}).UpdateAccount(context.Background(), a.ID, &UpdateAccountInput{GroupIDs: &ids, Name: "must not save"}) + case "account-service": + _, err = NewAccountService(repo, groups).Update(context.Background(), a.ID, UpdateAccountRequest{GroupIDs: &ids}) + case "bulk": + _, err = (&adminServiceImpl{accountRepo: repo, groupRepo: groups}).BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{ + AccountIDs: []int64{a.ID}, GroupIDs: &ids, SkipMixedChannelCheck: true, Name: "must not save"}) + } + require.Error(t, err) + require.Empty(t, repo.updatedAccounts) + require.Zero(t, repo.bulkUpdateCalls) + require.Empty(t, repo.bindGroupsCalls) + }) + } +} + +func TestGatewayManagementBulkRejectsInvalidCredentialMerge(t *testing.T) { + a := gatewayManagementFixture() + repo := &accountRepoStubForBulkUpdate{getByIDsAccounts: []*Account{a}} + _, err := (&adminServiceImpl{accountRepo: repo}).BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{ + AccountIDs: []int64{a.ID}, Credentials: map[string]any{"upstream_kind": "unknown"}}) + require.ErrorIs(t, err, ErrGatewayAccountIdentity) + require.Zero(t, repo.bulkUpdateCalls) + require.Equal(t, "new_api", a.Credentials["upstream_kind"]) +} diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index 9175be4086d9..1706eb8f1640 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -120,6 +120,9 @@ func sleepWithContext(ctx context.Context, d time.Duration) error { // Forward 转发请求到Claude API func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, parsed *ParsedRequest) (result *ForwardResult, err error) { + if account.gatewayProtocolsPending() { + return nil, ErrGatewayProtocolsPending + } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err } diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 8ec232767197..8ac3e36951b2 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -541,6 +541,9 @@ func (s *GeminiMessagesCompatService) HasAntigravityAccounts(ctx context.Context } func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) { + if account.gatewayProtocolsPending() { + return nil, ErrGatewayProtocolsPending + } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err } @@ -1112,6 +1115,9 @@ func isGeminiSignatureRelatedError(respBody []byte) bool { } func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.Context, account *Account, originalModel string, action string, stream bool, body []byte) (*ForwardResult, error) { + if account.gatewayProtocolsPending() { + return nil, ErrGatewayProtocolsPending + } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err } diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 78a384c6e034..277a48e855d5 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -63,6 +63,9 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions( promptCacheKey string, defaultMappedModel string, ) (*OpenAIForwardResult, error) { + if account.gatewayProtocolsPending() { + return nil, ErrGatewayProtocolsPending + } admittedCtx, admissionErr := s.beginPriorityLatencyTurn(ctx, c, account, gjson.GetBytes(body, "model").String()) if admissionErr != nil { diff --git a/backend/internal/service/openai_gateway_count_tokens.go b/backend/internal/service/openai_gateway_count_tokens.go index 7d388dd8c1fb..913f0d66b9f0 100644 --- a/backend/internal/service/openai_gateway_count_tokens.go +++ b/backend/internal/service/openai_gateway_count_tokens.go @@ -50,6 +50,9 @@ func (s *OpenAIGatewayService) ForwardResponsesInputTokens( account *Account, body []byte, ) error { + if account.gatewayProtocolsPending() { + return ErrGatewayProtocolsPending + } if account == nil { writeOpenAIResponsesInputTokensError(c, http.StatusServiceUnavailable, "api_error", "No available OpenAI accounts") return fmt.Errorf("responses input_tokens: missing account") @@ -268,6 +271,9 @@ func (s *OpenAIGatewayService) ForwardCountTokensAsAnthropic( body []byte, defaultMappedModel string, ) error { + if account.gatewayProtocolsPending() { + return ErrGatewayProtocolsPending + } if account == nil { writeAnthropicCountTokensError(c, http.StatusServiceUnavailable, "api_error", "No available OpenAI accounts") return fmt.Errorf("count_tokens: missing account") diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index e8962bf2b0d4..05990d39994e 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -91,6 +91,9 @@ func prismBrowserResponsesURL(baseURL string) string { // Forward forwards request to OpenAI API func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (result *OpenAIForwardResult, resultErr error) { + if account.gatewayProtocolsPending() { + return nil, ErrGatewayProtocolsPending + } preparedCtx, preparedBody, prepareErr := s.prepareOpenAIAgentOAuthReplay(ctx, account, body) if prepareErr != nil { return nil, prepareErr diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index dc069c6238a5..ef2cdd1197d5 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -33,6 +33,9 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( promptCacheKey string, defaultMappedModel string, ) (*OpenAIForwardResult, error) { + if account.gatewayProtocolsPending() { + return nil, ErrGatewayProtocolsPending + } admittedCtx, admissionErr := s.beginPriorityLatencyTurn(ctx, c, account, gjson.GetBytes(body, "model").String()) if admissionErr != nil { From e31ff56b7ae456e3fd1d2c4e20d1b152dcbebf25 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 02:05:46 +0800 Subject: [PATCH 02/26] fix: commit gateway settings and group updates atomically Address the independent review of 0a1a0b914: keep omitted-platform admin edits, AccountService updates and each gateway bulk membership item in one transaction. Reuse existing billing/state fences, live binding checks and outbox writes, with savepoint rollback for caller-owned transactions and cache publication after commit. Add deterministic PostgreSQL interleaving, staged-write rollback, inherited-transaction and successful billing-state regression sources. Validation remains remote CI only. --- .../workflows/issue959-gateway-regression.yml | 7 +- backend/internal/repository/account_repo.go | 3 + ...gateway_account_atomic_integration_test.go | 282 ++++++++++++++++++ .../repository/gateway_account_transaction.go | 78 +++++ backend/internal/service/account_service.go | 19 ++ backend/internal/service/admin_account.go | 62 +++- backend/internal/service/gateway_account.go | 18 ++ .../gateway_account_management_test.go | 60 +++- 8 files changed, 514 insertions(+), 15 deletions(-) create mode 100644 backend/internal/repository/gateway_account_atomic_integration_test.go create mode 100644 backend/internal/repository/gateway_account_transaction.go diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index 7fc1f308a202..02d2299a37ee 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -83,6 +83,7 @@ jobs: grep -F -- '--- PASS: TestUsagePlatformSnapshotsSelectedAccount' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementForwardingRemainsClosed' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayManagementUpdateRequiresAtomicCapability' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementRepositoryBindingGuard' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayDataImportIdentityValidation' ../evidence/unit-race.log grep -F -- '--- PASS: TestAccountGatewayDTORedactsCallingKey' ../evidence/unit-race.log @@ -92,13 +93,17 @@ jobs: run: | set -euo pipefail go test -race -tags=integration ./internal/repository \ - -run '^Test(ConcurrencyCacheSuite|AccountRepoSuite)$/^TestGateway(TargetsShareAccountConcurrency|ManagementAtomicMembershipAndOAuthExclusion)$' \ + -run '^Test((ConcurrencyCacheSuite|AccountRepoSuite)$|GatewayAtomicUpdate)/^(TestGateway(TargetsShareAccountConcurrency|ManagementAtomicMembershipAndOAuthExclusion)|admin|account-service|bulk)$' \ -count=1 -v -timeout=10m 2>&1 | tee ../evidence/concurrency-redis.log if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/concurrency-redis.log; then exit 1 fi grep -F -- '--- PASS: TestConcurrencyCacheSuite/TestGatewayTargetsShareAccountConcurrency' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayManagementAtomicMembershipAndOAuthExclusion' ../evidence/concurrency-redis.log + grep -F -- '--- PASS: TestGatewayAtomicUpdateOAuthInterleaving' ../evidence/concurrency-redis.log + grep -F -- '--- PASS: TestGatewayAtomicUpdateRollbackAfterStagedFields' ../evidence/concurrency-redis.log + grep -F -- '--- PASS: TestGatewayAtomicUpdateSuccessfulCommit' ../evidence/concurrency-redis.log + grep -F -- '--- PASS: TestGatewayAtomicUpdateCallerTransactionRollback' ../evidence/concurrency-redis.log - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 3f925f57fbc7..074ce97ef166 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -2487,6 +2487,9 @@ func (r *accountRepository) BindGroups(ctx context.Context, accountID int64, gro // SetGroupAllowedModels 覆盖账号在各个已绑定分组内的模型限制:allowed 里没有的分组恢复为不限制, // 账号未绑定的分组被忽略。有变化时通知调度器刷新该账号的缓存。 func (r *accountRepository) SetGroupAllowedModels(ctx context.Context, accountID int64, allowed map[int64][]string) error { + if scoped := r.accountTransactionScope(ctx); scoped != r { + return scoped.SetGroupAllowedModels(ctx, accountID, allowed) + } tx, err := r.client.Tx(ctx) if err != nil && !errors.Is(err, dbent.ErrTxStarted) { return err diff --git a/backend/internal/repository/gateway_account_atomic_integration_test.go b/backend/internal/repository/gateway_account_atomic_integration_test.go new file mode 100644 index 000000000000..82a5ceeeef3b --- /dev/null +++ b/backend/internal/repository/gateway_account_atomic_integration_test.go @@ -0,0 +1,282 @@ +//go:build integration + +package repository + +import ( + "context" + "fmt" + "sync" + "testing" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// The barriers are outside the production implementation. They exercise real +// service calls and independent PostgreSQL transactions without timing sleeps. +type gatewayAtomicBarrierRepo struct { + service.AdminAccountRepository + atomic service.GatewayAccountTransactionRepository + beforeLock bool + failBinding bool + entered chan struct{} + release chan struct{} + once sync.Once + staged *service.Account +} + +func (r *gatewayAtomicBarrierRepo) wait(ctx context.Context) error { + r.once.Do(func() { close(r.entered) }) + select { + case <-r.release: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (r *gatewayAtomicBarrierRepo) WithinGatewayAccountTransaction(ctx context.Context, id int64, groups []int64, run func(context.Context) error) error { + if r.beforeLock { + if err := r.wait(ctx); err != nil { + return err + } + } + return r.atomic.WithinGatewayAccountTransaction(ctx, id, groups, run) +} + +func (r *gatewayAtomicBarrierRepo) BindGroups(ctx context.Context, id int64, groups []int64) error { + if r.failBinding { + var err error + r.staged, err = r.AdminAccountRepository.GetByID(ctx, id) + if err != nil { + return err + } + if err := r.wait(ctx); err != nil { + return err + } + return service.ErrGatewayAccountGroup + } + return r.AdminAccountRepository.BindGroups(ctx, id, groups) +} + +type gatewayAtomicResult struct { + err error + bulk *service.BulkUpdateAccountsResult +} + +func gatewayAtomicFixture(t *testing.T) (service.AdminAccountRepository, service.AdminGroupRepository, *service.Account, int64) { + t.Helper() + ctx := t.Context() + repo := NewAdminAccountRepository(integrationEntClient, integrationDB, nil) + groups := NewAdminGroupRepository(integrationEntClient, integrationDB) + stamp := time.Now().UnixNano() + oldGroup, err := integrationEntClient.Group.Create().SetName(fmt.Sprintf("gateway-atomic-old-%d", stamp)).SetPlatform(service.PlatformOpenAI).Save(ctx) + require.NoError(t, err) + target, err := integrationEntClient.Group.Create().SetName(fmt.Sprintf("gateway-atomic-target-%d", stamp)).SetPlatform(service.PlatformAnthropic).Save(ctx) + require.NoError(t, err) + a := &service.Account{Name: fmt.Sprintf("gateway-atomic-%d", stamp), Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Status: service.StatusActive, Concurrency: 2, Priority: 10, + Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example", "api_key": "original-synthetic-key"}, + Extra: map[string]any{service.AccountCostMultiplierExtraKey: 0.3, "quota_used": 12.0}} + require.NoError(t, repo.CreateWithAccountGroups(ctx, a, []service.AccountGroup{{GroupID: oldGroup.ID, Priority: 37, AllowedModels: []string{"fixture-model"}}})) + t.Cleanup(func() { + _, _ = integrationDB.Exec(`DELETE FROM scheduler_outbox WHERE account_id=$1 OR group_id IN ($2,$3)`, a.ID, oldGroup.ID, target.ID) + _, _ = integrationDB.Exec(`DELETE FROM account_groups WHERE account_id=$1`, a.ID) + _, _ = integrationDB.Exec(`DELETE FROM accounts WHERE id=$1`, a.ID) + _, _ = integrationDB.Exec(`DELETE FROM groups WHERE id IN ($1,$2)`, oldGroup.ID, target.ID) + }) + return repo, groups, a, target.ID +} + +func gatewayAtomicWrite(ctx context.Context, route string, repo service.AdminAccountRepository, groups service.AdminGroupRepository, id, target int64) gatewayAtomicResult { + ids := []int64{target} + credentials := map[string]any{"api_key": "replacement-synthetic-key"} + name := "gateway-atomic-edited" + if route == "account-service" { + _, err := service.NewAccountService(repo, groups).Update(ctx, id, service.UpdateAccountRequest{Name: &name, Credentials: &credentials, GroupIDs: &ids}) + return gatewayAtomicResult{err: err} + } + admin := service.NewAdminService(nil, nil, groups, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, integrationEntClient, nil, nil, nil, nil, nil, nil, nil, nil, nil) + if route == "bulk" { + result, err := admin.BulkUpdateAccounts(ctx, &service.BulkUpdateAccountsInput{AccountIDs: []int64{id}, Name: name, Credentials: credentials, GroupIDs: &ids, SkipMixedChannelCheck: true}) + return gatewayAtomicResult{err: err, bulk: result} + } + // Platform is intentionally omitted: this was the reviewed partial-write path. + _, err := admin.UpdateAccount(ctx, id, &service.UpdateAccountInput{Name: name, Credentials: credentials, GroupIDs: &ids, SkipMixedChannelCheck: true}) + return gatewayAtomicResult{err: err} +} + +func gatewayAtomicAssertUnchanged(t *testing.T, repo service.AccountRepository, before *service.Account) { + t.Helper() + after, err := repo.GetByID(t.Context(), before.ID) + require.NoError(t, err) + require.Equal(t, before.Name, after.Name) + require.Equal(t, before.Credentials, after.Credentials) + require.Equal(t, before.RateMultiplier, after.RateMultiplier) + require.Equal(t, before.Extra, after.Extra) + require.Equal(t, before.Status, after.Status) + require.Equal(t, before.Schedulable, after.Schedulable) + require.Equal(t, before.GroupIDs, after.GroupIDs) + for i := range before.AccountGroups { + require.Equal(t, before.AccountGroups[i].Priority, after.AccountGroups[i].Priority) + require.Equal(t, before.AccountGroups[i].AllowedModels, after.AccountGroups[i].AllowedModels) + } +} + +func TestGatewayAtomicUpdateOAuthInterleaving(t *testing.T) { + for _, route := range []string{"admin", "account-service", "bulk"} { + t.Run(route, func(t *testing.T) { + repo, groups, a, target := gatewayAtomicFixture(t) + barrier := &gatewayAtomicBarrierRepo{AdminAccountRepository: repo, atomic: repo.(service.GatewayAccountTransactionRepository), beforeLock: true, + entered: make(chan struct{}), release: make(chan struct{})} + ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second) + defer cancel() + done := make(chan gatewayAtomicResult, 1) + go func() { done <- gatewayAtomicWrite(ctx, route, barrier, groups, a.ID, target) }() + select { + case <-barrier.entered: + case <-ctx.Done(): + t.Fatal("update did not reach the post-precheck transaction barrier") + } + group, err := groups.GetByID(ctx, target) + require.NoError(t, err) + group.RequireOAuthOnly = true + require.NoError(t, groups.Update(ctx, group), "independent group transaction wins after the service precheck") + _, err = integrationDB.ExecContext(ctx, `UPDATE accounts SET rate_multiplier=2.5,extra=extra||'{"quota_used":19,"cost_multiplier":0.7}'::jsonb WHERE id=$1`, a.ID) + require.NoError(t, err) + before, err := repo.GetByID(ctx, a.ID) + require.NoError(t, err) + close(barrier.release) + select { + case result := <-done: + if route == "bulk" { + require.NoError(t, result.err) + require.NotNil(t, result.bulk) + require.Equal(t, []int64{a.ID}, result.bulk.FailedIDs) + require.Empty(t, result.bulk.SuccessIDs) + } else { + require.ErrorIs(t, result.err, service.ErrGatewayAccountGroup) + } + case <-ctx.Done(): + t.Fatal("update did not finish") + } + gatewayAtomicAssertUnchanged(t, repo, before) + }) + } +} + +func TestGatewayAtomicUpdateRollbackAfterStagedFields(t *testing.T) { + for _, route := range []string{"admin", "account-service", "bulk"} { + t.Run(route, func(t *testing.T) { + repo, groups, a, target := gatewayAtomicFixture(t) + before, err := repo.GetByID(t.Context(), a.ID) + require.NoError(t, err) + var events int + require.NoError(t, integrationDB.QueryRow(`SELECT count(*) FROM scheduler_outbox WHERE account_id=$1`, a.ID).Scan(&events)) + barrier := &gatewayAtomicBarrierRepo{AdminAccountRepository: repo, atomic: repo.(service.GatewayAccountTransactionRepository), failBinding: true, + entered: make(chan struct{}), release: make(chan struct{})} + ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second) + defer cancel() + done := make(chan gatewayAtomicResult, 1) + go func() { done <- gatewayAtomicWrite(ctx, route, barrier, groups, a.ID, target) }() + select { + case <-barrier.entered: + case <-ctx.Done(): + t.Fatal("update did not reach binding after staging fields") + } + require.Equal(t, "gateway-atomic-edited", barrier.staged.Name) + require.Equal(t, "replacement-synthetic-key", barrier.staged.Credentials["api_key"]) + gatewayAtomicAssertUnchanged(t, repo, before) // independent connection cannot see staged writes + close(barrier.release) + select { + case result := <-done: + if route == "bulk" { + require.NoError(t, result.err) + require.NotNil(t, result.bulk) + require.Equal(t, []int64{a.ID}, result.bulk.FailedIDs) + } else { + require.ErrorIs(t, result.err, service.ErrGatewayAccountGroup) + } + case <-ctx.Done(): + t.Fatal("rollback did not finish") + } + gatewayAtomicAssertUnchanged(t, repo, before) + var afterEvents int + require.NoError(t, integrationDB.QueryRow(`SELECT count(*) FROM scheduler_outbox WHERE account_id=$1`, a.ID).Scan(&afterEvents)) + require.Equal(t, events, afterEvents, "failed writes must not publish outbox events") + }) + } +} + +func TestGatewayAtomicUpdateSuccessfulCommit(t *testing.T) { + for _, route := range []string{"admin", "account-service", "bulk"} { + t.Run(route, func(t *testing.T) { + repo, groups, a, target := gatewayAtomicFixture(t) + barrier := &gatewayAtomicBarrierRepo{AdminAccountRepository: repo, atomic: repo.(service.GatewayAccountTransactionRepository), beforeLock: true, + entered: make(chan struct{}), release: make(chan struct{})} + ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second) + defer cancel() + done := make(chan gatewayAtomicResult, 1) + go func() { done <- gatewayAtomicWrite(ctx, route, barrier, groups, a.ID, target) }() + select { + case <-barrier.entered: + case <-ctx.Done(): + t.Fatal("update did not reach the pre-lock billing-state barrier") + } + _, err := integrationDB.ExecContext(ctx, `UPDATE accounts SET rate_multiplier=2.5,extra=extra||'{"quota_used":19,"cost_multiplier":0.7}'::jsonb WHERE id=$1`, a.ID) + require.NoError(t, err) + close(barrier.release) + var result gatewayAtomicResult + select { + case result = <-done: + case <-ctx.Done(): + t.Fatal("atomic commit did not finish") + } + require.NoError(t, result.err) + if route == "bulk" { + require.NotNil(t, result.bulk) + require.Equal(t, []int64{a.ID}, result.bulk.SuccessIDs) + } + after, err := repo.GetByID(t.Context(), a.ID) + require.NoError(t, err) + require.Equal(t, "gateway-atomic-edited", after.Name) + require.Equal(t, "replacement-synthetic-key", after.Credentials["api_key"]) + require.Equal(t, []int64{target}, after.GroupIDs) + require.NotNil(t, after.RateMultiplier) + require.Equal(t, 2.5, *after.RateMultiplier, "omitted request rate must retain the latest committed value") + require.Equal(t, 19.0, after.Extra["quota_used"]) + require.Equal(t, 0.7, after.CostMultiplier()) + require.False(t, after.IsSchedulable()) + }) + } +} + +func TestGatewayAtomicUpdateCallerTransactionRollback(t *testing.T) { + for _, route := range []string{"admin", "account-service", "bulk"} { + t.Run(route, func(t *testing.T) { + repo, groups, a, target := gatewayAtomicFixture(t) + before, err := repo.GetByID(t.Context(), a.ID) + require.NoError(t, err) + barrier := &gatewayAtomicBarrierRepo{AdminAccountRepository: repo, atomic: repo.(service.GatewayAccountTransactionRepository), failBinding: true, + entered: make(chan struct{}), release: make(chan struct{})} + close(barrier.release) + tx, err := integrationEntClient.Tx(t.Context()) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + result := gatewayAtomicWrite(dbent.NewTxContext(t.Context(), tx), route, barrier, groups, a.ID, target) + if route == "bulk" { + require.NoError(t, result.err) + require.NotNil(t, result.bulk) + require.Equal(t, []int64{a.ID}, result.bulk.FailedIDs) + } else { + require.ErrorIs(t, result.err, service.ErrGatewayAccountGroup) + } + // A caller can commit other successful work without committing this + // failed item's fields or outbox. The savepoint owns item rollback. + require.NoError(t, tx.Commit()) + gatewayAtomicAssertUnchanged(t, repo, before) + }) + } +} diff --git a/backend/internal/repository/gateway_account_transaction.go b/backend/internal/repository/gateway_account_transaction.go new file mode 100644 index 000000000000..00189db32cf6 --- /dev/null +++ b/backend/internal/repository/gateway_account_transaction.go @@ -0,0 +1,78 @@ +package repository + +import ( + "context" + "errors" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +var _ service.GatewayAccountTransactionRepository = (*accountRepository)(nil) + +// WithinGatewayAccountTransaction reuses the established repository tx scope: +// billing settings still use updateLockedAccount and its managed-state fences, +// bulk still uses its existing SQL merge, and bindings retain their live checks. +func (r *accountRepository) WithinGatewayAccountTransaction(ctx context.Context, id int64, groups []int64, run func(context.Context) error) (writeErr error) { + tx := dbent.TxFromContext(ctx) + owned := tx == nil + if owned { + var err error + tx, err = r.client.Tx(ctx) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + } else { + // Bulk callers may keep their outer transaction after a failed item. + // Roll back this item's staged fields even in that caller-owned scope. + if _, err := tx.Client().ExecContext(ctx, "SAVEPOINT gateway_account_update"); err != nil { + return err + } + defer func() { + cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + defer cancel() + if writeErr != nil { + _, err := tx.Client().ExecContext(cleanupCtx, "ROLLBACK TO SAVEPOINT gateway_account_update") + writeErr = errors.Join(writeErr, err) + if err != nil { + _ = tx.Rollback() + return + } + } + _, err := tx.Client().ExecContext(cleanupCtx, "RELEASE SAVEPOINT gateway_account_update") + writeErr = errors.Join(writeErr, err) + if err != nil { + _ = tx.Rollback() + } + }() + } + txctx := dbent.NewTxContext(ctx, tx) + // Match the existing binding lock order: group policies, then account row. + if err := lockLiveGroups(txctx, tx.Client(), groups); err != nil { + return err + } + if _, err := lockOAuthDegradationGroupBindings(txctx, tx.Client(), id, groups); err != nil { + return err + } + account, err := r.GetByID(txctx, id) + if err != nil { + return err + } + if !account.IsGateway() || account.Platform != service.PlatformGateway { + return service.ErrGatewayAccountIdentity + } + if err := run(txctx); err != nil { + return err + } + // Context-scoped repositories suppress precommit cache publication. Reuse + // the existing commit hook for caller-owned transactions as well as ours. + service.AfterAccountCommit(txctx, func(committed context.Context) { + r.syncSchedulerAccountSnapshot(committed, id) + }) + if owned { + return tx.Commit() + } + return nil +} diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 35164e4e4694..73627a43631c 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -149,6 +149,13 @@ type AccountDuplicateRepository interface { CreateWithAccountGroups(ctx context.Context, account *Account, groups []AccountGroup) error } +// GatewayAccountTransactionRepository keeps the new gateway's settings, exact +// memberships and outbox writes in one transaction. Legacy accounts retain +// their existing write paths. The callback receives the repository's tx context. +type GatewayAccountTransactionRepository interface { + WithinGatewayAccountTransaction(ctx context.Context, accountID int64, groupIDs []int64, run func(context.Context) error) error +} + // AccountBillingSettingsRepository applies an admin edit without overwriting a // rate_multiplier that a successful upstream probe synchronized after the edit // form was loaded. A nil rateMultiplier means the request did not edit it. @@ -382,6 +389,18 @@ func (s *AccountService) Update(ctx context.Context, id int64, req UpdateAccount if err := validateGatewayAccountGroups(ctx, account, s.groupRepo, ids); err != nil { return nil, err } + if !gatewayAccountTransactionActive(ctx) { + var updated *Account + err := withinGatewayAccountTransaction(ctx, s.accountRepo, id, ids, func(txctx context.Context) error { + var err error + updated, err = s.Update(txctx, id, req) + return err + }) + if err != nil { + return nil, err + } + return updated, err + } } if req.Name != nil { account.Name = *req.Name diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 25f92b84a1c5..960a00303e90 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -664,7 +664,7 @@ func (s *adminServiceImpl) CreateAccount(ctx context.Context, input *CreateAccou } func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *UpdateAccountInput) (*Account, error) { - if input.Platform != "" && s.entClient != nil && dbent.TxFromContext(ctx) == nil { + if input.Platform != "" && input.Platform != PlatformGateway && s.entClient != nil && dbent.TxFromContext(ctx) == nil { return s.scopedAdminTransaction(ctx, id, false, func(txctx context.Context) (*Account, error) { return s.UpdateAccount(txctx, id, input) }) @@ -696,6 +696,18 @@ func (s *adminServiceImpl) UpdateAccount(ctx context.Context, id int64, input *U if err := validateGatewayAccountGroups(ctx, account, s.groupRepo, gatewayGroupIDs); err != nil { return nil, err } + if account.IsGateway() && !gatewayAccountTransactionActive(ctx) { + var updated *Account + err := withinGatewayAccountTransaction(ctx, s.accountRepo, id, gatewayGroupIDs, func(txctx context.Context) error { + var err error + updated, err = s.UpdateAccount(txctx, id, input) + return err + }) + if err != nil { + return nil, err + } + return updated, err + } if err := prepareVertexAuthModeUpdate(account, input); err != nil { return nil, err } @@ -1510,10 +1522,25 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp if s.excelOAuthReauth != nil && bpsChanged { repoUpdates.ExcelBPSAuthorizationPending = pendingByAccount } - if _, err := s.accountRepo.BulkUpdate(ctx, input.AccountIDs, repoUpdates); err != nil { - return nil, err + // A failed gateway binding must roll back its metadata too. Keep legacy + // accounts on the existing batch path; each gateway with a membership edit + // commits its own fields+groups atomically and reports its own result. + legacyIDs := make([]int64, 0, len(input.AccountIDs)) + gatewayIDs := make(map[int64]bool) + for _, id := range input.AccountIDs { + if input.GroupIDs != nil && targetsByID[id] != nil && targetsByID[id].IsGateway() { + gatewayIDs[id] = true + } else { + legacyIDs = append(legacyIDs, id) + } + } + if len(legacyIDs) > 0 { + if _, err := s.accountRepo.BulkUpdate(ctx, legacyIDs, repoUpdates); err != nil { + return nil, err + } } + gatewayWriteCtx := ctx ctx = accounttimer.WithoutManualIntent(ctx) // 将 proxy 变更传播到每个目标账号的 spark 影子账号 @@ -1522,7 +1549,7 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp if *repoUpdates.ProxyID != 0 { effectiveProxyID = repoUpdates.ProxyID } - for _, accountID := range input.AccountIDs { + for _, accountID := range legacyIDs { if err := s.propagateProxyToShadows(ctx, accountID, effectiveProxyID); err != nil { return nil, err } @@ -1533,15 +1560,24 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp for _, accountID := range input.AccountIDs { entry := BulkUpdateAccountResult{AccountID: accountID} - if input.GroupIDs != nil { - if err := s.accountRepo.BindGroups(ctx, accountID, *input.GroupIDs); err != nil { - entry.Success = false - entry.Error = err.Error() - result.Failed++ - result.FailedIDs = append(result.FailedIDs, accountID) - result.Results = append(result.Results, entry) - continue - } + var bindingErr error + if gatewayIDs[accountID] { + bindingErr = withinGatewayAccountTransaction(gatewayWriteCtx, s.accountRepo, accountID, *input.GroupIDs, func(txctx context.Context) error { + if _, err := s.accountRepo.BulkUpdate(txctx, []int64{accountID}, repoUpdates); err != nil { + return err + } + return s.accountRepo.BindGroups(accounttimer.WithoutManualIntent(txctx), accountID, *input.GroupIDs) + }) + } else if input.GroupIDs != nil { + bindingErr = s.accountRepo.BindGroups(ctx, accountID, *input.GroupIDs) + } + if bindingErr != nil { + entry.Success = false + entry.Error = bindingErr.Error() + result.Failed++ + result.FailedIDs = append(result.FailedIDs, accountID) + result.Results = append(result.Results, entry) + continue } entry.Success = true diff --git a/backend/internal/service/gateway_account.go b/backend/internal/service/gateway_account.go index f22f559fcb06..ca072e6ddc3f 100644 --- a/backend/internal/service/gateway_account.go +++ b/backend/internal/service/gateway_account.go @@ -17,6 +17,24 @@ const GatewayUpstreamKindCredentialKey = "upstream_kind" var ErrGatewayAccountIdentity = infraerrors.BadRequest("INVALID_GATEWAY_ACCOUNT", "gateway accounts require platform/type gateway, upstream_kind new_api or sub2api, a site URL and an API key") var ErrGatewayAccountGroup = infraerrors.BadRequest("INVALID_GATEWAY_GROUP", "gateway accounts require an existing concrete or composite group that does not require OAuth") var ErrGatewayProtocolsPending = infraerrors.BadRequest("GATEWAY_PROTOCOLS_PENDING", "gateway scheduling and forwarding are not available yet") +var ErrGatewayAtomicUpdateRequired = infraerrors.BadRequest("GATEWAY_ATOMIC_UPDATE_REQUIRED", "gateway updates require transactional account and group writes") + +type gatewayAccountTransactionKey struct{} + +func gatewayAccountTransactionActive(ctx context.Context) bool { + active, _ := ctx.Value(gatewayAccountTransactionKey{}).(bool) + return active +} + +func withinGatewayAccountTransaction(ctx context.Context, repo AccountRepository, id int64, groups []int64, run func(context.Context) error) error { + writer, ok := repo.(GatewayAccountTransactionRepository) + if !ok { + return ErrGatewayAtomicUpdateRequired + } + return writer.WithinGatewayAccountTransaction(ctx, id, groups, func(txctx context.Context) error { + return run(context.WithValue(txctx, gatewayAccountTransactionKey{}, true)) + }) +} // ValidateGatewayAccountIdentity reserves an account-only identity. Legacy // records are neither reclassified nor subjected to new credential validation. diff --git a/backend/internal/service/gateway_account_management_test.go b/backend/internal/service/gateway_account_management_test.go index 4a2d12eb8df2..0420cee59e62 100644 --- a/backend/internal/service/gateway_account_management_test.go +++ b/backend/internal/service/gateway_account_management_test.go @@ -16,6 +16,20 @@ func gatewayManagementFixture() *Account { Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example/tenant", "api_key": "synthetic-key"}} } +type gatewayManagementAtomicRepo struct { + *accountRepoStubForBulkUpdate + transactions int + transactionErr error +} + +func (r *gatewayManagementAtomicRepo) WithinGatewayAccountTransaction(ctx context.Context, _ int64, _ []int64, run func(context.Context) error) error { + r.transactions++ + if r.transactionErr != nil { + return r.transactionErr + } + return run(ctx) +} + func TestGatewayManagementIdentityIsAccountOnly(t *testing.T) { a := gatewayManagementFixture() require.NoError(t, ValidateGatewayAccountIdentity(a.Platform, a.Type, a.Credentials)) @@ -94,11 +108,12 @@ func TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups(t *t func TestGatewayManagementUpdatePreservesKeyAndRejectsIdentityConversion(t *testing.T) { a := gatewayManagementFixture() - repo := &accountRepoStubForBulkUpdate{getByIDAccounts: map[int64]*Account{959: a}} + repo := &gatewayManagementAtomicRepo{accountRepoStubForBulkUpdate: &accountRepoStubForBulkUpdate{getByIDAccounts: map[int64]*Account{959: a}}} svc := &adminServiceImpl{accountRepo: repo} updated, err := svc.UpdateAccount(context.Background(), 959, &UpdateAccountInput{ Name: "Edited gateway", Credentials: map[string]any{"base_url": "https://edited.example"}}) require.NoError(t, err) + require.Equal(t, 1, repo.transactions) require.Equal(t, "synthetic-key", updated.Credentials["api_key"]) require.Equal(t, "new_api", updated.Credentials["upstream_kind"]) for _, input := range []*UpdateAccountInput{{Platform: PlatformOpenAI}, {Type: AccountTypeAPIKey}, {Credentials: map[string]any{"upstream_kind": "unknown"}}} { @@ -113,6 +128,49 @@ func TestGatewayManagementUpdatePreservesKeyAndRejectsIdentityConversion(t *test require.Empty(t, legacyRepo.updatedAccounts) } +func TestGatewayManagementUpdateRequiresAtomicCapability(t *testing.T) { + for _, route := range []string{"admin", "account-service", "bulk"} { + t.Run(route, func(t *testing.T) { + a := gatewayManagementFixture() + repo := &accountRepoStubForBulkUpdate{getByIDAccounts: map[int64]*Account{a.ID: a}, getByIDsAccounts: []*Account{a}} + groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{1: {ID: 1, Platform: PlatformOpenAI}}} + ids := []int64{1} + admin := &adminServiceImpl{accountRepo: repo, groupRepo: groups} + switch route { + case "admin": + _, err := admin.UpdateAccount(context.Background(), a.ID, &UpdateAccountInput{GroupIDs: &ids, Name: "must not save"}) + require.ErrorIs(t, err, ErrGatewayAtomicUpdateRequired) + case "account-service": + _, err := NewAccountService(repo, groups).Update(context.Background(), a.ID, UpdateAccountRequest{GroupIDs: &ids}) + require.ErrorIs(t, err, ErrGatewayAtomicUpdateRequired) + case "bulk": + result, err := admin.BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{AccountIDs: []int64{a.ID}, GroupIDs: &ids, Name: "must not save", SkipMixedChannelCheck: true}) + require.NoError(t, err) + require.Equal(t, []int64{a.ID}, result.FailedIDs) + } + require.Empty(t, repo.updatedAccounts) + require.Zero(t, repo.bulkUpdateCalls) + require.Empty(t, repo.bindGroupsCalls) + }) + } +} + +func TestGatewayManagementMixedBulkRetainsLegacyWritePath(t *testing.T) { + gateway := gatewayManagementFixture() + legacy := &Account{ID: 7, Platform: PlatformOpenAI, Type: AccountTypeAPIKey} + repo := &gatewayManagementAtomicRepo{accountRepoStubForBulkUpdate: &accountRepoStubForBulkUpdate{getByIDsAccounts: []*Account{legacy, gateway}}, transactionErr: ErrGatewayAccountGroup} + groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{1: {ID: 1, Platform: PlatformOpenAI}}} + ids := []int64{1} + result, err := (&adminServiceImpl{accountRepo: repo, groupRepo: groups}).BulkUpdateAccounts(context.Background(), &BulkUpdateAccountsInput{ + AccountIDs: []int64{legacy.ID, gateway.ID}, GroupIDs: &ids, Name: "fixture edit", SkipMixedChannelCheck: true}) + require.NoError(t, err) + require.Equal(t, []int64{legacy.ID}, repo.bulkUpdateIDs, "gateway fields must never enter the legacy batch before membership validation") + require.Equal(t, []int64{legacy.ID}, repo.bindGroupsCalls) + require.Equal(t, []int64{legacy.ID}, result.SuccessIDs) + require.Equal(t, []int64{gateway.ID}, result.FailedIDs) + require.Equal(t, 1, repo.transactions) +} + func TestGatewayManagementAccountServiceRejectsOAuthGroupsBeforeCreate(t *testing.T) { repo := &accountRepoStubForBulkUpdate{createID: 959} groups := &groupRepoStubForAdmin{getByIDByID: map[int64]*Group{1: {ID: 1, Platform: PlatformComposite, RequireOAuthOnly: true}}} From 40dbf59d433f5610ddb0065e8d82935e2495059f Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 02:14:48 +0800 Subject: [PATCH 03/26] fix: disambiguate gateway account platform constant Rename only the new domain account-platform constant to AccountPlatformGateway and point the service alias at it. Preserve the existing PlatformGateway type, its protocol catalog and the persisted gateway string. Addresses the concrete PR971 remote compilation failure; dynamic validation remains remote CI only. --- backend/internal/domain/constants.go | 4 ++-- backend/internal/service/gateway_account.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/backend/internal/domain/constants.go b/backend/internal/domain/constants.go index 718087c50f27..49629dbd1565 100644 --- a/backend/internal/domain/constants.go +++ b/backend/internal/domain/constants.go @@ -44,8 +44,8 @@ const ( PlatformComposite = "composite" ) -// PlatformGateway is an account-only identity, never a request or group platform. -const PlatformGateway = "gateway" +// AccountPlatformGateway is an account-only identity, never a request or group platform. +const AccountPlatformGateway = "gateway" // Account mode constants 区分国产供应商的「按量付费(余额)」与「Coding Plan」两种接入方式。 // 存储于 credentials["account_mode"],决定 base_url 预设与额度监控方式。 diff --git a/backend/internal/service/gateway_account.go b/backend/internal/service/gateway_account.go index ca072e6ddc3f..f5b5dd6d514c 100644 --- a/backend/internal/service/gateway_account.go +++ b/backend/internal/service/gateway_account.go @@ -11,7 +11,7 @@ import ( ) // PlatformGateway is reserved for account storage and is excluded from the catalog. -const PlatformGateway = domain.PlatformGateway +const PlatformGateway = domain.AccountPlatformGateway const GatewayUpstreamKindCredentialKey = "upstream_kind" var ErrGatewayAccountIdentity = infraerrors.BadRequest("INVALID_GATEWAY_ACCOUNT", "gateway accounts require platform/type gateway, upstream_kind new_api or sub2api, a site URL and an API key") From 27b1864685c4cae77c07db229edd01c36fe1be04 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 02:26:39 +0800 Subject: [PATCH 04/26] feat: persist request-scoped gateway procurement cost evidence Refs #959. Capture concrete-target New API cost multipliers independently of customer charges, preserve them through every native usage insert/read and durable event replay, expose admin-only evidence, and use snapshots once in SmartOps procurement estimates. Add forward-only nullable metadata migration with immutable snapshots, unknown-cost semantics, legacy fallback coverage and remote-only regression sources. Wallet accounting and gateway admission remain unchanged. --- .../workflows/issue959-gateway-regression.yml | 24 ++- backend/internal/handler/dto/mappers.go | 1 + .../dto/procurement_cost_snapshot_test.go | 23 +++ backend/internal/handler/dto/types.go | 2 + ...curement_cost_snapshot_integration_test.go | 149 ++++++++++++++++++ .../internal/repository/profit_operations.go | 40 ++++- .../repository/usage_log_repo_insert.go | 36 +++-- .../repository/usage_log_repo_query.go | 11 +- .../usage_log_repo_request_type_test.go | 14 +- .../usage_log_session_id_unit_test.go | 14 +- .../internal/service/gateway_usage_billing.go | 1 + .../internal/service/openai_gateway_usage.go | 1 + .../service/procurement_cost_snapshot.go | 28 ++++ .../service/procurement_cost_snapshot_test.go | 95 +++++++++++ backend/internal/service/usage_log.go | 3 +- .../391_usage_procurement_cost_snapshot.sql | 18 +++ 16 files changed, 429 insertions(+), 31 deletions(-) create mode 100644 backend/internal/handler/dto/procurement_cost_snapshot_test.go create mode 100644 backend/internal/repository/procurement_cost_snapshot_integration_test.go create mode 100644 backend/internal/service/procurement_cost_snapshot.go create mode 100644 backend/internal/service/procurement_cost_snapshot_test.go create mode 100644 backend/migrations/391_usage_procurement_cost_snapshot.sql diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index 02d2299a37ee..ea0c3edc882a 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -13,6 +13,11 @@ on: - 'backend/internal/repository/group_repo.go' - 'backend/internal/repository/gateway_account*' - 'backend/internal/repository/oauth_degradation_group_bindings*' + - 'backend/internal/repository/procurement_cost_snapshot*' + - 'backend/internal/repository/profit_operations.go' + - 'backend/internal/repository/usage_log_repo*' + - 'backend/internal/handler/dto/procurement_cost_snapshot*' + - 'backend/migrations/391_usage_procurement_cost_snapshot.sql' - 'backend/internal/repository/concurrency_cache*' - 'backend/internal/repository/integration_harness_test.go' - 'backend/go.mod' @@ -73,7 +78,7 @@ jobs: run: | set -euo pipefail go test -race -tags=unit ./internal/service ./internal/handler/admin ./internal/handler/dto ./internal/repository \ - -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots)' \ + -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots|ProcurementSnapshot)' \ -count=1 -v -timeout=10m 2>&1 | tee ../evidence/unit-race.log if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/unit-race.log; then exit 1 @@ -87,6 +92,8 @@ jobs: grep -F -- '--- PASS: TestGatewayManagementRepositoryBindingGuard' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayDataImportIdentityValidation' ../evidence/unit-race.log grep -F -- '--- PASS: TestAccountGatewayDTORedactsCallingKey' ../evidence/unit-race.log + grep -F -- '--- PASS: TestProcurementSnapshotMixedTargetsThroughUsageWriters' ../evidence/unit-race.log + grep -F -- '--- PASS: TestProcurementSnapshotAdminDTOAndUserPrivacy' ../evidence/unit-race.log - name: Shared account slots against isolated Redis working-directory: backend shell: bash @@ -104,6 +111,21 @@ jobs: grep -F -- '--- PASS: TestGatewayAtomicUpdateRollbackAfterStagedFields' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestGatewayAtomicUpdateSuccessfulCommit' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestGatewayAtomicUpdateCallerTransactionRollback' ../evidence/concurrency-redis.log + - name: Procurement snapshots and legacy profit accounting + working-directory: backend + shell: bash + run: | + set -euo pipefail + go test -race -tags=integration ./internal/repository \ + -run '^(TestProcurementSnapshot|TestProfitOperationsPersistedProfitIndependentFromAccountDebit|TestProfitOperationsZeroLossUnknownAndCurrentConfiguration)' \ + -count=1 -v -timeout=10m 2>&1 | tee ../evidence/procurement-cost.log + if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/procurement-cost.log; then + exit 1 + fi + grep -F -- '--- PASS: TestProcurementSnapshotAllInsertPathsAndImmutability' ../evidence/procurement-cost.log + grep -F -- '--- PASS: TestProcurementSnapshotDurableReplayDoesNotRepriceOrRecharge' ../evidence/procurement-cost.log + grep -F -- '--- PASS: TestProcurementSnapshotProfitUsesMixedRequestTargetsAndUnknowns' ../evidence/procurement-cost.log + grep -F -- '--- PASS: TestProcurementSnapshotMigrationLeavesHistoryAndChargesUntouched' ../evidence/procurement-cost.log - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index 99292b7a1c7d..aa4d33ec4d3f 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -831,6 +831,7 @@ func UsageLogFromServiceAdmin(l *service.UsageLog) *AdminUsageLog { BillingTier: l.BillingTier, AccountRateMultiplier: l.AccountRateMultiplier, AccountStatsCost: l.AccountStatsCost, + ProcurementCostSnapshot: l.ProcurementCostSnapshot, IPAddress: l.IPAddress, Account: AccountSummaryFromService(l.Account), } diff --git a/backend/internal/handler/dto/procurement_cost_snapshot_test.go b/backend/internal/handler/dto/procurement_cost_snapshot_test.go new file mode 100644 index 000000000000..e8678bbecee6 --- /dev/null +++ b/backend/internal/handler/dto/procurement_cost_snapshot_test.go @@ -0,0 +1,23 @@ +package dto + +import ( + "encoding/json" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +func TestProcurementSnapshotAdminDTOAndUserPrivacy(t *testing.T) { + factor := .7 + log := &service.UsageLog{TotalCost: 10, ActualCost: 3, ProcurementCostSnapshot: &service.ProcurementCostSnapshot{ + Version: 1, AccountType: "gateway", Provider: "new_api", TargetPlatform: "openai", Basis: "total_cost", CostMultiplier: &factor}} + admin, err := json.Marshal(UsageLogFromServiceAdmin(log)) + require.NoError(t, err) + require.Contains(t, string(admin), `"procurement_cost_snapshot"`) + require.Contains(t, string(admin), `"cost_multiplier":0.7`) + user, err := json.Marshal(UsageLogFromService(log)) + require.NoError(t, err) + require.NotContains(t, string(user), "procurement_cost_snapshot") + require.Nil(t, UsageLogFromServiceAdmin(&service.UsageLog{}).ProcurementCostSnapshot) +} diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go index e09f36447299..c26e768d90e8 100644 --- a/backend/internal/handler/dto/types.go +++ b/backend/internal/handler/dto/types.go @@ -746,6 +746,8 @@ type AdminUsageLog struct { AccountRateMultiplier *float64 `json:"account_rate_multiplier"` // AccountStatsCost 自定义定价规则计算的账号统计费用(nil 表示使用默认公式) AccountStatsCost *float64 `json:"account_stats_cost,omitempty"` + // ProcurementCostSnapshot is supplier-cost evidence visible only to admins. + ProcurementCostSnapshot *service.ProcurementCostSnapshot `json:"procurement_cost_snapshot,omitempty"` // IPAddress 用户请求 IP IPAddress *string `json:"ip_address,omitempty"` diff --git a/backend/internal/repository/procurement_cost_snapshot_integration_test.go b/backend/internal/repository/procurement_cost_snapshot_integration_test.go new file mode 100644 index 000000000000..40ed5a8b06e5 --- /dev/null +++ b/backend/internal/repository/procurement_cost_snapshot_integration_test.go @@ -0,0 +1,149 @@ +//go:build integration + +package repository + +import ( + "context" + "encoding/json" + "fmt" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/Wei-Shaw/sub2api/migrations" + "github.com/stretchr/testify/require" +) + +func procurementFixtureSnapshot(platform string, factor *float64) *service.ProcurementCostSnapshot { + return &service.ProcurementCostSnapshot{Version: 1, AccountType: "gateway", Provider: "new_api", TargetPlatform: platform, Basis: "total_cost", CostMultiplier: factor} +} + +func TestProcurementSnapshotAllInsertPathsAndImmutability(t *testing.T) { + f := newChannelOperationsFixture(t) + repo := newUsageLogRepositoryWithSQL(integrationEntClient, integrationDB) + for _, mode := range []string{"single", "batch", "best-effort-single", "best-effort-batch", "legacy"} { + t.Run(mode, func(t *testing.T) { + factor := .7 + log := &service.UsageLog{UserID: f.user, APIKeyID: f.key, AccountID: f.account, RequestID: fmt.Sprintf("procurement-%d-%s", f.account, mode), + Platform: "openai", Model: "fixture-model", TotalCost: 10, ActualCost: 3, CreatedAt: time.Now().UTC()} + if mode != "legacy" { + log.ProcurementCostSnapshot = procurementFixtureSnapshot("openai", &factor) + } + prepared := prepareUsageLogInsert(log) + var err error + switch mode { + case "single", "legacy": + _, err = repo.createSingle(t.Context(), integrationDB, log) + case "batch": + key := usageLogBatchKey(log.RequestID, log.APIKeyID) + _, _, _, err = repo.batchInsertUsageLogs(integrationDB, []string{key}, map[string]usageLogInsertPrepared{key: prepared}) + case "best-effort-single": + err = execUsageLogInsertNoResult(t.Context(), integrationDB, prepared) + case "best-effort-batch": + query, args := buildUsageLogBestEffortInsertQuery([]usageLogInsertPrepared{prepared}) + _, err = integrationDB.ExecContext(t.Context(), query, args...) + } + require.NoError(t, err) + stored, err := scanUsageLog(integrationDB.QueryRowContext(t.Context(), "SELECT "+usageLogSelectColumns+" FROM usage_logs WHERE request_id=$1 AND api_key_id=$2", log.RequestID, f.key)) + require.NoError(t, err) + require.Equal(t, log.ProcurementCostSnapshot, stored.ProcurementCostSnapshot) + require.Equal(t, 10.0, stored.TotalCost) + require.Equal(t, 3.0, stored.ActualCost) + if mode != "legacy" { + log.ProcurementCostSnapshot = procurementFixtureSnapshot("openai", nil) + _, err = repo.createSingle(t.Context(), integrationDB, log) + require.NoError(t, err) + var saved float64 + require.NoError(t, integrationDB.QueryRow(`SELECT (procurement_cost_snapshot->>'cost_multiplier')::numeric FROM usage_logs WHERE id=$1`, stored.ID).Scan(&saved)) + require.Equal(t, .7, saved, "dedup must retain the first snapshot") + _, err = integrationDB.Exec(`UPDATE usage_logs SET procurement_cost_snapshot=NULL WHERE id=$1`, stored.ID) + require.ErrorContains(t, err, "immutable") + } + }) + } +} + +func TestProcurementSnapshotDurableReplayDoesNotRepriceOrRecharge(t *testing.T) { + repo, cmd, usage, _ := durableBillingFixture(t) + factor := .7 + usage.Platform, usage.TotalCost, usage.ActualCost = "openai", 10, 3 + cmd.BalanceCost, cmd.APIKeyQuotaCost = 3, 3 + usage.ProcurementCostSnapshot = procurementFixtureSnapshot("openai", &factor) + require.NoError(t, repo.StageUsageBilling(t.Context(), &cmd, &usage)) + usage.ProcurementCostSnapshot = procurementFixtureSnapshot("kimi", nil) + require.NoError(t, repo.StageUsageBilling(t.Context(), &cmd, &usage)) + key := service.UsageBillingEventKey{RequestID: cmd.RequestID, APIKeyID: cmd.APIKeyID} + for i := 0; i < 2; i++ { + _, err := repo.ApplyStagedUsageBilling(t.Context(), key) + require.NoError(t, err) + } + stored, err := scanUsageLog(repo.db.QueryRowContext(t.Context(), "SELECT "+usageLogSelectColumns+" FROM usage_logs WHERE request_id=$1 AND api_key_id=$2", cmd.RequestID, cmd.APIKeyID)) + require.NoError(t, err) + require.Equal(t, "openai", stored.ProcurementCostSnapshot.TargetPlatform) + require.Equal(t, .7, *stored.ProcurementCostSnapshot.CostMultiplier) + var balance, quota float64 + require.NoError(t, repo.db.QueryRow(`SELECT balance FROM users WHERE id=$1`, cmd.UserID).Scan(&balance)) + require.NoError(t, repo.db.QueryRow(`SELECT quota_used FROM api_keys WHERE id=$1`, cmd.APIKeyID).Scan("a)) + require.Equal(t, 97.0, balance, "user charge is actual_cost=3, never procurement 7") + require.Equal(t, 3.0, quota, "replay cannot double-charge") +} + +func TestProcurementSnapshotProfitUsesMixedRequestTargetsAndUnknowns(t *testing.T) { + f := newChannelOperationsFixture(t) + now := time.Now().UTC() + _, err := integrationDB.Exec(`UPDATE accounts SET type='gateway',platform='gateway',credentials='{"upstream_kind":"new_api","base_url":"https://gateway.example/tenant","api_key":"synthetic-only"}',extra='{"cost_multiplier":99}',rate_multiplier=77 WHERE id=$1`, f.account) + require.NoError(t, err) + repo := newUsageLogRepositoryWithSQL(integrationEntClient, integrationDB) + for i, target := range []string{"openai", "kimi"} { + factor := []float64{.7, .1}[i] + _, err = repo.createSingle(t.Context(), integrationDB, &service.UsageLog{UserID: f.user, APIKeyID: f.key, AccountID: f.account, + RequestID: fmt.Sprintf("procurement-mixed-%d-%d", f.account, i), Platform: target, Model: "fixture-model", TotalCost: 10, ActualCost: 3, + CreatedAt: now.Add(-time.Hour), ProcurementCostSnapshot: procurementFixtureSnapshot(target, &factor)}) + require.NoError(t, err) + } + filter := service.UpstreamOperationsFilter{From: now.Add(-24 * time.Hour), Until: now, AccountID: f.account, Dimension: "account", ModelScope: "public", Sort: "requests", Direction: "desc", Page: 1, PageSize: 20} + read := func() map[string]any { + out, err := f.repo.ReadProfitOperations(t.Context(), filter) + require.NoError(t, err) + var data map[string]any + require.NoError(t, json.Unmarshal(out.Usage, &data)) + return data["summary"].(map[string]any) + } + summary := read() + require.Equal(t, 8.0, summary["estimated_cost"], "10*.7 + 10*.1 exactly once; never account debit 77 or current cost 99") + require.Equal(t, 6.0, summary["request_income"]) + require.Equal(t, -2.0, summary["estimated_profit"]) + _, err = integrationDB.Exec(`UPDATE accounts SET extra='{"cost_multiplier":0.01}',rate_multiplier=1 WHERE id=$1`, f.account) + require.NoError(t, err) + require.Equal(t, summary["estimated_cost"], read()["estimated_cost"], "account edits cannot reprice captured requests") + factor := .7 + future := procurementFixtureSnapshot("openai", &factor) + future.Version = 99 + for i, snapshot := range []*service.ProcurementCostSnapshot{nil, procurementFixtureSnapshot("openai", nil), future, procurementFixtureSnapshot("kimi", &factor)} { + _, err = repo.createSingle(t.Context(), integrationDB, &service.UsageLog{UserID: f.user, APIKeyID: f.key, AccountID: f.account, + RequestID: fmt.Sprintf("procurement-unknown-%d-%d", f.account, i), Platform: "openai", Model: "fixture-model", TotalCost: 10, ActualCost: 3, + CreatedAt: now.Add(-time.Hour), ProcurementCostSnapshot: snapshot}) + require.NoError(t, err) + } + summary = read() + require.Nil(t, summary["estimated_cost"]) + require.Equal(t, 4.0, summary["unknown_cost_requests"], "missing, captured unknown, unsupported version and mismatched target all stay unknown") + require.Equal(t, 8.0, summary["covered_estimated_cost"]) +} + +func TestProcurementSnapshotMigrationLeavesHistoryAndChargesUntouched(t *testing.T) { + tx, err := integrationDB.BeginTx(context.Background(), nil) + require.NoError(t, err) + defer func() { _ = tx.Rollback() }() + _, err = tx.Exec(`CREATE TEMP TABLE usage_logs(id bigint,total_cost numeric,actual_cost numeric) ON COMMIT DROP; INSERT INTO usage_logs VALUES(1,10,3)`) + require.NoError(t, err) + sql, err := migrations.FS.ReadFile("391_usage_procurement_cost_snapshot.sql") + require.NoError(t, err) + for i := 0; i < 2; i++ { + _, err = tx.Exec(string(sql)) + require.NoError(t, err) + } + var unchanged bool + require.NoError(t, tx.QueryRow(`SELECT procurement_cost_snapshot IS NULL AND total_cost=10 AND actual_cost=3 FROM usage_logs WHERE id=1`).Scan(&unchanged)) + require.True(t, unchanged) +} diff --git a/backend/internal/repository/profit_operations.go b/backend/internal/repository/profit_operations.go index 648f4643265a..93600ba8b839 100644 --- a/backend/internal/repository/profit_operations.go +++ b/backend/internal/repository/profit_operations.go @@ -21,6 +21,7 @@ func profitOperationsAccounts(ctx context.Context, tx *sql.Tx, f service.Upstrea var accounts []struct { operationsAccount Multiplier *float64 `json:"multiplier"` + AccountType string `json:"account_type"` CostBasis string `json:"cost_basis"` URLKey string `json:"url_key"` URLAttribution string `json:"url_attribution"` @@ -37,16 +38,18 @@ func profitOperationsAccounts(ctx context.Context, tx *sql.Tx, f service.Upstrea if err = json.Unmarshal(raw, &accounts); err != nil { return nil, err } - rows, err := tx.QueryContext(ctx, `SELECT id,extra->'cost_multiplier' FROM accounts WHERE id IN (SELECT id FROM jsonb_to_recordset($1::jsonb) c(id bigint))`, string(raw)) + rows, err := tx.QueryContext(ctx, `SELECT id,type,extra->'cost_multiplier' FROM accounts WHERE id IN (SELECT id FROM jsonb_to_recordset($1::jsonb) c(id bigint))`, string(raw)) if err != nil { return nil, err } defer func() { _ = rows.Close() }() costs := map[int64]any{} + accountTypes := map[int64]string{} for rows.Next() { var id int64 var value []byte - if err = rows.Scan(&id, &value); err != nil { + var accountType string + if err = rows.Scan(&id, &accountType, &value); err != nil { return nil, err } var cost any @@ -56,6 +59,7 @@ func profitOperationsAccounts(ctx context.Context, tx *sql.Tx, f service.Upstrea } } costs[id] = cost + accountTypes[id] = accountType } if err = rows.Err(); err != nil { return nil, err @@ -66,6 +70,11 @@ func profitOperationsAccounts(ctx context.Context, tx *sql.Tx, f service.Upstrea v, basis := service.OperationsCostMultiplier(&service.Account{Extra: map[string]any{"cost_multiplier": costs[id]}}) a.Multiplier = v a.CostBasis = basis + a.AccountType = accountTypes[id] + if a.AccountType == service.AccountTypeGateway { + a.Multiplier = nil + a.CostBasis = "request_procurement_unknown" + } } if err = rows.Close(); err != nil { return nil, err @@ -178,11 +187,25 @@ func profitOAuthChannels(ctx context.Context, tx *sql.Tx, raw string) (map[int64 } const profitOperationsCohort = `accounts_config AS ( - SELECT * FROM jsonb_to_recordset($3::jsonb) AS c(id bigint,name text,key text,attribution text,updated_at timestamptz,deleted boolean,multiplier numeric,cost_basis text,schedulable boolean,concurrency integer,status text,url_key text,url_attribution text,url_channel_id bigint,url_origin_hash text,channel_id bigint,channel_name text,channel_code text,channel_remark text,channel_revision bigint,assignment text,oauth_channel_id bigint) + SELECT * FROM jsonb_to_recordset($3::jsonb) AS c(id bigint,name text,key text,attribution text,updated_at timestamptz,deleted boolean,multiplier numeric,cost_basis text,schedulable boolean,concurrency integer,status text,url_key text,url_attribution text,url_channel_id bigint,url_origin_hash text,channel_id bigint,channel_name text,channel_code text,channel_remark text,channel_revision bigint,assignment text,oauth_channel_id bigint,account_type text) ), cohort AS ( SELECT * FROM accounts_config WHERE ($4='' OR key=$4) AND ($5::bigint=0 OR id=$5) AND ($11::bigint=0 OR channel_id=$11) )` +// A captured unknown/unsupported snapshot never falls back to today's account +// settings. The multiplier already includes New API's request-target x1/x7. +const profitRequestCostMultiplierSQL = `CASE WHEN u.procurement_cost_snapshot IS NOT NULL THEN + CASE WHEN u.procurement_cost_snapshot->>'version'='1' + AND u.procurement_cost_snapshot->>'basis'='total_cost' + AND u.procurement_cost_snapshot->>'account_type'='gateway' + AND u.procurement_cost_snapshot->>'provider'='new_api' + AND u.procurement_cost_snapshot->>'target_platform'=u.platform + AND u.platform<>'' AND u.platform<>'composite' + AND jsonb_typeof(u.procurement_cost_snapshot->'cost_multiplier')='number' + THEN CASE WHEN (u.procurement_cost_snapshot->>'cost_multiplier')::numeric BETWEEN 0 AND 1000000 + THEN (u.procurement_cost_snapshot->>'cost_multiplier')::numeric END END + WHEN c.account_type='gateway' THEN NULL ELSE c.multiplier END` + // Join the complete projection before applying the selected cohort. Joining only // cohort would turn every configured account outside it into account_missing. const profitOperationsBase = `WITH ` + profitOperationsCohort + `, event_rows AS ( @@ -190,7 +213,9 @@ const profitOperationsBase = `WITH ` + profitOperationsCohort + `, event_rows AS u.account_stats_cost,u.input_tokens,u.output_tokens,u.cache_read_tokens,u.cache_creation_tokens,u.duration_ms,u.billing_type,u.created_at,u.queue_timing,u.queue_wait_ms, COALESCE('channel:'||owner.channel_id::text,c.url_key,'unknown:account_missing') AS upstream_key, CASE WHEN e.channel_id IS NOT NULL OR h.channel_id IS NOT NULL THEN 'historical_channel' WHEN legacy.channel_id IS NOT NULL THEN 'legacy_channel_estimate' WHEN owner.channel_id IS NOT NULL THEN 'provider_url' ELSE COALESCE(c.url_attribution,'account_missing') END AS attribution, - c.name AS account_name,c.updated_at AS config_updated_at,c.deleted,c.multiplier,owner.channel_id AS explicit_channel_id,ch.name AS channel_name,ch.code AS channel_code,ch.remark AS channel_remark,ch.revision AS channel_revision,p.id AS provider_id,p.site_type AS provider_site_type, + c.name AS account_name,c.updated_at AS config_updated_at,c.deleted,` + profitRequestCostMultiplierSQL + ` AS multiplier, + u.procurement_cost_snapshot IS NOT NULL AS has_procurement_snapshot, + owner.channel_id AS explicit_channel_id,ch.name AS channel_name,ch.code AS channel_code,ch.remark AS channel_remark,ch.revision AS channel_revision,p.id AS provider_id,p.site_type AS provider_site_type, CASE WHEN snap.amount IS NOT NULL THEN snap.amount WHEN $18::bool AND jsonb_typeof(p.metrics->'today_spend')='number' AND p.observed_at>=$12::timestamptz AND p.observed_at<$13::timestamptz THEN (p.metrics->>'today_spend')::numeric END AS wallet_spend, CASE WHEN snap.amount IS NOT NULL AND snap.currency IN ('USD','CNY','quota_units') THEN snap.currency @@ -203,7 +228,8 @@ const profitOperationsBase = `WITH ` + profitOperationsCohort + `, event_rows AS CASE WHEN h.assignment='manual_unlinked' AND owner.channel_id IS NOT NULL THEN CASE WHEN c.url_key='unknown:oauth_dynamic_endpoint' THEN 'provider_import' ELSE 'provider_url' END END, h.assignment, CASE WHEN legacy.channel_id IS NOT NULL THEN 'explicit' WHEN owner.channel_id IS NOT NULL AND c.url_key='unknown:oauth_dynamic_endpoint' THEN 'provider_import' WHEN owner.channel_id IS NOT NULL THEN 'provider_url' WHEN c.url_key IS NULL OR c.url_key LIKE 'unknown:%' THEN 'unbound_unknown' ELSE 'unbound_url' END) AS assignment, - e.amount AS upstream_reported,e.settled_amount AS upstream_debit,COALESCE(c.cost_basis,'account_missing') AS cost_basis, + e.amount AS upstream_reported,e.settled_amount AS upstream_debit, + CASE WHEN u.procurement_cost_snapshot IS NOT NULL THEN 'request_procurement_snapshot' ELSE COALESCE(c.cost_basis,'account_missing') END AS cost_basis, COALESCE(NULLIF(u.requested_model,''),u.model) AS public_model, u.total_cost AS cost_base FROM usage_logs u LEFT JOIN accounts_config c ON c.id=u.account_id @@ -399,9 +425,9 @@ func (r *channelRepository) ReadProfitOperations(ctx context.Context, f service. 'catalog',COALESCE((SELECT jsonb_agg(to_jsonb(g)) FROM (SELECT key AS key,COALESCE(NULLIF(max(channel_name),''),key) AS name,max(channel_id) AS channel_id,max(channel_code) AS channel_code,max(channel_remark) AS channel_remark,max(channel_revision) AS channel_revision,max(assignment) AS assignment,count(*) AS accounts FROM cohort c WHERE NOT deleted AND ($6::bigint=0 OR EXISTS(SELECT 1 FROM account_groups ag WHERE ag.account_id=c.id AND ag.group_id=$6)) GROUP BY key ORDER BY key LIMIT $9 OFFSET $10)g),'[]'::jsonb), 'capacity',(SELECT jsonb_build_object('accounts',count(*),'schedulable',count(*) FILTER(WHERE schedulable AND status='active'),'configured_concurrency',COALESCE(sum(concurrency),0)) FROM cohort c WHERE NOT deleted AND ($6::bigint=0 OR EXISTS(SELECT 1 FROM account_groups ag WHERE ag.account_id=c.id AND ag.group_id=$6))), 'catalog_total',(SELECT count(DISTINCT key) FROM cohort c WHERE NOT deleted AND ($6::bigint=0 OR EXISTS(SELECT 1 FROM account_groups ag WHERE ag.account_id=c.id AND ag.group_id=$6))), - 'account_details_limit',100,'historical_upstream_snapshot_requests',(SELECT count(*) FROM priced WHERE attribution='historical_channel'),'historical_cost_multiplier_snapshot_requests',0, + 'account_details_limit',100,'historical_upstream_snapshot_requests',(SELECT count(*) FROM priced WHERE attribution='historical_channel'),'historical_cost_multiplier_snapshot_requests',(SELECT count(*) FROM priced WHERE has_procurement_snapshot AND multiplier IS NOT NULL), 'wallet_synced_at',(SELECT to_jsonb(max(observed_at)) FROM provider_spend_snapshots WHERE window_from=$1 AND window_until=$2 AND amount IS NOT NULL), - 'cost_formula','bound channel: provider_spend_snapshots for this exact window (today also falls back to channel-operations today_spend); wallet total is not split by account or model; unbound channel: usage_logs.total_cost * current extra.cost_multiplier (default 0.1)', + 'cost_formula','request procurement estimate: persisted usage_logs.total_cost * captured procurement multiplier once; unknown gateway snapshots stay unknown; legacy estimate: total_cost * current extra.cost_multiplier (default 0.1); bound channel wallet accounting is unchanged and never split across requests', 'income_source','persisted usage_logs.actual_cost; subscription usage valuation, not cash receipts; no guarantee of debit in simple mode', 'standard_source','persisted usage_logs.total_cost; historical model/cache/per-request pricing is not recalculated', 'account_rate_multiplier_used',false,'error_rate',NULL)` diff --git a/backend/internal/repository/usage_log_repo_insert.go b/backend/internal/repository/usage_log_repo_insert.go index 3029981b3c3c..1ffc75ac92e8 100644 --- a/backend/internal/repository/usage_log_repo_insert.go +++ b/backend/internal/repository/usage_log_repo_insert.go @@ -92,6 +92,7 @@ var usageLogInsertArgTypes = [...]string{ "jsonb", // queue_timing "text", // platform "jsonb", // customer_cost_details + "jsonb", // procurement_cost_snapshot } const ( @@ -298,14 +299,15 @@ func (r *usageLogRepository) createSingle(ctx context.Context, sqlq sqlExecutor, created_at, queue_timing, platform, - customer_cost_details + customer_cost_details, + procurement_cost_snapshot ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, - $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67, $68 + $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67, $68, $69 ) ON CONFLICT (request_id, api_key_id) DO NOTHING RETURNING id, created_at @@ -764,7 +766,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage created_at, queue_timing, platform, - customer_cost_details + customer_cost_details, + procurement_cost_snapshot ) AS (VALUES `) // Each batch row prepends the synthetic input_index before the 61 @@ -865,7 +868,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage created_at, queue_timing, platform, - customer_cost_details + customer_cost_details, + procurement_cost_snapshot ) SELECT user_id, @@ -935,7 +939,8 @@ func buildUsageLogBatchInsertQuery(keys []string, preparedByKey map[string]usage created_at, queue_timing, platform, - customer_cost_details + customer_cost_details, + procurement_cost_snapshot FROM input ON CONFLICT (request_id, api_key_id) DO NOTHING RETURNING request_id, api_key_id, id, created_at @@ -1045,7 +1050,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) ( created_at, queue_timing, platform, - customer_cost_details + customer_cost_details, + procurement_cost_snapshot ) AS (VALUES `) args := make([]any, 0, len(preparedList)*60) @@ -1141,7 +1147,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) ( created_at, queue_timing, platform, - customer_cost_details + customer_cost_details, + procurement_cost_snapshot ) SELECT user_id, @@ -1211,7 +1218,8 @@ func buildUsageLogBestEffortInsertQuery(preparedList []usageLogInsertPrepared) ( created_at, queue_timing, platform, - customer_cost_details + customer_cost_details, + procurement_cost_snapshot FROM input ON CONFLICT (request_id, api_key_id) DO NOTHING `) @@ -1289,14 +1297,15 @@ func execUsageLogInsertNoResult(ctx context.Context, sqlq sqlExecutor, prepared created_at, queue_timing, platform, - customer_cost_details + customer_cost_details, + procurement_cost_snapshot ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, - $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67, $68 + $26, $27, $28, $29, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $40, $41, $42, $43, $44, $45, $46, $47, $48, $49, $50, $51, $52, $53, $54, $55, $56, $57, $58, $59, $60, $61, $62, $63, $64, $65, $66, $67, $68, $69 ) ON CONFLICT (request_id, api_key_id) DO NOTHING `, prepared.args...) @@ -1321,6 +1330,12 @@ func prepareUsageLogInsert(log *service.UsageLog) usageLogInsertPrepared { duration := nullInt(log.DurationMs) firstToken := nullInt(log.FirstTokenMs) queueWait := nullInt(log.QueueWaitMs) + var procurementCostSnapshot any + if log.ProcurementCostSnapshot != nil { + if raw, err := json.Marshal(log.ProcurementCostSnapshot); err == nil { + procurementCostSnapshot = string(raw) + } + } var customerCostDetails any if log.CustomerCostDetails != nil { if raw, err := json.Marshal(log.CustomerCostDetails); err == nil { @@ -1439,6 +1454,7 @@ func prepareUsageLogInsert(log *service.UsageLog) usageLogInsertPrepared { queueTiming, nullString(&log.Platform), customerCostDetails, + procurementCostSnapshot, }, } } diff --git a/backend/internal/repository/usage_log_repo_query.go b/backend/internal/repository/usage_log_repo_query.go index ad7d1b83640f..fbae0551cdf5 100644 --- a/backend/internal/repository/usage_log_repo_query.go +++ b/backend/internal/repository/usage_log_repo_query.go @@ -19,7 +19,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/service" ) -const usageLogSelectColumns = "id, user_id, api_key_id, account_id, request_id, model, requested_model, upstream_model, upstream_response_model, upstream_model_mismatch, group_id, subscription_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, cache_creation_5m_tokens, cache_creation_1h_tokens, image_output_tokens, image_output_cost, image_input_tokens, image_input_cost, input_cost, output_cost, cache_creation_cost, cache_read_cost, total_cost, actual_cost, rate_multiplier, account_rate_multiplier, billing_type, request_type, stream, openai_ws_mode, duration_ms, first_token_ms, queue_wait_ms, user_agent, ip_address, image_count, image_size, image_input_size, image_output_size, image_size_source, image_size_breakdown, video_count, video_resolution, video_duration_seconds, service_tier, reasoning_effort, requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, long_context_billing_applied, channel_id, model_mapping_chain, billing_tier, billing_mode, account_stats_cost, upstream_request_id, session_id, native_compaction_v2, cache_creation_30m_tokens, cache_creation_12h_tokens, created_at, queue_timing, platform, customer_cost_details" +const usageLogSelectColumns = "id, user_id, api_key_id, account_id, request_id, model, requested_model, upstream_model, upstream_response_model, upstream_model_mismatch, group_id, subscription_id, input_tokens, output_tokens, cache_creation_tokens, cache_read_tokens, cache_creation_5m_tokens, cache_creation_1h_tokens, image_output_tokens, image_output_cost, image_input_tokens, image_input_cost, input_cost, output_cost, cache_creation_cost, cache_read_cost, total_cost, actual_cost, rate_multiplier, account_rate_multiplier, billing_type, request_type, stream, openai_ws_mode, duration_ms, first_token_ms, queue_wait_ms, user_agent, ip_address, image_count, image_size, image_input_size, image_output_size, image_size_source, image_size_breakdown, video_count, video_resolution, video_duration_seconds, service_tier, reasoning_effort, requested_reasoning_effort, inbound_endpoint, upstream_endpoint, cache_ttl_overridden, long_context_billing_applied, channel_id, model_mapping_chain, billing_tier, billing_mode, account_stats_cost, upstream_request_id, session_id, native_compaction_v2, cache_creation_30m_tokens, cache_creation_12h_tokens, created_at, queue_timing, platform, customer_cost_details, procurement_cost_snapshot" func (r *usageLogRepository) GetByID(ctx context.Context, id int64) (log *service.UsageLog, err error) { query := "SELECT " + usageLogSelectColumns + " FROM usage_logs WHERE id = $1" @@ -507,6 +507,7 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e cacheCreation30m int cacheCreation12h int createdAt time.Time + procurementCostSnapshot sql.NullString customerCostDetails sql.NullString queueTiming sql.NullString platform sql.NullString @@ -582,6 +583,7 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e &queueTiming, &platform, &customerCostDetails, + &procurementCostSnapshot, ); err != nil { return nil, err } @@ -623,6 +625,13 @@ func scanUsageLog(scanner interface{ Scan(...any) error }) (*service.UsageLog, e LongContextBillingApplied: longContextBillingApplied, CreatedAt: createdAt, } + if procurementCostSnapshot.Valid { + var snapshot service.ProcurementCostSnapshot + if err := json.Unmarshal([]byte(procurementCostSnapshot.String), &snapshot); err != nil { + return nil, err + } + log.ProcurementCostSnapshot = &snapshot + } if customerCostDetails.Valid { var detail service.CustomerCostDetails if json.Unmarshal([]byte(customerCostDetails.String), &detail) == nil { diff --git a/backend/internal/repository/usage_log_repo_request_type_test.go b/backend/internal/repository/usage_log_repo_request_type_test.go index 8024f90190b3..369d13f97e03 100644 --- a/backend/internal/repository/usage_log_repo_request_type_test.go +++ b/backend/internal/repository/usage_log_repo_request_type_test.go @@ -108,7 +108,8 @@ func TestUsageLogRepositoryCreateSyncRequestTypeAndLegacyFields(t *testing.T) { createdAt, sqlmock.AnyArg(), // queue_timing sql.NullString{}, // platform - nil, // customer_cost_details + nil, // customer_cost_details + nil, // procurement_cost_snapshot ). WillReturnRows(sqlmock.NewRows([]string{"id", "created_at"}).AddRow(int64(99), createdAt)) @@ -209,7 +210,8 @@ func TestUsageLogRepositoryCreate_PersistsServiceTier(t *testing.T) { createdAt, sqlmock.AnyArg(), // queue_timing sql.NullString{}, // platform - nil, // customer_cost_details + nil, // customer_cost_details + nil, // procurement_cost_snapshot ). WillReturnRows(sqlmock.NewRows([]string{"id", "created_at"}).AddRow(int64(100), createdAt)) @@ -290,8 +292,8 @@ func TestPrepareUsageLogInsert_PersistsNativeCompactionV2WithoutChangingRequestT prepared := prepareUsageLogInsert(log) require.Len(t, prepared.args, len(usageLogInsertArgTypes)) - require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-7]) - require.Equal(t, true, prepared.args[len(prepared.args)-7]) + require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-8]) + require.Equal(t, true, prepared.args[len(prepared.args)-8]) require.Equal(t, int16(service.RequestTypeStream), prepared.args[30]) require.Equal(t, service.RequestTypeStream, log.RequestType) require.True(t, log.Stream) @@ -979,6 +981,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { sql.NullString{}, // queue_timing sql.NullString{}, // platform sql.NullString{}, // customer_cost_details + sql.NullString{}, // procurement_cost_snapshot }}) require.NoError(t, err) require.Equal(t, 2, log.ImageCount) @@ -1065,6 +1068,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { sql.NullString{}, // queue_timing sql.NullString{}, // platform sql.NullString{}, // customer_cost_details + sql.NullString{}, // procurement_cost_snapshot }}) require.NoError(t, err) require.NotNil(t, log.ServiceTier) @@ -1134,6 +1138,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { sql.NullString{}, // queue_timing sql.NullString{}, // platform sql.NullString{}, // customer_cost_details + sql.NullString{}, // procurement_cost_snapshot }}) require.NoError(t, err) require.NotNil(t, log.ServiceTier) @@ -1204,6 +1209,7 @@ func TestScanUsageLogRequestTypeAndLegacyFallback(t *testing.T) { sql.NullString{}, // queue_timing sql.NullString{}, // platform sql.NullString{}, // customer_cost_details + sql.NullString{}, // procurement_cost_snapshot }}) require.NoError(t, err) require.NotNil(t, log.ServiceTier) diff --git a/backend/internal/repository/usage_log_session_id_unit_test.go b/backend/internal/repository/usage_log_session_id_unit_test.go index 8c8649598493..6263ebd63c7a 100644 --- a/backend/internal/repository/usage_log_session_id_unit_test.go +++ b/backend/internal/repository/usage_log_session_id_unit_test.go @@ -30,7 +30,7 @@ func newSessionIDUsageLog(sessionID *string) *service.UsageLog { // TestPrepareUsageLogInsert_SessionIDArgWiring pins the session_id column to the // arg slice / arg-type table so the five INSERT column lists stay in sync. session_id -// is immediately before native_compaction_v2; created_at, queue_timing, platform and customer_cost_details follow. +// is immediately before native_compaction_v2; created_at, queue_timing, platform, customer_cost_details and procurement_cost_snapshot follow. func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) { sessionID := "sess-persisted-123" prepared := prepareUsageLogInsert(newSessionIDUsageLog(&sessionID)) @@ -38,16 +38,16 @@ func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) { require.Len(t, prepared.args, len(usageLogInsertArgTypes), "prepared args must match the arg-type table length") - // session_id precedes native_compaction_v2, both TTL counters, created_at, queue_timing, platform and customer_cost_details. - sessionArg := prepared.args[len(prepared.args)-8] + // session_id precedes native_compaction_v2, both TTL counters, created_at, queue_timing, platform, customer_cost_details and procurement_cost_snapshot. + sessionArg := prepared.args[len(prepared.args)-9] ns, ok := sessionArg.(sql.NullString) require.True(t, ok, "session_id arg should be a sql.NullString, got %T", sessionArg) require.True(t, ns.Valid) require.Equal(t, sessionID, ns.String) - require.Equal(t, "text", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-8], + require.Equal(t, "text", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-9], "session_id arg type must be text") - require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-7], + require.Equal(t, "boolean", usageLogInsertArgTypes[len(usageLogInsertArgTypes)-8], "native_compaction_v2 arg type must be boolean") } @@ -55,14 +55,14 @@ func TestPrepareUsageLogInsert_SessionIDArgWiring(t *testing.T) { // persisted as SQL NULL rather than an empty string. func TestPrepareUsageLogInsert_SessionIDNullWhenAbsent(t *testing.T) { prepared := prepareUsageLogInsert(newSessionIDUsageLog(nil)) - sessionArg := prepared.args[len(prepared.args)-8] + sessionArg := prepared.args[len(prepared.args)-9] ns, ok := sessionArg.(sql.NullString) require.True(t, ok, "session_id arg should be a sql.NullString, got %T", sessionArg) require.False(t, ns.Valid, "absent session id must be NULL, not empty string") empty := "" preparedEmpty := prepareUsageLogInsert(newSessionIDUsageLog(&empty)) - nsEmpty := preparedEmpty.args[len(preparedEmpty.args)-8].(sql.NullString) + nsEmpty := preparedEmpty.args[len(preparedEmpty.args)-9].(sql.NullString) require.False(t, nsEmpty.Valid, "empty session id must also be NULL") } diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 46390dac24cc..af208e63e9b4 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -964,6 +964,7 @@ func (s *GatewayService) recordUsageCore(ctx context.Context, input *recordUsage addCacheStorageToAccountStatsCost(usageLog, cacheStorageCost) } + captureGatewayProcurementCost(usageLog, account) simpleModeKeyRateLimitOnly := simpleModeKeyRateLimitBillingEnabled(s.cfg, apiKey) if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple && !simpleModeKeyRateLimitOnly { writeUsageLogBestEffort(ctx, s.usageLogRepo, usageLog, "service.gateway") diff --git a/backend/internal/service/openai_gateway_usage.go b/backend/internal/service/openai_gateway_usage.go index 9c4bc74d0632..e8b51f5d0580 100644 --- a/backend/internal/service/openai_gateway_usage.go +++ b/backend/internal/service/openai_gateway_usage.go @@ -534,6 +534,7 @@ func (s *OpenAIGatewayService) RecordUsage(ctx context.Context, input *OpenAIRec ) } + captureGatewayProcurementCost(usageLog, account) simpleModeKeyRateLimitOnly := simpleModeKeyRateLimitBillingEnabled(s.cfg, apiKey) if s.cfg != nil && s.cfg.RunMode == config.RunModeSimple && !simpleModeKeyRateLimitOnly { writeUsageLogBestEffort(ctx, s.usageLogRepo, usageLog, "service.openai_gateway") diff --git a/backend/internal/service/procurement_cost_snapshot.go b/backend/internal/service/procurement_cost_snapshot.go new file mode 100644 index 000000000000..11c25b7c74ea --- /dev/null +++ b/backend/internal/service/procurement_cost_snapshot.go @@ -0,0 +1,28 @@ +package service + +// ProcurementCostSnapshot is request-time evidence, independent of the user +// charge and account debit multiplier. A nil CostMultiplier means unknown, not +// zero. A nil snapshot denotes history/legacy accounts, not a current estimate. +type ProcurementCostSnapshot struct { + Version int `json:"version"` + AccountType string `json:"account_type"` + Provider string `json:"provider"` + TargetPlatform string `json:"target_platform"` + Basis string `json:"basis"` + CostMultiplier *float64 `json:"cost_multiplier,omitempty"` +} + +func captureGatewayProcurementCost(log *UsageLog, account *Account) { + if log == nil || !account.IsGateway() { + return + } + provider := account.GetCredential(GatewayUpstreamKindCredentialKey) + snapshot := &ProcurementCostSnapshot{Version: 1, AccountType: AccountTypeGateway, + Provider: provider, TargetPlatform: log.Platform, Basis: "total_cost"} + if provider == "new_api" { + if factor, ok := NewAPIGatewayCostForRequest(account, log.Platform); ok { + snapshot.CostMultiplier = &factor + } + } + log.ProcurementCostSnapshot = snapshot +} diff --git a/backend/internal/service/procurement_cost_snapshot_test.go b/backend/internal/service/procurement_cost_snapshot_test.go new file mode 100644 index 000000000000..d4f9ee071229 --- /dev/null +++ b/backend/internal/service/procurement_cost_snapshot_test.go @@ -0,0 +1,95 @@ +//go:build unit + +package service + +import ( + "context" + "encoding/json" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestProcurementSnapshotMixedTargetsThroughUsageWriters(t *testing.T) { + for _, writer := range []string{"gateway", "openai"} { + t.Run(writer, func(t *testing.T) { + a := &Account{ID: 3, Platform: PlatformGateway, Type: AccountTypeGateway, + Credentials: map[string]any{GatewayUpstreamKindCredentialKey: "new_api"}, Extra: map[string]any{UpstreamBillingProviderExtraKey: "new_api", AccountCostMultiplierExtraKey: 99.0}} + a.Extra[UpstreamBillingProbeExtraKey] = newAPISnapshot(a, NewAPIToken{Group: "fixed"}, &newAPIData{wallet: 12, ratios: map[string]float64{"fixed": .1}}, 30, time.Now()) + var recorded []*UsageLog + for _, target := range []string{PlatformOpenAI, PlatformKimi} { + logs := &openAIRecordUsageLogRepoStub{inserted: true} + users, subs := &openAIRecordUsageUserRepoStub{}, &openAIRecordUsageSubRepoStub{} + key := &APIKey{ID: 1, Group: &Group{Platform: PlatformComposite, RateMultiplier: .3}} + billing := &openAIRecordUsageBillingRepoStub{result: &UsageBillingApplyResult{Applied: false}} + if writer == "openai" { + svc := newOpenAIRecordUsageServiceForTest(logs, users, subs, nil) + svc.usageBillingRepo = billing + require.NoError(t, svc.RecordUsage(context.Background(), &OpenAIRecordUsageInput{ + Result: &OpenAIForwardResult{RequestID: "procurement-" + target, Model: "gpt-5.1", Usage: OpenAIUsage{InputTokens: 100}}, + APIKey: key, User: &User{ID: 2}, Account: a, QuotaPlatform: target})) + } else { + svc := newGatewayRecordUsageServiceWithBillingRepoForTest(logs, billing, users, subs) + require.NoError(t, svc.RecordUsage(context.Background(), &RecordUsageInput{ + Result: &ForwardResult{RequestID: "procurement-" + target, Model: "claude-sonnet-4", Usage: ClaudeUsage{InputTokens: 100}}, + APIKey: key, User: &User{ID: 2}, Account: a, QuotaPlatform: target})) + } + require.NotNil(t, logs.lastLog) + require.NotNil(t, logs.lastLog.ProcurementCostSnapshot) + require.NotNil(t, logs.lastLog.ProcurementCostSnapshot.CostMultiplier) + want := .7 + if target == PlatformKimi { + want = .1 + } + require.Equal(t, want, *logs.lastLog.ProcurementCostSnapshot.CostMultiplier) + require.Equal(t, target, logs.lastLog.ProcurementCostSnapshot.TargetPlatform) + recorded = append(recorded, logs.lastLog) + } + // Already-built asynchronous usage/events cannot be repriced by edits. + a.Extra[NewAPIApplyUSDRateExtraKey] = false + a.Extra[AccountCostMultiplierExtraKey] = 1.0 + a.Extra[UpstreamBillingProbeExtraKey] = nil + for i, want := range []float64{.7, .1} { + raw, err := json.Marshal(&UsageBillingEvent{Version: 1, Usage: *recorded[i]}) + require.NoError(t, err) + var event UsageBillingEvent + require.NoError(t, json.Unmarshal(raw, &event)) + require.Equal(t, want, *event.Usage.ProcurementCostSnapshot.CostMultiplier) + require.Equal(t, recorded[i].TotalCost, event.Usage.TotalCost) + require.Equal(t, recorded[i].ActualCost, event.Usage.ActualCost) + } + }) + } +} + +func TestProcurementSnapshotUnknownAndLegacySemantics(t *testing.T) { + a := &Account{Platform: PlatformGateway, Type: AccountTypeGateway, Credentials: map[string]any{GatewayUpstreamKindCredentialKey: "new_api"}} + log := &UsageLog{Platform: PlatformOpenAI, TotalCost: 10, ActualCost: 3} + captureGatewayProcurementCost(log, a) + require.NotNil(t, log.ProcurementCostSnapshot, "record unknown request-time evidence, never use the gateway's current account cost") + require.Nil(t, log.ProcurementCostSnapshot.CostMultiplier) + for _, kind := range []string{AccountTypeAPIKey, AccountTypeUpstream, AccountTypeOAuth} { + legacy := &UsageLog{Platform: PlatformOpenAI} + captureGatewayProcurementCost(legacy, &Account{Type: kind}) + require.Nil(t, legacy.ProcurementCostSnapshot, "legacy single-platform reporting must retain its existing fallback") + } + require.Equal(t, 10.0, log.TotalCost) + require.Equal(t, 3.0, log.ActualCost) +} + +func TestProcurementSnapshotZeroDisabledConversionAndUnresolvedTarget(t *testing.T) { + a := &Account{Platform: PlatformGateway, Type: AccountTypeGateway, + Credentials: map[string]any{GatewayUpstreamKindCredentialKey: "new_api"}, + Extra: map[string]any{UpstreamBillingProviderExtraKey: "new_api", NewAPIApplyUSDRateExtraKey: false}} + for _, rate := range []float64{0, .1} { + a.Extra[UpstreamBillingProbeExtraKey] = newAPISnapshot(a, NewAPIToken{Group: "fixed"}, &newAPIData{wallet: 12, ratios: map[string]float64{"fixed": rate}}, 30, time.Now()) + log := &UsageLog{Platform: PlatformOpenAI} + captureGatewayProcurementCost(log, a) + require.NotNil(t, log.ProcurementCostSnapshot.CostMultiplier) + require.Equal(t, rate, *log.ProcurementCostSnapshot.CostMultiplier) + log.Platform = PlatformComposite + captureGatewayProcurementCost(log, a) + require.Nil(t, log.ProcurementCostSnapshot.CostMultiplier, "composite cannot decide the currency scale") + } +} diff --git a/backend/internal/service/usage_log.go b/backend/internal/service/usage_log.go index c492bd6b915b..2e552399e1fc 100644 --- a/backend/internal/service/usage_log.go +++ b/backend/internal/service/usage_log.go @@ -103,7 +103,8 @@ func ApplyLegacyRequestFields(requestType RequestType, fallbackStream bool, fall } type UsageLog struct { - CustomerCostDetails *CustomerCostDetails + ProcurementCostSnapshot *ProcurementCostSnapshot + CustomerCostDetails *CustomerCostDetails // Platform snapshots the concrete upstream provider at request time. Gateway // accounts use the resolved request target. Empty is unknown legacy data. Platform string diff --git a/backend/migrations/391_usage_procurement_cost_snapshot.sql b/backend/migrations/391_usage_procurement_cost_snapshot.sql new file mode 100644 index 000000000000..0c7407cf9cac --- /dev/null +++ b/backend/migrations/391_usage_procurement_cost_snapshot.sql @@ -0,0 +1,18 @@ +-- SQL-owned usage metadata, like account_stats_cost. Historical rows remain NULL; +-- never backfill a request's procurement estimate from mutable account settings. +ALTER TABLE usage_logs ADD COLUMN IF NOT EXISTS procurement_cost_snapshot JSONB; + +CREATE OR REPLACE FUNCTION reject_usage_procurement_cost_rewrite() RETURNS trigger +LANGUAGE plpgsql AS $$ +BEGIN + IF OLD.procurement_cost_snapshot IS DISTINCT FROM NEW.procurement_cost_snapshot THEN + RAISE EXCEPTION 'usage procurement cost snapshot is immutable'; + END IF; + RETURN NEW; +END; +$$; + +DROP TRIGGER IF EXISTS usage_procurement_cost_immutable ON usage_logs; +CREATE TRIGGER usage_procurement_cost_immutable +BEFORE UPDATE OF procurement_cost_snapshot ON usage_logs +FOR EACH ROW EXECUTE FUNCTION reject_usage_procurement_cost_rewrite(); From fb1ad20df958d1697a5aa36feb4bf0d1dac1c594 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 02:35:47 +0800 Subject: [PATCH 05/26] fix: reserve migration 392 and document observer cost scope Rename only the unpublished procurement snapshot migration to 392, retaining the published sibling 391 reservation. Align its fixture and CI path, correct the DTO visibility comment without changing permissions, and exercise the existing observer/user usage handler projection and ownership boundaries. Validation remains remote CI only. --- .../workflows/issue959-gateway-regression.yml | 8 ++-- backend/internal/handler/dto/types.go | 2 +- .../internal/handler/usage_observer_test.go | 40 +++++++++++++++++++ ...curement_cost_snapshot_integration_test.go | 2 +- ...> 392_usage_procurement_cost_snapshot.sql} | 0 5 files changed, 47 insertions(+), 5 deletions(-) rename backend/migrations/{391_usage_procurement_cost_snapshot.sql => 392_usage_procurement_cost_snapshot.sql} (100%) diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index ea0c3edc882a..01fbba57cd29 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -17,7 +17,8 @@ on: - 'backend/internal/repository/profit_operations.go' - 'backend/internal/repository/usage_log_repo*' - 'backend/internal/handler/dto/procurement_cost_snapshot*' - - 'backend/migrations/391_usage_procurement_cost_snapshot.sql' + - 'backend/internal/handler/usage_observer_test.go' + - 'backend/migrations/392_usage_procurement_cost_snapshot.sql' - 'backend/internal/repository/concurrency_cache*' - 'backend/internal/repository/integration_harness_test.go' - 'backend/go.mod' @@ -77,8 +78,8 @@ jobs: shell: bash run: | set -euo pipefail - go test -race -tags=unit ./internal/service ./internal/handler/admin ./internal/handler/dto ./internal/repository \ - -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots|ProcurementSnapshot)' \ + go test -race -tags=unit ./internal/service ./internal/handler ./internal/handler/admin ./internal/handler/dto ./internal/repository \ + -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots|ProcurementSnapshot|ObserverProcurementSnapshot)' \ -count=1 -v -timeout=10m 2>&1 | tee ../evidence/unit-race.log if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/unit-race.log; then exit 1 @@ -94,6 +95,7 @@ jobs: grep -F -- '--- PASS: TestAccountGatewayDTORedactsCallingKey' ../evidence/unit-race.log grep -F -- '--- PASS: TestProcurementSnapshotMixedTargetsThroughUsageWriters' ../evidence/unit-race.log grep -F -- '--- PASS: TestProcurementSnapshotAdminDTOAndUserPrivacy' ../evidence/unit-race.log + grep -F -- '--- PASS: TestObserverProcurementSnapshotFollowsExistingAccountCostScope' ../evidence/unit-race.log - name: Shared account slots against isolated Redis working-directory: backend shell: bash diff --git a/backend/internal/handler/dto/types.go b/backend/internal/handler/dto/types.go index c26e768d90e8..b827f0b3b362 100644 --- a/backend/internal/handler/dto/types.go +++ b/backend/internal/handler/dto/types.go @@ -746,7 +746,7 @@ type AdminUsageLog struct { AccountRateMultiplier *float64 `json:"account_rate_multiplier"` // AccountStatsCost 自定义定价规则计算的账号统计费用(nil 表示使用默认公式) AccountStatsCost *float64 `json:"account_stats_cost,omitempty"` - // ProcurementCostSnapshot is supplier-cost evidence visible only to admins. + // ProcurementCostSnapshot follows existing admin/authorized observer cost scope. ProcurementCostSnapshot *service.ProcurementCostSnapshot `json:"procurement_cost_snapshot,omitempty"` // IPAddress 用户请求 IP diff --git a/backend/internal/handler/usage_observer_test.go b/backend/internal/handler/usage_observer_test.go index 82c90ba49008..6eeafd2cc948 100644 --- a/backend/internal/handler/usage_observer_test.go +++ b/backend/internal/handler/usage_observer_test.go @@ -55,6 +55,7 @@ func observerUsageRouter(r *observerUsageRepo, role string) *gin.Engine { router.GET("/usage/dashboard/snapshot-v2", h.DashboardSnapshotV2) router.GET("/usage/filter-options", h.ObserverFilterOptions) router.GET("/usage/:id/timing", h.ObserverTiming) + router.GET("/usage/:id", h.GetByID) return router } func usageGET(router *gin.Engine, path string) *httptest.ResponseRecorder { @@ -104,6 +105,45 @@ func TestObserverUsageScopeAndProjection(t *testing.T) { } } +func TestObserverProcurementSnapshotFollowsExistingAccountCostScope(t *testing.T) { + factor, accountRate, accountCost := .7, 2.0, 9.0 + for _, role := range []string{service.RoleObserver, service.RoleUser} { + t.Run(role, func(t *testing.T) { + row := service.UsageLog{ID: 1, UserID: 42, AccountRateMultiplier: &accountRate, + ProcurementCostSnapshot: &service.ProcurementCostSnapshot{Version: 1, AccountType: "gateway", Provider: "new_api", TargetPlatform: "openai", Basis: "total_cost", CostMultiplier: &factor}, + Account: &service.Account{ID: 7, Credentials: map[string]any{"api_key": "synthetic-must-not-leak"}}} + r := &observerUsageRepo{record: &row, userUsageRepoCapture: userUsageRepoCapture{ + listRows: []service.UsageLog{row}, stats: &usagestats.UsageStats{TotalAccountCost: &accountCost}}} + router := observerUsageRouter(r, role) + for _, path := range []string{"/usage?user_id=999", "/usage/1"} { + w := usageGET(router, path) + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + require.NotContains(t, w.Body.String(), "synthetic-must-not-leak") + if role == service.RoleObserver { + require.Contains(t, w.Body.String(), `"account_rate_multiplier":2`) + require.Contains(t, w.Body.String(), `"procurement_cost_snapshot"`) + require.Contains(t, w.Body.String(), `"cost_multiplier":0.7`) + } else { + require.NotContains(t, w.Body.String(), "account_rate_multiplier") + require.NotContains(t, w.Body.String(), "procurement_cost_snapshot") + } + } + require.Equal(t, int64(42), r.listFilters.UserID, "query user_id cannot expand existing ownership scope") + w := usageGET(router, "/usage/stats?user_id=999") + require.Equal(t, http.StatusOK, w.Code, w.Body.String()) + if role == service.RoleObserver { + require.Contains(t, w.Body.String(), `"total_account_cost":9`) + } else { + require.NotContains(t, w.Body.String(), `"total_account_cost":9`) + } + r.record.UserID = 999 + w = usageGET(router, "/usage/1") + require.Equal(t, http.StatusForbidden, w.Code) + require.NotContains(t, w.Body.String(), "procurement_cost_snapshot", "a foreign record remains forbidden") + }) + } +} + func TestObserverOwnUsageFiltersAndTiming(t *testing.T) { r := &observerUsageRepo{record: &service.UsageLog{ID: 1, UserID: 999}} router := observerUsageRouter(r, service.RoleObserver) diff --git a/backend/internal/repository/procurement_cost_snapshot_integration_test.go b/backend/internal/repository/procurement_cost_snapshot_integration_test.go index 40ed5a8b06e5..fe7db81d7ac6 100644 --- a/backend/internal/repository/procurement_cost_snapshot_integration_test.go +++ b/backend/internal/repository/procurement_cost_snapshot_integration_test.go @@ -137,7 +137,7 @@ func TestProcurementSnapshotMigrationLeavesHistoryAndChargesUntouched(t *testing defer func() { _ = tx.Rollback() }() _, err = tx.Exec(`CREATE TEMP TABLE usage_logs(id bigint,total_cost numeric,actual_cost numeric) ON COMMIT DROP; INSERT INTO usage_logs VALUES(1,10,3)`) require.NoError(t, err) - sql, err := migrations.FS.ReadFile("391_usage_procurement_cost_snapshot.sql") + sql, err := migrations.FS.ReadFile("392_usage_procurement_cost_snapshot.sql") require.NoError(t, err) for i := 0; i < 2; i++ { _, err = tx.Exec(string(sql)) diff --git a/backend/migrations/391_usage_procurement_cost_snapshot.sql b/backend/migrations/392_usage_procurement_cost_snapshot.sql similarity index 100% rename from backend/migrations/391_usage_procurement_cost_snapshot.sql rename to backend/migrations/392_usage_procurement_cost_snapshot.sql From a8d88cda0e34d23c7a18a515b80933e24cc063b5 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 03:04:20 +0800 Subject: [PATCH 06/26] test: keep observer cost projection fixture portable across WS baselines --- backend/internal/handler/usage_observer_test.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/backend/internal/handler/usage_observer_test.go b/backend/internal/handler/usage_observer_test.go index 6eeafd2cc948..abe9602590dd 100644 --- a/backend/internal/handler/usage_observer_test.go +++ b/backend/internal/handler/usage_observer_test.go @@ -106,12 +106,16 @@ func TestObserverUsageScopeAndProjection(t *testing.T) { } func TestObserverProcurementSnapshotFollowsExistingAccountCostScope(t *testing.T) { - factor, accountRate, accountCost := .7, 2.0, 9.0 + accountRate, accountCost := 2.0, 9.0 for _, role := range []string{service.RoleObserver, service.RoleUser} { t.Run(role, func(t *testing.T) { row := service.UsageLog{ID: 1, UserID: 42, AccountRateMultiplier: &accountRate, - ProcurementCostSnapshot: &service.ProcurementCostSnapshot{Version: 1, AccountType: "gateway", Provider: "new_api", TargetPlatform: "openai", Basis: "total_cost", CostMultiplier: &factor}, Account: &service.Account{ID: 7, Credentials: map[string]any{"api_key": "synthetic-must-not-leak"}}} + // Historical WS regressions compile this test package against older UsageLog types. + // The observer response below must expose the decoded snapshot on the candidate. + require.NoError(t, json.Unmarshal([]byte(`{"ProcurementCostSnapshot":{ + "version":1,"account_type":"gateway","provider":"new_api","target_platform":"openai", + "basis":"total_cost","cost_multiplier":0.7}}`), &row)) r := &observerUsageRepo{record: &row, userUsageRepoCapture: userUsageRepoCapture{ listRows: []service.UsageLog{row}, stats: &usagestats.UsageStats{TotalAccountCost: &accountCost}}} router := observerUsageRouter(r, role) From b839f42a7ec85f41789339e7cdef501bf3ccc656 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 03:52:19 +0800 Subject: [PATCH 07/26] ci: retain additive procurement DTO fields in historical cost regressions --- .github/scripts/prepare-image-usage-free-fast-red.py | 7 ++++++- .github/workflows/free-fast-customer-cost-details.yml | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/scripts/prepare-image-usage-free-fast-red.py b/.github/scripts/prepare-image-usage-free-fast-red.py index f526fb9ce3fb..bf9be7f71316 100644 --- a/.github/scripts/prepare-image-usage-free-fast-red.py +++ b/.github/scripts/prepare-image-usage-free-fast-red.py @@ -14,7 +14,12 @@ marker = 'type UsageLog struct {' # Omit nil just as the pre-snapshot DTO did; persistence RED must reach # its original missing-snapshot assertion, not a later JSON null mismatch. - addition = '\n\tCustomerCostDetails *CustomerCostDetails `json:"CustomerCostDetails,omitempty"`\n' + addition = ('\n\tCustomerCostDetails *CustomerCostDetails `json:"CustomerCostDetails,omitempty"`\n' + '\tProcurementCostSnapshot *ProcurementCostSnapshot `json:"ProcurementCostSnapshot,omitempty"`\n') +elif phase == 'admin-usage': + name = 'backend/internal/handler/dto/types.go' + marker = 'type AdminUsageLog struct {' + addition = '\n\tProcurementCostSnapshot *service.ProcurementCostSnapshot `json:"procurement_cost_snapshot,omitempty"`\n' elif phase == 'cache': name = 'backend/internal/service/customer_cost_details.go' marker = 'type CustomerCostDetails struct {' diff --git a/.github/workflows/free-fast-customer-cost-details.yml b/.github/workflows/free-fast-customer-cost-details.yml index f6d94e0edfcb..f23c18e9e7f3 100644 --- a/.github/workflows/free-fast-customer-cost-details.yml +++ b/.github/workflows/free-fast-customer-cost-details.yml @@ -95,6 +95,7 @@ jobs: # The new image receipt reader needs the additive DTO field; retain # the old Free Fast producer so the selected assertions still fail. python3 .github/scripts/prepare-image-usage-free-fast-red.py usage "$baseline" + python3 .github/scripts/prepare-image-usage-free-fast-red.py admin-usage "$baseline" # Tests stay byte-for-byte at candidate HEAD. Keep the new additive # DB column so a missing migration can never qualify as business RED. set +e From 3e1794e945b5aedf513bc72d4d7fbde0bcca1274 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 05:13:50 +0800 Subject: [PATCH 08/26] test: format procurement snapshot fixture columns --- .../repository/usage_log_repo_request_type_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/backend/internal/repository/usage_log_repo_request_type_test.go b/backend/internal/repository/usage_log_repo_request_type_test.go index 369d13f97e03..35e4298d2161 100644 --- a/backend/internal/repository/usage_log_repo_request_type_test.go +++ b/backend/internal/repository/usage_log_repo_request_type_test.go @@ -108,8 +108,8 @@ func TestUsageLogRepositoryCreateSyncRequestTypeAndLegacyFields(t *testing.T) { createdAt, sqlmock.AnyArg(), // queue_timing sql.NullString{}, // platform - nil, // customer_cost_details - nil, // procurement_cost_snapshot + nil, // customer_cost_details + nil, // procurement_cost_snapshot ). WillReturnRows(sqlmock.NewRows([]string{"id", "created_at"}).AddRow(int64(99), createdAt)) @@ -210,8 +210,8 @@ func TestUsageLogRepositoryCreate_PersistsServiceTier(t *testing.T) { createdAt, sqlmock.AnyArg(), // queue_timing sql.NullString{}, // platform - nil, // customer_cost_details - nil, // procurement_cost_snapshot + nil, // customer_cost_details + nil, // procurement_cost_snapshot ). WillReturnRows(sqlmock.NewRows([]string{"id", "created_at"}).AddRow(int64(100), createdAt)) From e45540ae763fa6e54b2e089916d524587a8baac9 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 06:47:26 +0800 Subject: [PATCH 09/26] test: align procurement snapshot assertions with gofmt --- backend/internal/service/procurement_cost_snapshot_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/backend/internal/service/procurement_cost_snapshot_test.go b/backend/internal/service/procurement_cost_snapshot_test.go index d4f9ee071229..1beaf5f4d8f5 100644 --- a/backend/internal/service/procurement_cost_snapshot_test.go +++ b/backend/internal/service/procurement_cost_snapshot_test.go @@ -81,7 +81,7 @@ func TestProcurementSnapshotUnknownAndLegacySemantics(t *testing.T) { func TestProcurementSnapshotZeroDisabledConversionAndUnresolvedTarget(t *testing.T) { a := &Account{Platform: PlatformGateway, Type: AccountTypeGateway, Credentials: map[string]any{GatewayUpstreamKindCredentialKey: "new_api"}, - Extra: map[string]any{UpstreamBillingProviderExtraKey: "new_api", NewAPIApplyUSDRateExtraKey: false}} + Extra: map[string]any{UpstreamBillingProviderExtraKey: "new_api", NewAPIApplyUSDRateExtraKey: false}} for _, rate := range []float64{0, .1} { a.Extra[UpstreamBillingProbeExtraKey] = newAPISnapshot(a, NewAPIToken{Group: "fixed"}, &newAPIData{wallet: 12, ratios: map[string]float64{"fixed": rate}}, 30, time.Now()) log := &UsageLog{Platform: PlatformOpenAI} From 3752a6afee7223c45e34101b871a3946e6293a97 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 11:13:37 +0800 Subject: [PATCH 10/26] feat: admit gateway requests into native protocol forwarders Refs #959. Reload gateway account and explicit group policy at terminal admission, validate concrete/Composite targets, model scope and shared identity, and use isolated API-key transport views for native Anthropic, OpenAI and Gemini forwarding including Antigravity ingress. Keep global gateway selection and unsupported protocol paths closed until coherent scheduler integration. Add source regressions for builders, identity, stale membership and repository refresh; remote CI only. --- .../workflows/issue959-gateway-regression.yml | 8 +- .../repository/gateway_request_admission.go | 49 ++++ ...eway_request_admission_integration_test.go | 30 +++ .../service/antigravity_gateway_claude.go | 2 +- .../service/antigravity_gateway_gemini.go | 2 +- .../service/antigravity_gateway_upstream.go | 2 +- backend/internal/service/gateway_forward.go | 12 +- .../service/gateway_protocol_admission.go | 211 ++++++++++++++++++ .../gateway_protocol_admission_test.go | 163 ++++++++++++++ .../service/gateway_protocol_forward_test.go | 143 ++++++++++++ .../service/gemini_messages_compat_service.go | 12 +- .../openai_gateway_chat_completions.go | 6 +- .../service/openai_gateway_forward.go | 6 +- .../service/openai_gateway_messages.go | 6 +- 14 files changed, 641 insertions(+), 11 deletions(-) create mode 100644 backend/internal/repository/gateway_request_admission.go create mode 100644 backend/internal/repository/gateway_request_admission_integration_test.go create mode 100644 backend/internal/service/gateway_protocol_admission.go create mode 100644 backend/internal/service/gateway_protocol_admission_test.go create mode 100644 backend/internal/service/gateway_protocol_forward_test.go diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index 01fbba57cd29..6a5629b8af3b 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -12,6 +12,7 @@ on: - 'backend/internal/repository/account_repo.go' - 'backend/internal/repository/group_repo.go' - 'backend/internal/repository/gateway_account*' + - 'backend/internal/repository/gateway_request_admission*' - 'backend/internal/repository/oauth_degradation_group_bindings*' - 'backend/internal/repository/procurement_cost_snapshot*' - 'backend/internal/repository/profit_operations.go' @@ -79,7 +80,7 @@ jobs: run: | set -euo pipefail go test -race -tags=unit ./internal/service ./internal/handler ./internal/handler/admin ./internal/handler/dto ./internal/repository \ - -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots|ProcurementSnapshot|ObserverProcurementSnapshot)' \ + -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayProtocol|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots|ProcurementSnapshot|ObserverProcurementSnapshot)' \ -count=1 -v -timeout=10m 2>&1 | tee ../evidence/unit-race.log if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/unit-race.log; then exit 1 @@ -89,6 +90,8 @@ jobs: grep -F -- '--- PASS: TestUsagePlatformSnapshotsSelectedAccount' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementForwardingRemainsClosed' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolForwardUsesNativeBuildersAndSharedIdentity' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementUpdateRequiresAtomicCapability' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementRepositoryBindingGuard' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayDataImportIdentityValidation' ../evidence/unit-race.log @@ -102,13 +105,14 @@ jobs: run: | set -euo pipefail go test -race -tags=integration ./internal/repository \ - -run '^Test((ConcurrencyCacheSuite|AccountRepoSuite)$|GatewayAtomicUpdate)/^(TestGateway(TargetsShareAccountConcurrency|ManagementAtomicMembershipAndOAuthExclusion)|admin|account-service|bulk)$' \ + -run '^Test((ConcurrencyCacheSuite|AccountRepoSuite)$|GatewayAtomicUpdate)/^(TestGateway(TargetsShareAccountConcurrency|ManagementAtomicMembershipAndOAuthExclusion|RequestAdmissionReloadsGroupMembershipAndStatus)|admin|account-service|bulk)$' \ -count=1 -v -timeout=10m 2>&1 | tee ../evidence/concurrency-redis.log if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/concurrency-redis.log; then exit 1 fi grep -F -- '--- PASS: TestConcurrencyCacheSuite/TestGatewayTargetsShareAccountConcurrency' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayManagementAtomicMembershipAndOAuthExclusion' ../evidence/concurrency-redis.log + grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayRequestAdmissionReloadsGroupMembershipAndStatus' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestGatewayAtomicUpdateOAuthInterleaving' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestGatewayAtomicUpdateRollbackAfterStagedFields' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestGatewayAtomicUpdateSuccessfulCommit' ../evidence/concurrency-redis.log diff --git a/backend/internal/repository/gateway_request_admission.go b/backend/internal/repository/gateway_request_admission.go new file mode 100644 index 000000000000..20de24c107c9 --- /dev/null +++ b/backend/internal/repository/gateway_request_admission.go @@ -0,0 +1,49 @@ +package repository + +import ( + "context" + "database/sql" + "errors" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +var _ service.GatewayRequestAccountReader = (*accountRepository)(nil) + +func (r *accountRepository) GatewayRequestAccount(ctx context.Context, accountID, groupID int64) (*service.Account, *service.Group, error) { + if dbent.TxFromContext(ctx) == nil { + tx, err := r.client.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead}) + if errors.Is(err, dbent.ErrTxStarted) { + return r.gatewayRequestAccount(ctx, accountID, groupID) + } + if err != nil { + return nil, nil, err + } + defer func() { _ = tx.Rollback() }() + account, group, err := r.gatewayRequestAccount(dbent.NewTxContext(ctx, tx), accountID, groupID) + if err != nil { + return nil, nil, err + } + if err := tx.Commit(); err != nil { + return nil, nil, err + } + return account, group, nil + } + return r.gatewayRequestAccount(ctx, accountID, groupID) +} + +func (r *accountRepository) gatewayRequestAccount(ctx context.Context, accountID, groupID int64) (*service.Account, *service.Group, error) { + account, err := r.GetByID(ctx, accountID) + if err != nil { + return nil, nil, err + } + group, err := clientFromContext(ctx, r.client).Group.Get(ctx, groupID) + if err != nil { + return nil, nil, translatePersistenceError(err, service.ErrGroupNotFound, nil) + } + if group.DeletedAt != nil { + return nil, nil, service.ErrGroupNotFound + } + return account, groupEntityToService(group), nil +} diff --git a/backend/internal/repository/gateway_request_admission_integration_test.go b/backend/internal/repository/gateway_request_admission_integration_test.go new file mode 100644 index 000000000000..d472eae5996f --- /dev/null +++ b/backend/internal/repository/gateway_request_admission_integration_test.go @@ -0,0 +1,30 @@ +//go:build integration + +package repository + +import "github.com/Wei-Shaw/sub2api/internal/service" + +func (s *AccountRepoSuite) TestGatewayRequestAdmissionReloadsGroupMembershipAndStatus() { + group, err := s.client.Group.Create().SetName("gateway-request-admission").SetPlatform(service.PlatformComposite).Save(s.ctx) + s.Require().NoError(err) + a := &service.Account{Name: "gateway-admission", Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Status: service.StatusActive, Concurrency: 2, + Credentials: map[string]any{"upstream_kind": "sub2api", "base_url": "https://gateway.example", "api_key": "synthetic-only"}} + s.Require().NoError(s.repo.CreateWithAccountGroups(s.ctx, a, []service.AccountGroup{{GroupID: group.ID, Priority: 1}})) + current, liveGroup, err := s.repo.GatewayRequestAccount(s.ctx, a.ID, group.ID) + s.Require().NoError(err) + s.Equal([]int64{group.ID}, current.GroupIDs) + s.False(liveGroup.RequireOAuthOnly) + s.Require().NoError(s.repo.BindGroups(s.ctx, a.ID, nil)) + _, err = s.client.Group.UpdateOneID(group.ID).SetRequireOauthOnly(true).Save(s.ctx) + s.Require().NoError(err) + current, liveGroup, err = s.repo.GatewayRequestAccount(s.ctx, a.ID, group.ID) + s.Require().NoError(err) + s.Empty(current.GroupIDs, "reader cannot reuse the pre-removal membership snapshot") + s.True(liveGroup.RequireOAuthOnly, "terminal admission sees the current group policy") + _, err = s.client.Account.UpdateOneID(a.ID).SetStatus(service.StatusError).Save(s.ctx) + s.Require().NoError(err) + current, _, err = s.repo.GatewayRequestAccount(s.ctx, a.ID, group.ID) + s.Require().NoError(err) + s.Equal(service.StatusError, current.Status) +} diff --git a/backend/internal/service/antigravity_gateway_claude.go b/backend/internal/service/antigravity_gateway_claude.go index 06d0d261f8fc..976d395cff1a 100644 --- a/backend/internal/service/antigravity_gateway_claude.go +++ b/backend/internal/service/antigravity_gateway_claude.go @@ -29,7 +29,7 @@ import ( // └─ 失败 → 设置模型限流 + 清除粘性绑定 → 切换账号 func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte, isStickySession bool) (*ForwardResult, error) { if account.gatewayProtocolsPending() { - return nil, ErrGatewayProtocolsPending + return s.forwardGatewayMessages(ctx, c, account, body) } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err diff --git a/backend/internal/service/antigravity_gateway_gemini.go b/backend/internal/service/antigravity_gateway_gemini.go index e15f7089bb0f..0ab6f770e2ed 100644 --- a/backend/internal/service/antigravity_gateway_gemini.go +++ b/backend/internal/service/antigravity_gateway_gemini.go @@ -43,7 +43,7 @@ func WithForwardGeminiSession(groupID int64, sessionHash string) ForwardGeminiOp func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Context, account *Account, originalModel string, action string, stream bool, body []byte, isStickySession bool, options ...ForwardGeminiOption) (*ForwardResult, error) { if account.gatewayProtocolsPending() { - return nil, ErrGatewayProtocolsPending + return s.forwardGatewayGemini(ctx, c, account, originalModel, action, stream, body) } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err diff --git a/backend/internal/service/antigravity_gateway_upstream.go b/backend/internal/service/antigravity_gateway_upstream.go index 25b3d2e3ba07..c38ae9c8a7fa 100644 --- a/backend/internal/service/antigravity_gateway_upstream.go +++ b/backend/internal/service/antigravity_gateway_upstream.go @@ -20,7 +20,7 @@ import ( // ForwardUpstream 使用 base_url + /v1/messages + 双 header 认证透传上游 Claude 请求 func (s *AntigravityGatewayService) ForwardUpstream(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) { if account.gatewayProtocolsPending() { - return nil, ErrGatewayProtocolsPending + return s.forwardGatewayMessages(ctx, c, account, body) } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err diff --git a/backend/internal/service/gateway_forward.go b/backend/internal/service/gateway_forward.go index 1706eb8f1640..88023d961541 100644 --- a/backend/internal/service/gateway_forward.go +++ b/backend/internal/service/gateway_forward.go @@ -13,6 +13,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/pkg/claude" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" "github.com/Wei-Shaw/sub2api/internal/pkg/logger" "github.com/tidwall/gjson" @@ -121,7 +122,16 @@ func sleepWithContext(ctx context.Context, d time.Duration) error { // Forward 转发请求到Claude API func (s *GatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, parsed *ParsedRequest) (result *ForwardResult, err error) { if account.gatewayProtocolsPending() { - return nil, ErrGatewayProtocolsPending + if parsed != nil && parsed.GroupID != nil { + if group, ok := ctx.Value(ctxkey.Group).(*Group); !ok || group == nil || group.ID != *parsed.GroupID { + return nil, ErrGatewayAccountGroup + } + } + view, err := s.gatewayProtocolAccount(ctx, account, "anthropic", gatewayProtocolParsedModel(parsed)) + if err != nil { + return nil, err + } + account = view } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err diff --git a/backend/internal/service/gateway_protocol_admission.go b/backend/internal/service/gateway_protocol_admission.go new file mode 100644 index 000000000000..25c0a15471fd --- /dev/null +++ b/backend/internal/service/gateway_protocol_admission.go @@ -0,0 +1,211 @@ +package service + +import ( + "context" + "encoding/json" + "maps" + "strings" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/gin-gonic/gin" +) + +func gatewayProtocolParsedModel(parsed *ParsedRequest) string { + if parsed == nil { + return "" + } + return parsed.Model +} + +func gatewayProtocolBodyModel(body []byte) string { + var request struct { + Model string `json:"model"` + } + _ = json.Unmarshal(body, &request) + return request.Model +} + +func (s *GatewayService) gatewayProtocolAccount(ctx context.Context, account *Account, family domain.PlatformGateway, model string) (*Account, error) { + if s == nil { + return nil, ErrGatewayProtocolsPending + } + return prepareGatewayProtocolAccount(ctx, account, s.accountRepo, family, model) +} + +func (s *OpenAIGatewayService) gatewayProtocolAccount(ctx context.Context, account *Account, family domain.PlatformGateway, model string) (*Account, error) { + if s == nil { + return nil, ErrGatewayProtocolsPending + } + return prepareGatewayProtocolAccount(ctx, account, s.accountRepo, family, model) +} + +func (s *GeminiMessagesCompatService) gatewayProtocolAccount(ctx context.Context, account *Account, family domain.PlatformGateway, model string) (*Account, error) { + if s == nil { + return nil, ErrGatewayProtocolsPending + } + return prepareGatewayProtocolAccount(ctx, account, s.accountRepo, family, model) +} + +// Relay accounts on Antigravity URLs use native protocols, never the official +// cloudcode OAuth envelope or its default model aliases. +func (s *AntigravityGatewayService) forwardGatewayMessages(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) { + if s == nil { + return nil, ErrGatewayProtocolsPending + } + cfg := &config.Config{} + if s.settingService != nil && s.settingService.cfg != nil { + cfg = s.settingService.cfg + } + var request struct { + Model string `json:"model"` + Stream bool `json:"stream"` + } + if err := json.Unmarshal(body, &request); err != nil { + return nil, err + } + relay := &GatewayService{cfg: cfg, httpUpstream: s.httpUpstream, accountRepo: s.accountRepo, + rateLimitService: s.rateLimitService, settingService: s.settingService, + responseHeaderFilter: compileResponseHeaderFilter(cfg), deferredService: &DeferredService{}} + return relay.Forward(ctx, c, account, &ParsedRequest{Body: NewRequestBodyRef(body), Model: request.Model, Stream: request.Stream}) +} + +func (s *AntigravityGatewayService) forwardGatewayGemini(ctx context.Context, c *gin.Context, account *Account, model, action string, stream bool, body []byte) (*ForwardResult, error) { + if s == nil { + return nil, ErrGatewayProtocolsPending + } + cfg := &config.Config{} + if s.settingService != nil && s.settingService.cfg != nil { + cfg = s.settingService.cfg + } + relay := &GeminiMessagesCompatService{cfg: cfg, httpUpstream: s.httpUpstream, accountRepo: s.accountRepo, + rateLimitService: s.rateLimitService} + return relay.ForwardNative(ctx, c, account, model, action, stream, body) +} + +// GatewayRequestAccountReader reloads the account and its requested group at +// final admission. It never infers membership from an account platform or URL. +type GatewayRequestAccountReader interface { + GatewayRequestAccount(ctx context.Context, accountID, groupID int64) (*Account, *Group, error) +} + +// prepareGatewayProtocolAccount makes an isolated API-key transport view. The +// caller retains the original gateway for usage/procurement bookkeeping. ID, +// concurrency, proxy and runtime state remain those of the one shared account. +func prepareGatewayProtocolAccount(ctx context.Context, selected *Account, repo AccountRepository, family domain.PlatformGateway, model string) (*Account, error) { + group, _ := ctx.Value(ctxkey.Group).(*Group) + if selected == nil || !selected.IsGateway() || group == nil || group.ID <= 0 { + return nil, ErrGatewayProtocolsPending + } + if model == "" { + return nil, ErrGatewayProtocolsPending + } + reader, ok := repo.(GatewayRequestAccountReader) + if !ok { + return nil, ErrGatewayProtocolsPending + } + current, liveGroup, err := reader.GatewayRequestAccount(ctx, selected.ID, group.ID) + if err != nil { + return nil, err + } + if current == nil || !current.IsGateway() || current.Platform != PlatformGateway || current.ID != selected.ID || liveGroup == nil || liveGroup.ID != group.ID || + !liveGroup.IsActive() || ValidateGatewayAccountGroup(current, liveGroup) != nil { + return nil, ErrGatewayAccountGroup + } + if err := ValidateGatewayAccountIdentity(current.Platform, current.Type, current.Credentials); err != nil { + return nil, err + } + if current.ParentAccountID != nil || current.AuthConnectionID != "" { + return nil, ErrGatewayAccountIdentity + } + // A credential/proxy edit after selection requires a fresh selection, rather + // than forwarding with one identity and logging another identity's snapshot. + for _, key := range []string{"api_key", "base_url", GatewayUpstreamKindCredentialKey} { + if selected.GetCredential(key) != current.GetCredential(key) { + return nil, ErrGatewayAccountIdentity + } + } + if (selected.ProxyID == nil) != (current.ProxyID == nil) || + (selected.ProxyID != nil && *selected.ProxyID != *current.ProxyID) { + return nil, ErrGatewayAccountIdentity + } + member := false + for _, id := range current.GroupIDs { + member = member || id == liveGroup.ID + } + for _, binding := range current.AccountGroups { + member = member || binding.GroupID == liveGroup.ID + } + if !member { + return nil, ErrGatewayAccountGroup + } + target := liveGroup.Platform + if resolved, ok := ResolvedTargetPlatformFromContext(ctx); ok { + target = resolved + } + if forced, _ := ctx.Value(ctxkey.ForcePlatform).(string); forced != "" { + if resolved, ok := ResolvedTargetPlatformFromContext(ctx); ok && resolved != forced { + return nil, ErrGatewayAccountGroup + } + target = forced + } + spec, concrete := domain.LookupPlatform(target) + if !concrete || (liveGroup.Platform != PlatformComposite && liveGroup.Platform != target) { + return nil, ErrGatewayAccountGroup + } + if spec.Gateway != family && !(target == PlatformAntigravity && (family == domain.PlatformGatewayAnthropic || family == domain.PlatformGatewayGemini)) { + return nil, ErrGatewayProtocolsPending + } + // Validate model scope while the account still has its neutral identity: no + // official provider defaults or passthrough options can bypass a whitelist. + scope := *current + scope.Credentials = maps.Clone(current.Credentials) + scope.modelMappingCacheReady = false + id := liveGroup.ID + publicModel := model + if original, ok := RequestedPublicModelFromContext(ctx); ok { + publicModel = original + } + if !liveGroup.ModelAllowlist.Allows(publicModel) || !scope.isModelMappingSupported(model) || !scope.IsModelAllowedInGroup(&id, model) { + return nil, ErrGatewayAccountGroup + } + view := scope + view.Type = AccountTypeAPIKey + view.Platform = string(family) + // Provider-specific alternate credentials/endpoints are not gateway inputs. + // Keep only the one upstream key/site and portable mapping/header settings. + view.Credentials = make(map[string]any) + for _, key := range []string{"api_key", "base_url", "model_mapping", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} { + if value, ok := scope.Credentials[key]; ok { + view.Credentials[key] = value + } + } + // Only normalize a terminal protocol version. Tenant prefixes stay intact; + // native builders append the protocol's own /v1 or /v1beta exactly once. + base := strings.TrimSuffix(strings.TrimRight(view.GetCredential("base_url"), "/"), "/v1beta") + if family == domain.PlatformGatewayGemini { + base = strings.TrimSuffix(base, "/v1") + } + view.Credentials["base_url"] = base + delete(view.Credentials, "api_base_urls") + view.Extra = maps.Clone(current.Extra) + if view.Extra == nil { + view.Extra = make(map[string]any) + } + for _, key := range []string{"openai_connections_managed", "openai_copilot_sdk", "openai_prism_browser", "custom_base_url_enabled"} { + delete(view.Extra, key) + } + view.modelMappingCacheReady = false + if !view.IsSchedulable() { + return nil, ErrGatewayProtocolsPending + } + if family == domain.PlatformGatewayAnthropic { + view.Extra["anthropic_passthrough"] = true + } + if family == domain.PlatformGatewayOpenAI { + view.Extra["openai_passthrough"] = true + view.Extra["openai_passthrough_model_filter"] = true + } + return &view, nil +} diff --git a/backend/internal/service/gateway_protocol_admission_test.go b/backend/internal/service/gateway_protocol_admission_test.go new file mode 100644 index 000000000000..654764e16ab0 --- /dev/null +++ b/backend/internal/service/gateway_protocol_admission_test.go @@ -0,0 +1,163 @@ +//go:build unit + +package service + +import ( + "context" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/domain" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/stretchr/testify/require" +) + +type gatewayProtocolAdmissionRepo struct { + AccountRepository + account *Account + group *Group + calls int +} + +func (r *gatewayProtocolAdmissionRepo) GatewayRequestAccount(_ context.Context, _, _ int64) (*Account, *Group, error) { + r.calls++ + return r.account, r.group, nil +} + +func gatewayProtocolFixture(target string) (*gatewayProtocolAdmissionRepo, context.Context) { + a := &Account{ID: 959, Platform: PlatformGateway, Type: AccountTypeGateway, Status: StatusActive, Schedulable: true, + Concurrency: 2, Priority: 7, GroupIDs: []int64{1}, AccountGroups: []AccountGroup{{GroupID: 1}}, + Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example/tenant/v1", "api_key": "synthetic-only"}} + g := &Group{ID: 1, Platform: target, Status: StatusActive, Hydrated: true} + return &gatewayProtocolAdmissionRepo{account: a, group: g}, context.WithValue(context.Background(), ctxkey.Group, g) +} + +func TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity(t *testing.T) { + for _, spec := range domain.Platforms() { + for _, composite := range []bool{false, true} { + t.Run(spec.ID+map[bool]string{false: "/concrete", true: "/composite"}[composite], func(t *testing.T) { + repo, ctx := gatewayProtocolFixture(spec.ID) + if composite { + repo.group.Platform = PlatformComposite + ctx = WithResolvedTargetPlatform(ctx, spec.ID) + } + family := spec.Gateway + if family == domain.PlatformGatewayAntigravity { + family = domain.PlatformGatewayAnthropic + } + view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, family, "public-model") + require.NoError(t, err) + require.Equal(t, repo.account.ID, view.ID) + require.Equal(t, 2, view.Concurrency) + require.Equal(t, 7, view.Priority) + require.Equal(t, AccountTypeAPIKey, view.Type) + require.Equal(t, "synthetic-only", view.GetCredential("api_key")) + wantBase := "https://gateway.example/tenant/v1" + if family == domain.PlatformGatewayGemini { + wantBase = "https://gateway.example/tenant" + } + require.Equal(t, wantBase, view.GetCredential("base_url")) + require.Equal(t, "public-model", view.GetMappedModel("public-model"), "default model names pass through") + require.Equal(t, PlatformGateway, repo.account.Platform) + require.Equal(t, AccountTypeGateway, repo.account.Type) + view.Credentials["api_key"] = "changed-view-only" + require.Equal(t, "synthetic-only", repo.account.GetCredential("api_key")) + }) + } + } +} + +func TestGatewayProtocolAdmissionRejectsUnboundWrongTargetAndOAuth(t *testing.T) { + for _, scenario := range []string{"no-context", "unbound", "wrong-target", "oauth-only", "disabled-group", "disabled-account", "unschedulable", "unresolved-composite", "invalid-url", "model-group", "model-account", "wrong-protocol", "legacy-replacement"} { + t.Run(scenario, func(t *testing.T) { + repo, ctx := gatewayProtocolFixture(PlatformOpenAI) + family := domain.PlatformGatewayOpenAI + switch scenario { + case "no-context": + ctx = context.Background() + case "unbound": + repo.account.GroupIDs, repo.account.AccountGroups = nil, nil + case "wrong-target": + ctx = WithResolvedTargetPlatform(ctx, PlatformKimi) + case "oauth-only": + repo.group.RequireOAuthOnly = true + case "disabled-group": + repo.group.Status = StatusDisabled + case "disabled-account": + repo.account.Status = StatusDisabled + case "unschedulable": + repo.account.Schedulable = false + case "unresolved-composite": + repo.group.Platform = PlatformComposite + case "invalid-url": + repo.account.Credentials["base_url"] = "https://gateway.example?key=secret" + case "model-group": + repo.account.AccountGroups[0].AllowedModels = []string{"other"} + case "model-account": + repo.account.Credentials["model_mapping"] = map[string]any{"other": "other"} + case "wrong-protocol": + family = domain.PlatformGatewayGemini + case "legacy-replacement": + repo.account.Type, repo.account.Platform = AccountTypeAPIKey, PlatformOpenAI + } + _, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, family, "public-model") + require.Error(t, err) + }) + } +} + +func TestGatewayProtocolAdmissionBaseVersionAndModelScopes(t *testing.T) { + for _, suffix := range []string{"", "/v1", "/v1beta", "/v1/"} { + repo, ctx := gatewayProtocolFixture(PlatformGemini) + repo.account.Credentials["base_url"] = "https://gateway.example/tenant" + suffix + view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayGemini, "public-model") + require.NoError(t, err) + require.Equal(t, "https://gateway.example/tenant", view.GetCredential("base_url")) + require.Equal(t, "https://gateway.example/tenant"+suffix, repo.account.GetCredential("base_url"), "URL normalization is request-local") + } + repo, ctx := gatewayProtocolFixture(PlatformComposite) + ctx = WithCompositeRouteDecision(ctx, CompositeRouteDecision{Matched: true, PublicModel: "public-alias", UpstreamModel: "resolved-model", TargetPlatform: PlatformOpenAI}) + repo.group.ModelAllowlist = GroupModelAllowlist{Enabled: true, Models: []string{"public-alias"}} + repo.account.AccountGroups[0].AllowedModels = []string{"resolved-model"} + repo.account.Credentials["model_mapping"] = map[string]any{"resolved-model": "upstream-model"} + view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayOpenAI, "resolved-model") + require.NoError(t, err) + require.Equal(t, "upstream-model", view.GetMappedModel("resolved-model")) + repo.account.Credentials["api_base_urls"] = map[string]any{"responses": "https://alternate.invalid"} + repo.account.Extra = map[string]any{"openai_copilot_sdk": true, "openai_connections_managed": true} + view, err = prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayOpenAI, "resolved-model") + require.NoError(t, err) + require.NotContains(t, view.Credentials, "api_base_urls") + require.False(t, view.IsCopilotSDKEnabled()) + require.False(t, view.HasManagedOpenAIConnections()) +} + +func TestGatewayProtocolAdmissionAntigravityAcceptsBothNativeProtocols(t *testing.T) { + repo, ctx := gatewayProtocolFixture(PlatformAntigravity) + for _, family := range []domain.PlatformGateway{domain.PlatformGatewayAnthropic, domain.PlatformGatewayGemini} { + view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, family, "custom-model") + require.NoError(t, err) + require.Equal(t, "custom-model", view.GetMappedModel("custom-model"), "do not inject official Antigravity mappings into a relay") + } + ctx = context.WithValue(ctx, ctxkey.ForcePlatform, PlatformGemini) + _, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayGemini, "custom-model") + require.Error(t, err, "forced URL must not bypass concrete group target") +} + +func TestGatewayProtocolAdmissionSharedStateAndSelectionIdentity(t *testing.T) { + repo, ctx := gatewayProtocolFixture(PlatformComposite) + selected := *repo.account + selected.Credentials = map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example/tenant/v1", "api_key": "synthetic-only"} + repo.account.Credentials["api_key"] = "rotated-after-selection" + _, err := prepareGatewayProtocolAccount(WithResolvedTargetPlatform(ctx, PlatformOpenAI), &selected, repo, domain.PlatformGatewayOpenAI, "public-model") + require.ErrorIs(t, err, ErrGatewayAccountIdentity) + repo.account.Credentials["api_key"] = "synthetic-only" + repo.account.Status = StatusError + for _, target := range []string{PlatformOpenAI, PlatformAnthropic, PlatformGemini, PlatformAntigravity} { + family := domain.PlatformGateway(target) + if target == PlatformAntigravity { + family = domain.PlatformGatewayAnthropic + } + _, err := prepareGatewayProtocolAccount(WithResolvedTargetPlatform(ctx, target), &selected, repo, family, "public-model") + require.Error(t, err, "one shared account error blocks all target protocols") + } +} diff --git a/backend/internal/service/gateway_protocol_forward_test.go b/backend/internal/service/gateway_protocol_forward_test.go new file mode 100644 index 000000000000..a4352f88af60 --- /dev/null +++ b/backend/internal/service/gateway_protocol_forward_test.go @@ -0,0 +1,143 @@ +//go:build unit + +package service + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +type gatewayProtocolTransport struct { + anthropicHTTPUpstreamRecorder + accountID int64 + concurrency int +} + +func (u *gatewayProtocolTransport) Do(req *http.Request, proxy string, id int64, concurrency int) (*http.Response, error) { + u.accountID, u.concurrency = id, concurrency + return u.anthropicHTTPUpstreamRecorder.Do(req, proxy, id, concurrency) +} + +func (u *gatewayProtocolTransport) DoWithTLS(req *http.Request, proxy string, id int64, concurrency int, _ *tlsfingerprint.Profile) (*http.Response, error) { + return u.Do(req, proxy, id, concurrency) +} + +func TestGatewayProtocolForwardUsesNativeBuildersAndSharedIdentity(t *testing.T) { + for _, route := range []string{"anthropic", "openai", "gemini", "antigravity-messages", "antigravity-gemini"} { + t.Run(route, func(t *testing.T) { + target := route + if strings.HasPrefix(route, "antigravity-") { + target = PlatformAntigravity + } + repo, ctx := gatewayProtocolFixture(target) + repo.account.Credentials["model_mapping"] = map[string]any{"public-model": "upstream-model"} + body := []byte(`{"model":"public-model","messages":[{"role":"user","content":"hello"}],"max_tokens":16,"stream":false}`) + path, content := "/v1/messages", `{"id":"fixture","type":"message","model":"upstream-model","content":[{"type":"text","text":"OK"}],"usage":{"input_tokens":10,"output_tokens":2}}` + if route == "openai" { + path = "/v1/responses" + body = []byte(`{"model":"public-model","input":"hello","stream":false}`) + content = `{"id":"resp_fixture","object":"response","status":"completed","model":"upstream-model","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":10,"output_tokens":2,"total_tokens":12}}` + } + if route == "gemini" || route == "antigravity-gemini" { + path = "/v1beta/models/public-model:generateContent" + body = []byte(`{"contents":[{"role":"user","parts":[{"text":"hello"}]}]}`) + content = `{"candidates":[{"content":{"parts":[{"text":"OK"}],"role":"model"},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":2,"totalTokenCount":12}}` + } + if strings.HasPrefix(route, "antigravity-") { + path = "/antigravity" + path + } + upstream := &gatewayProtocolTransport{anthropicHTTPUpstreamRecorder: anthropicHTTPUpstreamRecorder{resp: &http.Response{StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"application/json"}, "X-Request-Id": []string{"fixture-id"}}, Body: io.NopCloser(strings.NewReader(content))}}} + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)).WithContext(ctx) + c.Request.Host = "inbound-only.invalid" + c.Request.Header.Set("Authorization", "Bearer inbound-must-not-leak") + cfg := &config.Config{} + var err error + switch route { + case "anthropic": + svc := &GatewayService{cfg: cfg, accountRepo: repo, httpUpstream: upstream, + responseHeaderFilter: compileResponseHeaderFilter(cfg), rateLimitService: &RateLimitService{}, deferredService: &DeferredService{}} + _, err = svc.Forward(ctx, c, repo.account, &ParsedRequest{Body: NewRequestBodyRef(body), Model: "public-model"}) + case "openai": + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), accountRepo: repo, httpUpstream: upstream, + rateLimitService: &RateLimitService{}, deferredService: &DeferredService{}, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + _, err = svc.Forward(ctx, c, repo.account, body) + case "gemini": + svc := &GeminiMessagesCompatService{cfg: cfg, accountRepo: repo, httpUpstream: upstream, rateLimitService: &RateLimitService{}} + _, err = svc.ForwardNative(ctx, c, repo.account, "public-model", "generateContent", false, body) + case "antigravity-messages": + svc := &AntigravityGatewayService{accountRepo: repo, httpUpstream: upstream, rateLimitService: &RateLimitService{}, settingService: &SettingService{cfg: cfg}} + _, err = svc.Forward(ctx, c, repo.account, body, false) + case "antigravity-gemini": + svc := &AntigravityGatewayService{accountRepo: repo, httpUpstream: upstream, rateLimitService: &RateLimitService{}, settingService: &SettingService{cfg: cfg}} + _, err = svc.ForwardGemini(ctx, c, repo.account, "public-model", "generateContent", false, body, false) + } + require.NoError(t, err) + require.NotNil(t, upstream.lastReq, "real service entry must reach its existing native upstream builder") + require.Equal(t, "gateway.example", upstream.lastReq.URL.Host) + if route == "gemini" || route == "antigravity-gemini" { + require.Equal(t, "/tenant/v1beta/models/upstream-model:generateContent", upstream.lastReq.URL.Path) + require.Equal(t, "synthetic-only", upstream.lastReq.Header.Get("x-goog-api-key")) + } else { + want := "/tenant/v1/messages" + if route == "openai" { + want = "/tenant/v1/responses" + } + require.Equal(t, want, upstream.lastReq.URL.Path) + require.Contains(t, string(upstream.lastBody), "upstream-model") + require.NotContains(t, upstream.lastReq.Header.Get("Authorization"), "inbound-must-not-leak") + } + require.Equal(t, AccountTypeGateway, repo.account.Type) + require.Equal(t, PlatformGateway, repo.account.Platform) + require.Equal(t, int64(959), repo.account.ID) + require.Equal(t, int64(959), upstream.accountID, "all native transports share one account key and connection budget") + require.Equal(t, 2, upstream.concurrency) + require.NotEmpty(t, recorder.Body.String()) + }) + } +} + +func TestGatewayProtocolForwardRejectsRemovedMembershipBeforeTransport(t *testing.T) { + for _, route := range []string{"anthropic", "openai", "gemini", "antigravity-messages", "antigravity-gemini"} { + t.Run(route, func(t *testing.T) { + target := route + if strings.HasPrefix(route, "antigravity-") { + target = PlatformAntigravity + } + repo, ctx := gatewayProtocolFixture(target) + selected := *repo.account + repo.account = &Account{ID: selected.ID, Platform: PlatformGateway, Type: AccountTypeGateway, + Status: StatusActive, Schedulable: true, Credentials: selected.Credentials} + upstream := &gatewayProtocolTransport{} + body := []byte(`{"model":"public-model","messages":[{"role":"user","content":"hello"}]}`) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)).WithContext(ctx) + var err error + switch route { + case "anthropic": + _, err = (&GatewayService{accountRepo: repo, httpUpstream: upstream}).Forward(ctx, c, &selected, &ParsedRequest{Model: "public-model", Body: NewRequestBodyRef(body)}) + case "openai": + _, err = (&OpenAIGatewayService{accountRepo: repo, httpUpstream: upstream}).Forward(ctx, c, &selected, body) + case "gemini": + _, err = (&GeminiMessagesCompatService{accountRepo: repo, httpUpstream: upstream}).ForwardNative(ctx, c, &selected, "public-model", "generateContent", false, body) + case "antigravity-messages": + _, err = (&AntigravityGatewayService{accountRepo: repo, httpUpstream: upstream}).Forward(ctx, c, &selected, body, false) + case "antigravity-gemini": + _, err = (&AntigravityGatewayService{accountRepo: repo, httpUpstream: upstream}).ForwardGemini(ctx, c, &selected, "public-model", "generateContent", false, body, false) + } + require.ErrorIs(t, err, ErrGatewayAccountGroup) + require.Nil(t, upstream.lastReq, "stale selection cannot leak a key after membership removal") + }) + } +} diff --git a/backend/internal/service/gemini_messages_compat_service.go b/backend/internal/service/gemini_messages_compat_service.go index 8ac3e36951b2..b2b9633b176c 100644 --- a/backend/internal/service/gemini_messages_compat_service.go +++ b/backend/internal/service/gemini_messages_compat_service.go @@ -542,7 +542,11 @@ func (s *GeminiMessagesCompatService) HasAntigravityAccounts(ctx context.Context func (s *GeminiMessagesCompatService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (*ForwardResult, error) { if account.gatewayProtocolsPending() { - return nil, ErrGatewayProtocolsPending + view, err := s.gatewayProtocolAccount(ctx, account, "gemini", gatewayProtocolBodyModel(body)) + if err != nil { + return nil, err + } + account = view } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err @@ -1116,7 +1120,11 @@ func isGeminiSignatureRelatedError(respBody []byte) bool { func (s *GeminiMessagesCompatService) ForwardNative(ctx context.Context, c *gin.Context, account *Account, originalModel string, action string, stream bool, body []byte) (*ForwardResult, error) { if account.gatewayProtocolsPending() { - return nil, ErrGatewayProtocolsPending + view, err := s.gatewayProtocolAccount(ctx, account, "gemini", originalModel) + if err != nil { + return nil, err + } + account = view } if err := CheckUpstreamModeration(ctx, c, account); err != nil { return nil, err diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 277a48e855d5..a091a7bfeeea 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -64,7 +64,11 @@ func (s *OpenAIGatewayService) ForwardAsChatCompletions( defaultMappedModel string, ) (*OpenAIForwardResult, error) { if account.gatewayProtocolsPending() { - return nil, ErrGatewayProtocolsPending + view, err := s.gatewayProtocolAccount(ctx, account, "openai", gatewayProtocolBodyModel(body)) + if err != nil { + return nil, err + } + account = view } admittedCtx, admissionErr := s.beginPriorityLatencyTurn(ctx, c, account, gjson.GetBytes(body, "model").String()) diff --git a/backend/internal/service/openai_gateway_forward.go b/backend/internal/service/openai_gateway_forward.go index 05990d39994e..3c0417f1d841 100644 --- a/backend/internal/service/openai_gateway_forward.go +++ b/backend/internal/service/openai_gateway_forward.go @@ -92,7 +92,11 @@ func prismBrowserResponsesURL(baseURL string) string { // Forward forwards request to OpenAI API func (s *OpenAIGatewayService) Forward(ctx context.Context, c *gin.Context, account *Account, body []byte) (result *OpenAIForwardResult, resultErr error) { if account.gatewayProtocolsPending() { - return nil, ErrGatewayProtocolsPending + view, err := s.gatewayProtocolAccount(ctx, account, "openai", gatewayProtocolBodyModel(body)) + if err != nil { + return nil, err + } + account = view } preparedCtx, preparedBody, prepareErr := s.prepareOpenAIAgentOAuthReplay(ctx, account, body) if prepareErr != nil { diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index ef2cdd1197d5..e94bab674efb 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -34,7 +34,11 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( defaultMappedModel string, ) (*OpenAIForwardResult, error) { if account.gatewayProtocolsPending() { - return nil, ErrGatewayProtocolsPending + view, err := s.gatewayProtocolAccount(ctx, account, "openai", gatewayProtocolBodyModel(body)) + if err != nil { + return nil, err + } + account = view } admittedCtx, admissionErr := s.beginPriorityLatencyTurn(ctx, c, account, gjson.GetBytes(body, "model").String()) From 3b7aca97de20e52c97722c766a322247825b0aef Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 11:16:24 +0800 Subject: [PATCH 11/26] fix: retain parsed request and model cooldown in relay admission Use the shared Anthropic parser for Antigravity relay Messages after integration, preserving request ranges and 024 normalization semantics. Recheck model-scoped eligibility on the isolated transport view so current cooldown state is retained. Add the model cooldown source regression; dynamic validation remains remote CI only. --- .../internal/service/gateway_protocol_admission.go | 11 ++++------- .../service/gateway_protocol_admission_test.go | 12 ++++++++++++ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/backend/internal/service/gateway_protocol_admission.go b/backend/internal/service/gateway_protocol_admission.go index 25c0a15471fd..a446af116197 100644 --- a/backend/internal/service/gateway_protocol_admission.go +++ b/backend/internal/service/gateway_protocol_admission.go @@ -58,17 +58,14 @@ func (s *AntigravityGatewayService) forwardGatewayMessages(ctx context.Context, if s.settingService != nil && s.settingService.cfg != nil { cfg = s.settingService.cfg } - var request struct { - Model string `json:"model"` - Stream bool `json:"stream"` - } - if err := json.Unmarshal(body, &request); err != nil { + parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic) + if err != nil { return nil, err } relay := &GatewayService{cfg: cfg, httpUpstream: s.httpUpstream, accountRepo: s.accountRepo, rateLimitService: s.rateLimitService, settingService: s.settingService, responseHeaderFilter: compileResponseHeaderFilter(cfg), deferredService: &DeferredService{}} - return relay.Forward(ctx, c, account, &ParsedRequest{Body: NewRequestBodyRef(body), Model: request.Model, Stream: request.Stream}) + return relay.Forward(ctx, c, account, parsed) } func (s *AntigravityGatewayService) forwardGatewayGemini(ctx context.Context, c *gin.Context, account *Account, model, action string, stream bool, body []byte) (*ForwardResult, error) { @@ -197,7 +194,7 @@ func prepareGatewayProtocolAccount(ctx context.Context, selected *Account, repo delete(view.Extra, key) } view.modelMappingCacheReady = false - if !view.IsSchedulable() { + if !view.IsSchedulableForModelWithContext(ctx, model) { return nil, ErrGatewayProtocolsPending } if family == domain.PlatformGatewayAnthropic { diff --git a/backend/internal/service/gateway_protocol_admission_test.go b/backend/internal/service/gateway_protocol_admission_test.go index 654764e16ab0..207b81082c20 100644 --- a/backend/internal/service/gateway_protocol_admission_test.go +++ b/backend/internal/service/gateway_protocol_admission_test.go @@ -5,6 +5,7 @@ package service import ( "context" "testing" + "time" "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" @@ -161,3 +162,14 @@ func TestGatewayProtocolAdmissionSharedStateAndSelectionIdentity(t *testing.T) { require.Error(t, err, "one shared account error blocks all target protocols") } } + +func TestGatewayProtocolAdmissionPreservesModelCooldown(t *testing.T) { + repo, ctx := gatewayProtocolFixture(PlatformOpenAI) + repo.account.Extra = map[string]any{modelRateLimitsKey: map[string]any{ + "public-model": map[string]any{"rate_limit_reset_at": time.Now().Add(time.Hour).Format(time.RFC3339)}, + }} + _, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayOpenAI, "public-model") + require.ErrorIs(t, err, ErrGatewayProtocolsPending, "transport view must retain existing per-model cooldown admission") + _, err = prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayOpenAI, "another-model") + require.NoError(t, err, "a model cooldown does not erase other model capacity") +} From 1c1f913d4d0afbe88277fb0f926972864846a12c Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 11:26:31 +0800 Subject: [PATCH 12/26] fix: preserve gateway identity through final OpenAI admission --- .../workflows/issue959-gateway-regression.yml | 4 + backend/internal/service/account.go | 5 + .../service/gateway_protocol_admission.go | 12 +- .../service/gateway_protocol_forward_test.go | 4 +- .../gateway_protocol_openai_admission_test.go | 193 ++++++++++++++++++ .../openai_gateway_chat_completions.go | 7 + .../service/openai_gateway_messages.go | 7 + .../service/openai_gateway_passthrough.go | 14 ++ .../internal/service/openai_turn_admission.go | 47 ++++- 9 files changed, 285 insertions(+), 8 deletions(-) create mode 100644 backend/internal/service/gateway_protocol_openai_admission_test.go diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index 6a5629b8af3b..a4b9cb2a4a5b 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -91,6 +91,10 @@ jobs: grep -F -- '--- PASS: TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementForwardingRemainsClosed' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolForwardUsesNativeBuildersAndSharedIdentity' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolOpenAIAuthoritativeAdmission' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolOpenAIRejectsFinalAuthorityChanges' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolOpenAIResponsesMappedWireModel' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolOpenAILegacyPassthroughKeepsWireModel' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementUpdateRequiresAtomicCapability' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementRepositoryBindingGuard' ../evidence/unit-race.log diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 1f0fd2c18af7..18cbbfe6880b 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -79,6 +79,11 @@ type Account struct { GroupIDs []int64 Groups []*Group + // Request-local transport binding only; never persisted or exported. Final + // admission compares the neutral gateway identity before rebuilding a view. + gatewayProtocolSource *Account + gatewayProtocolModel string + // model_mapping 热路径缓存(非持久化字段) modelMappingCache map[string]string modelMappingCacheReady bool diff --git a/backend/internal/service/gateway_protocol_admission.go b/backend/internal/service/gateway_protocol_admission.go index a446af116197..793d624559e3 100644 --- a/backend/internal/service/gateway_protocol_admission.go +++ b/backend/internal/service/gateway_protocol_admission.go @@ -106,6 +106,14 @@ func prepareGatewayProtocolAccount(ctx context.Context, selected *Account, repo if err != nil { return nil, err } + return gatewayProtocolAccountFromSnapshot(ctx, selected, current, liveGroup, family, model) +} + +func gatewayProtocolAccountFromSnapshot(ctx context.Context, selected, current *Account, liveGroup *Group, family domain.PlatformGateway, model string) (*Account, error) { + group, _ := ctx.Value(ctxkey.Group).(*Group) + if selected == nil || group == nil || model == "" { + return nil, ErrGatewayProtocolsPending + } if current == nil || !current.IsGateway() || current.Platform != PlatformGateway || current.ID != selected.ID || liveGroup == nil || liveGroup.ID != group.ID || !liveGroup.IsActive() || ValidateGatewayAccountGroup(current, liveGroup) != nil { return nil, ErrGatewayAccountGroup @@ -168,12 +176,14 @@ func prepareGatewayProtocolAccount(ctx context.Context, selected *Account, repo return nil, ErrGatewayAccountGroup } view := scope + view.gatewayProtocolSource = &scope + view.gatewayProtocolModel = model view.Type = AccountTypeAPIKey view.Platform = string(family) // Provider-specific alternate credentials/endpoints are not gateway inputs. // Keep only the one upstream key/site and portable mapping/header settings. view.Credentials = make(map[string]any) - for _, key := range []string{"api_key", "base_url", "model_mapping", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} { + for _, key := range []string{"api_key", "base_url", "model_mapping", "compact_model_mapping", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} { if value, ok := scope.Credentials[key]; ok { view.Credentials[key] = value } diff --git a/backend/internal/service/gateway_protocol_forward_test.go b/backend/internal/service/gateway_protocol_forward_test.go index a4352f88af60..9c4faca4142c 100644 --- a/backend/internal/service/gateway_protocol_forward_test.go +++ b/backend/internal/service/gateway_protocol_forward_test.go @@ -20,10 +20,12 @@ type gatewayProtocolTransport struct { anthropicHTTPUpstreamRecorder accountID int64 concurrency int + proxyURL string } func (u *gatewayProtocolTransport) Do(req *http.Request, proxy string, id int64, concurrency int) (*http.Response, error) { u.accountID, u.concurrency = id, concurrency + u.proxyURL = proxy return u.anthropicHTTPUpstreamRecorder.Do(req, proxy, id, concurrency) } @@ -70,7 +72,7 @@ func TestGatewayProtocolForwardUsesNativeBuildersAndSharedIdentity(t *testing.T) responseHeaderFilter: compileResponseHeaderFilter(cfg), rateLimitService: &RateLimitService{}, deferredService: &DeferredService{}} _, err = svc.Forward(ctx, c, repo.account, &ParsedRequest{Body: NewRequestBodyRef(body), Model: "public-model"}) case "openai": - svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), accountRepo: repo, httpUpstream: upstream, + svc := &OpenAIGatewayService{cfg: rawChatCompletionsTestConfig(), accountRepo: &gatewayProtocolOpenAIRepo{gatewayProtocolAdmissionRepo: repo}, httpUpstream: upstream, requireLatestTurnAdmission: true, rateLimitService: &RateLimitService{}, deferredService: &DeferredService{}, responseHeaderFilter: compileResponseHeaderFilter(cfg)} _, err = svc.Forward(ctx, c, repo.account, body) case "gemini": diff --git a/backend/internal/service/gateway_protocol_openai_admission_test.go b/backend/internal/service/gateway_protocol_openai_admission_test.go new file mode 100644 index 000000000000..f5e51ee3bafd --- /dev/null +++ b/backend/internal/service/gateway_protocol_openai_admission_test.go @@ -0,0 +1,193 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "maps" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +// Both production reader capabilities are required; a supplied-account-only +// fixture cannot exercise the final authoritative OpenAI send boundary. +type gatewayProtocolOpenAIRepo struct { + *gatewayProtocolAdmissionRepo + turnReads int + changeAt int + change func(*Account) +} + +func (r *gatewayProtocolOpenAIRepo) GetOpenAITurnAdmission(context.Context, int64) (*Account, *Account, error) { + r.turnReads++ + a := *r.account + a.Credentials = maps.Clone(a.Credentials) + if r.change != nil && r.turnReads >= r.changeAt { + r.change(&a) + } + return &a, nil, nil +} + +func gatewayProtocolOpenAIForward(t *testing.T, route string, stream bool, repo *gatewayProtocolOpenAIRepo, ctx context.Context) (*OpenAIForwardResult, *gatewayProtocolTransport, *httptest.ResponseRecorder, error) { + t.Helper() + path := "/v1/responses" + body := []byte(`{"model":"public-model","input":"hello","stream":false}`) + if stream { + body = []byte(`{"model":"public-model","input":"hello","stream":true}`) + } + if route == "compact" { + path += "/compact" + } + if route == "chat" || route == "messages" { + path = "/v1/chat/completions" + body = []byte(`{"model":"public-model","messages":[{"role":"user","content":"hello"}],"max_tokens":16,"stream":false}`) + if route == "messages" { + path = "/v1/messages" + } + } + content := `{"id":"resp_fixture","object":"response","status":"completed","model":"upstream-model","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":10,"output_tokens":2,"total_tokens":12}}` + contentType := "application/json" + if stream { + contentType = "text/event-stream" + content = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"OK\"}\n\ndata: {\"type\":\"response.completed\",\"response\":" + content + "}\n\ndata: [DONE]\n\n" + } + if route == "compact" { + if mapped, ok := repo.account.ResolveCompactMappedModel("public-model"); ok { + content = strings.ReplaceAll(content, "upstream-model", mapped) + } + } + upstream := &gatewayProtocolTransport{anthropicHTTPUpstreamRecorder: anthropicHTTPUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{contentType}}, Body: io.NopCloser(strings.NewReader(content))}}} + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)).WithContext(ctx) + groupID := repo.group.ID + c.Set("api_key", &APIKey{GroupID: &groupID}) + cfg := rawChatCompletionsTestConfig() + svc := &OpenAIGatewayService{cfg: cfg, accountRepo: repo, httpUpstream: upstream, + requireLatestTurnAdmission: true, rateLimitService: &RateLimitService{}, deferredService: &DeferredService{}, responseHeaderFilter: compileResponseHeaderFilter(cfg)} + var result *OpenAIForwardResult + var err error + switch route { + case "chat": + result, err = svc.ForwardAsChatCompletions(ctx, c, repo.account, body, "", "") + case "messages": + result, err = svc.ForwardAsAnthropic(ctx, c, repo.account, body, "", "") + default: + result, err = svc.Forward(ctx, c, repo.account, body) + } + return result, upstream, recorder, err +} + +func TestGatewayProtocolOpenAIAuthoritativeAdmission(t *testing.T) { + for _, route := range []string{"responses", "chat", "messages"} { + t.Run(route, func(t *testing.T) { + base, ctx := gatewayProtocolFixture(PlatformOpenAI) + base.account.Credentials["model_mapping"] = map[string]any{"public-model": "upstream-model"} + base.account.AccountGroups[0].AllowedModels = []string{"public-model"} + proxyID := int64(95) + base.account.ProxyID = &proxyID + base.account.Proxy = &Proxy{ID: proxyID, Protocol: "http", Host: "proxy.invalid", Port: 8080} + repo := &gatewayProtocolOpenAIRepo{gatewayProtocolAdmissionRepo: base} + result, upstream, _, err := gatewayProtocolOpenAIForward(t, route, false, repo, ctx) + require.NoError(t, err) + require.NotNil(t, result) + require.GreaterOrEqual(t, repo.turnReads, 2, "initial and actual-send admission must both read authority") + require.NotNil(t, upstream.lastReq) + require.Equal(t, "upstream-model", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, int64(959), upstream.accountID) + require.Equal(t, 2, upstream.concurrency) + require.Equal(t, "http://proxy.invalid:8080", upstream.proxyURL) + require.Equal(t, PlatformGateway, repo.account.Platform) + require.False(t, repo.account.IsSchedulable(), "the scheduler stays fail closed") + }) + } +} + +func TestGatewayProtocolOpenAIRejectsFinalAuthorityChanges(t *testing.T) { + for _, route := range []string{"responses", "chat", "messages"} { + for _, change := range []string{"membership", "disabled", "credential", "platform", "cooldown", "disabled-group", "oauth-only"} { + t.Run(route+"/"+change, func(t *testing.T) { + base, ctx := gatewayProtocolFixture(PlatformOpenAI) + repo := &gatewayProtocolOpenAIRepo{gatewayProtocolAdmissionRepo: base, changeAt: 2, change: func(a *Account) { + switch change { + case "membership": + a.GroupIDs, a.AccountGroups = nil, nil + case "disabled": + a.Status = StatusDisabled + case "credential": + a.Credentials["api_key"] = "rotated-synthetic-only" + case "platform": + a.Platform, a.Type = PlatformOpenAI, AccountTypeAPIKey + case "cooldown": + a.Schedulable = false + case "disabled-group": + base.group.Status = StatusDisabled + case "oauth-only": + base.group.RequireOAuthOnly = true + } + }} + _, upstream, _, err := gatewayProtocolOpenAIForward(t, route, false, repo, ctx) + require.Error(t, err) + require.GreaterOrEqual(t, repo.turnReads, 2) + require.Nil(t, upstream.lastReq, "a later authoritative rejection must precede transport") + }) + } + } +} + +func TestGatewayProtocolOpenAILegacyPassthroughKeepsWireModel(t *testing.T) { + base, ctx := gatewayProtocolFixture(PlatformOpenAI) + base.account.Platform, base.account.Type = PlatformOpenAI, AccountTypeAPIKey + base.account.Extra = map[string]any{"openai_passthrough": true} + base.account.Credentials["model_mapping"] = map[string]any{"public-model": "upstream-model"} + repo := &gatewayProtocolOpenAIRepo{gatewayProtocolAdmissionRepo: base} + result, upstream, _, err := gatewayProtocolOpenAIForward(t, "responses", false, repo, ctx) + require.NoError(t, err) + require.Equal(t, "public-model", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, "public-model", result.Model) + require.Empty(t, result.UpstreamModel) +} + +func TestGatewayProtocolOpenAIResponsesMappedWireModel(t *testing.T) { + for _, scenario := range []struct { + name, route string + stream bool + }{ + {"nonstream", "responses", false}, {"stream", "responses", true}, {"compact", "compact", false}, {"compact-override", "compact", false}, + } { + t.Run(scenario.name, func(t *testing.T) { + base, ctx := gatewayProtocolFixture(PlatformOpenAI) + base.account.Credentials["model_mapping"] = map[string]any{"public-model": "upstream-model"} + wantModel := "upstream-model" + if scenario.name == "compact-override" { + wantModel = "compact-upstream-model" + base.account.Credentials["compact_model_mapping"] = map[string]any{"public-model": wantModel} + } + repo := &gatewayProtocolOpenAIRepo{gatewayProtocolAdmissionRepo: base} + result, upstream, recorder, err := gatewayProtocolOpenAIForward(t, scenario.route, scenario.stream, repo, ctx) + require.NoError(t, err) + require.Equal(t, wantModel, gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, scenario.stream, gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.Equal(t, "hello", gjson.GetBytes(upstream.lastBody, "input").String()) + wantPath := "/tenant/v1/responses" + if scenario.route == "compact" { + wantPath += "/compact" + } + require.Equal(t, wantPath, upstream.lastReq.URL.Path) + require.Equal(t, "public-model", result.Model) + require.Equal(t, wantModel, result.UpstreamModel) + require.Empty(t, result.BillingModel, "retain existing passthrough public-model billing") + require.Contains(t, recorder.Body.String(), "public-model") + require.Equal(t, 10, result.Usage.InputTokens) + }) + } +} diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index 538e733a9e12..f37b760c1ef6 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -446,6 +446,13 @@ func (s *OpenAIGatewayService) forwardAsChatCompletions( } // 5. Get access token + if account.gatewayProtocolSource != nil { + latest, err := s.admitOpenAITurn(ctx, c, account, upstreamModel, responsesBody) + if err != nil { + return nil, err + } + account = latest + } token, _, err := s.GetAccessToken(ctx, account) if err != nil { return nil, fmt.Errorf("get access token: %w", err) diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 7750ef2f1600..82519128e781 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -426,6 +426,13 @@ func (s *OpenAIGatewayService) forwardAsAnthropic( } // 5. Get access token + if account.gatewayProtocolSource != nil { + latest, err := s.admitOpenAITurn(ctx, c, account, upstreamModel, responsesBody) + if err != nil { + return nil, err + } + account = latest + } token, _, err := s.getRequestCredential(ctx, c, account) if err != nil { return nil, fmt.Errorf("get access token: %w", err) diff --git a/backend/internal/service/openai_gateway_passthrough.go b/backend/internal/service/openai_gateway_passthrough.go index 3cdd40194230..a971cd0fcb6d 100644 --- a/backend/internal/service/openai_gateway_passthrough.go +++ b/backend/internal/service/openai_gateway_passthrough.go @@ -140,6 +140,20 @@ func (s *OpenAIGatewayService) forwardOpenAIPassthrough( ctx = withOpenAITransportMode(ctx, "passthrough") requestedModel := reqModel upstreamPassthroughModel := "" + // Gateway accounts retain explicit portable mappings even though their + // transport uses passthrough. Legacy passthrough keeps its original contract. + if account != nil && account.gatewayProtocolSource != nil { + mappedModel := account.GetMappedModel(reqModel) + if mappedModel != "" && mappedModel != reqModel { + nextBody, setErr := sjson.SetBytes(body, "model", mappedModel) + if setErr != nil { + return nil, fmt.Errorf("set gateway passthrough model: %w", setErr) + } + body = nextBody + upstreamPassthroughModel = mappedModel + attemptImageIntentInvalidated = true + } + } if isOpenAIResponsesCompactPath(c) && !account.IsCopilotSDKEnabled() { compactMappedModel := s.resolveOpenAICompactFallbackModel(account, reqModel) if compactMappedModel != "" && compactMappedModel != reqModel { diff --git a/backend/internal/service/openai_turn_admission.go b/backend/internal/service/openai_turn_admission.go index b0132e0a4459..9818a6ee69de 100644 --- a/backend/internal/service/openai_turn_admission.go +++ b/backend/internal/service/openai_turn_admission.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" "github.com/gin-gonic/gin" ) @@ -258,7 +259,12 @@ func (s *OpenAIGatewayService) latestOpenAITurnAccountForGroup( if selected == nil { return nil, denyOpenAITurn("account_unavailable") } - if !selected.IsOpenAI() && (s.schedulerSnapshot == nil || s.schedulerSnapshot.localSnapshotReader == nil) { + gatewayView := selected.gatewayProtocolSource != nil + gatewayModel := selected.gatewayProtocolModel + if gatewayView { + selected = selected.gatewayProtocolSource + } + if !gatewayView && !selected.IsOpenAI() && (s.schedulerSnapshot == nil || s.schedulerSnapshot.localSnapshotReader == nil) { // This patch changes OpenAI Responses admission only, not other // providers which share the generic forwarding implementation. return selected, nil @@ -277,7 +283,7 @@ func (s *OpenAIGatewayService) latestOpenAITurnAccountForGroup( } authoritativeRead = true } else { - if ttl := s.openAITurnAdmissionCacheTTL(); ttl > 0 { + if ttl := s.openAITurnAdmissionCacheTTL(); ttl > 0 && !gatewayView { if cached, cachedParent, ok := s.openAITurnAdmissionCache.load(selected.ID, ttl); ok { latest, parent, authoritativeRead = cached, cachedParent, true } @@ -285,7 +291,7 @@ func (s *OpenAIGatewayService) latestOpenAITurnAccountForGroup( if s.accountRepo != nil { reader, ok := s.accountRepo.(OpenAITurnAdmissionReader) if !ok { - if s.requireLatestTurnAdmission { + if s.requireLatestTurnAdmission || gatewayView { return nil, denyOpenAITurn("latest_state_unavailable") } // Small direct-call fixtures may provide a repository for @@ -304,11 +310,11 @@ func (s *OpenAIGatewayService) latestOpenAITurnAccountForGroup( if err != nil || latest == nil || latest.ID != selected.ID { return nil, denyOpenAITurn("latest_state_unavailable") } - if s.openAITurnAdmissionCacheTTL() > 0 { + if s.openAITurnAdmissionCacheTTL() > 0 && !gatewayView { s.openAITurnAdmissionCache.store(latest, parent) } } - } else if s.requireLatestTurnAdmission { + } else if s.requireLatestTurnAdmission || gatewayView { // Real services are constructed with this flag. Small unit-test services // can exercise the pure supplied-account predicate without a database. return nil, denyOpenAITurn("latest_state_unavailable") @@ -336,6 +342,31 @@ func (s *OpenAIGatewayService) latestOpenAITurnAccountForGroup( } } } + if gatewayView { + // Keep the real turn reader and all common admission guards. Validate + // both uncached snapshots against the original neutral identity, then + // rebuild a view; never make the stored gateway schedulable. + reader, ok := s.accountRepo.(GatewayRequestAccountReader) + if !ok || !authoritativeRead { + return nil, denyOpenAITurn("latest_state_unavailable") + } + group, _ := ctx.Value(ctxkey.Group).(*Group) + if group == nil || (enforceGroup && group.ID != groupID) { + return nil, denyOpenAITurn("group_membership_changed") + } + current, liveGroup, err := reader.GatewayRequestAccount(ctx, selected.ID, group.ID) + if err != nil { + return nil, &OpenAITurnAdmissionError{Reason: "latest_state_unavailable", cause: err} + } + if _, err := gatewayProtocolAccountFromSnapshot(ctx, selected, current, liveGroup, "openai", gatewayModel); err != nil { + return nil, &OpenAITurnAdmissionError{Reason: "account_ineligible", cause: err} + } + view, err := gatewayProtocolAccountFromSnapshot(ctx, selected, latest, liveGroup, "openai", gatewayModel) + if err != nil { + return nil, &OpenAITurnAdmissionError{Reason: "account_ineligible", cause: err} + } + latest = view + } if authoritativeRead && !latest.IsSchedulable() { return nil, denyOpenAITurn("account_ineligible") } @@ -416,7 +447,11 @@ func (s *OpenAIGatewayService) admitOpenAITurnWithGroup( return nil, &OpenAITurnAdmissionError{Reason: excelOAuthRouteErrorCode, cause: err} } // 会话中途被收窄了分组内的可用模型、或后续 turn 换成了不允许的模型时,要求客户端重连重新选号。 - if enforceGroup && !latest.IsModelAllowedInGroup(&groupID, outboundModel) { + groupModel := outboundModel + if latest.gatewayProtocolSource != nil { + groupModel = latest.gatewayProtocolModel + } + if enforceGroup && !latest.IsModelAllowedInGroup(&groupID, groupModel) { return nil, denyOpenAITurn("model_not_allowed_in_group") } if !latest.IsOpenAI() { From 9349428ee4948ecbb410ef2d79ae099d3ad7883a Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 11:45:56 +0800 Subject: [PATCH 13/26] feat: select explicitly bound gateways for native Anthropic messages --- .../workflows/issue959-gateway-regression.yml | 9 +- backend/internal/handler/gateway_handler.go | 1 + .../gateway_messages_selection_test.go | 165 ++++++++++++++++++ .../repository/gateway_request_admission.go | 5 + .../repository/gateway_request_candidates.go | 56 ++++++ ...way_request_candidates_integration_test.go | 42 +++++ backend/internal/service/account.go | 1 + .../service/gateway_anthropic_passthrough.go | 18 ++ .../service/gateway_messages_selection.go | 98 +++++++++++ .../gateway_messages_selection_test.go | 105 +++++++++++ .../internal/service/gateway_scheduling.go | 38 +++- backend/internal/service/gateway_service.go | 3 + 12 files changed, 536 insertions(+), 5 deletions(-) create mode 100644 backend/internal/handler/gateway_messages_selection_test.go create mode 100644 backend/internal/repository/gateway_request_candidates.go create mode 100644 backend/internal/repository/gateway_request_candidates_integration_test.go create mode 100644 backend/internal/service/gateway_messages_selection.go create mode 100644 backend/internal/service/gateway_messages_selection_test.go diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index a4b9cb2a4a5b..67e2a888ebcc 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -13,6 +13,8 @@ on: - 'backend/internal/repository/group_repo.go' - 'backend/internal/repository/gateway_account*' - 'backend/internal/repository/gateway_request_admission*' + - 'backend/internal/repository/gateway_request_candidates*' + - 'backend/internal/handler/gateway_messages_selection_test.go' - 'backend/internal/repository/oauth_degradation_group_bindings*' - 'backend/internal/repository/procurement_cost_snapshot*' - 'backend/internal/repository/profit_operations.go' @@ -95,6 +97,10 @@ jobs: grep -F -- '--- PASS: TestGatewayProtocolOpenAIRejectsFinalAuthorityChanges' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolOpenAIResponsesMappedWireModel' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolOpenAILegacyPassthroughKeepsWireModel' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidatesStayRequestScoped' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidateSourceRefreshesAfterWarmSnapshot' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidateReadFailurePreservesLegacy' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolMessagesHandlerSchedulerToUsage' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementUpdateRequiresAtomicCapability' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementRepositoryBindingGuard' ../evidence/unit-race.log @@ -109,7 +115,7 @@ jobs: run: | set -euo pipefail go test -race -tags=integration ./internal/repository \ - -run '^Test((ConcurrencyCacheSuite|AccountRepoSuite)$|GatewayAtomicUpdate)/^(TestGateway(TargetsShareAccountConcurrency|ManagementAtomicMembershipAndOAuthExclusion|RequestAdmissionReloadsGroupMembershipAndStatus)|admin|account-service|bulk)$' \ + -run '^Test((ConcurrencyCacheSuite|AccountRepoSuite)$|GatewayAtomicUpdate)/^(TestGateway(TargetsShareAccountConcurrency|ManagementAtomicMembershipAndOAuthExclusion|RequestAdmissionReloadsGroupMembershipAndStatus|RequestCandidatesRequireLiveExplicitAnthropicGroup)|admin|account-service|bulk)$' \ -count=1 -v -timeout=10m 2>&1 | tee ../evidence/concurrency-redis.log if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/concurrency-redis.log; then exit 1 @@ -117,6 +123,7 @@ jobs: grep -F -- '--- PASS: TestConcurrencyCacheSuite/TestGatewayTargetsShareAccountConcurrency' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayManagementAtomicMembershipAndOAuthExclusion' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayRequestAdmissionReloadsGroupMembershipAndStatus' ../evidence/concurrency-redis.log + grep -F -- '--- PASS: TestAccountRepoSuite/TestGatewayRequestCandidatesRequireLiveExplicitAnthropicGroup' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestGatewayAtomicUpdateOAuthInterleaving' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestGatewayAtomicUpdateRollbackAfterStagedFields' ../evidence/concurrency-redis.log grep -F -- '--- PASS: TestGatewayAtomicUpdateSuccessfulCommit' ../evidence/concurrency-redis.log diff --git a/backend/internal/handler/gateway_handler.go b/backend/internal/handler/gateway_handler.go index 9c7ddd4b5100..bbbf8dba1d03 100644 --- a/backend/internal/handler/gateway_handler.go +++ b/backend/internal/handler/gateway_handler.go @@ -229,6 +229,7 @@ func (h *GatewayHandler) Messages(c *gin.Context) { h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "Model is not supported by composite groups") return } + c.Request = c.Request.WithContext(service.WithGatewayMessagesSelection(c.Request.Context(), reqModel)) if rejectSystemOneOnlyPlatform(c, apiKey, h.errorResponse) { return } diff --git a/backend/internal/handler/gateway_messages_selection_test.go b/backend/internal/handler/gateway_messages_selection_test.go new file mode 100644 index 000000000000..3b0097bc6729 --- /dev/null +++ b/backend/internal/handler/gateway_messages_selection_test.go @@ -0,0 +1,165 @@ +//go:build unit + +package handler + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/repository" + middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +type gatewayMessagesHandlerRepo struct { + service.AccountRepository + account *service.Account + group *service.Group + queries int + reads int +} + +func (r *gatewayMessagesHandlerRepo) ListGatewayRequestCandidates(context.Context, int64, string) ([]service.Account, *service.Group, error) { + r.queries++ + return []service.Account{*r.account}, r.group, nil +} + +func (r *gatewayMessagesHandlerRepo) GatewayRequestAccount(context.Context, int64, int64) (*service.Account, *service.Group, error) { + r.reads++ + return r.account, r.group, nil +} + +type gatewayMessagesSlotCache struct { + fakeConcurrencyCache + id int64 + limit int + active int + releases int + before func() +} + +func (s *gatewayMessagesSlotCache) AcquireAccountSlot(_ context.Context, id int64, limit int, _ string) (bool, error) { + s.id, s.limit = id, limit + s.active++ + if s.before != nil { + s.before() + } + return true, nil +} + +func (s *gatewayMessagesSlotCache) ReleaseAccountSlot(context.Context, int64, string) error { + s.active-- + s.releases++ + return nil +} + +// These are real handler -> scheduler -> slot -> production HTTP adapter -> +// synthetic peer -> usage sink regressions, not direct Forward helper calls. +func TestGatewayProtocolMessagesHandlerSchedulerToUsage(t *testing.T) { + gin.SetMode(gin.TestMode) + for _, batch := range []bool{false, true} { + for _, bound := range []bool{false, true} { + for _, revoke := range []bool{false, true} { + name := "fallback" + if batch { + name = "load-aware" + } + if bound { + name += "/sticky" + } + if revoke { + name += "/removed-after-slot" + } + t.Run(name, func(t *testing.T) { + var peerCalls atomic.Int32 + peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + peerCalls.Add(1) + body, err := io.ReadAll(req.Body) + require.NoError(t, err) + require.Equal(t, "/tenant/v1/messages", req.URL.Path) + require.Equal(t, "upstream-claude", gjson.GetBytes(body, "model").String()) + require.Equal(t, "synthetic-gateway-key", req.Header.Get("x-api-key")) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"msg_gateway","type":"message","role":"assistant","model":"upstream-claude","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":7}}`) + })) + defer peer.Close() + cfg := &config.Config{} + cfg.Security.URLAllowlist.AllowPrivateHosts = true + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Gateway.Scheduling.LoadBatchEnabled = batch + groupID := int64(9591) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1} + account := &service.Account{ID: 9592, Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Status: service.StatusActive, Schedulable: true, Concurrency: 2, Priority: 3, + Credentials: map[string]any{"upstream_kind": "new_api", "api_key": "synthetic-gateway-key", "base_url": peer.URL + "/tenant/v1", + "model_mapping": map[string]any{"claude-sonnet-4.5": "upstream-claude"}}, + GroupIDs: []int64{groupID}, AccountGroups: []service.AccountGroup{{AccountID: 9592, GroupID: groupID}}} + repo := &gatewayMessagesHandlerRepo{account: account, group: group} + slots := &gatewayMessagesSlotCache{} + if revoke { + slots.before = func() { account.GroupIDs, account.AccountGroups = nil, nil } + } + concurrency := service.NewConcurrencyService(slots) + cache := &stickyWritebackCache{} + if bound { + cache.accountID = account.ID + } + // Warm shared snapshot is empty: no gateway platform view is cached. + snapshot := service.NewSchedulerSnapshotService(&fakeSchedulerCache{}, nil, nil, nil, nil) + usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 2)} + billing := &compatStreamUsageBillingRepo{} + billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + gw := service.NewGatewayService( + repo, &fakeGroupRepo{group: group}, usage, billing, nil, nil, nil, cache, cfg, + snapshot, concurrency, service.NewBillingService(cfg, nil), nil, nil, nil, repository.NewHTTPUpstream(cfg), + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, + ) + h := &GatewayHandler{gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(concurrency, SSEPingFormatClaude, 0)} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"claude-sonnet-4.5","max_tokens":32,"messages":[{"role":"user","content":"hello"}]}`)) + c.Request.Header.Set("Content-Type", "application/json") + key := &service.APIKey{ID: 9593, UserID: 9594, GroupID: &groupID, Group: group, User: &service.User{ID: 9594, Balance: 100}} + c.Set(string(middleware.ContextKeyAPIKey), key) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9594}) + h.Messages(c) + require.Equal(t, account.ID, slots.id) + require.Equal(t, account.Concurrency, slots.limit) + require.Zero(t, slots.active) + require.Positive(t, slots.releases) + require.Positive(t, repo.reads) + if revoke { + require.Zero(t, peerCalls.Load()) + require.Empty(t, usage.created) + return + } + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Equal(t, int32(1), peerCalls.Load()) + select { + case log := <-usage.created: + require.Equal(t, account.ID, log.AccountID) + require.Equal(t, service.PlatformAnthropic, log.Platform) + require.Equal(t, 12, log.InputTokens) + require.NotNil(t, log.ProcurementCostSnapshot) + require.Equal(t, service.PlatformAnthropic, log.ProcurementCostSnapshot.TargetPlatform) + case <-time.After(3 * time.Second): + t.Fatal("handler did not deliver usage to its sink") + } + require.False(t, account.IsSchedulable()) + }) + } + } + } +} diff --git a/backend/internal/repository/gateway_request_admission.go b/backend/internal/repository/gateway_request_admission.go index 20de24c107c9..a2434a9cd5be 100644 --- a/backend/internal/repository/gateway_request_admission.go +++ b/backend/internal/repository/gateway_request_admission.go @@ -38,6 +38,11 @@ func (r *accountRepository) gatewayRequestAccount(ctx context.Context, accountID if err != nil { return nil, nil, err } + paused, err := performancePaused(ctx, clientFromContext(ctx, r.client), []int64{accountID}) + if err != nil { + return nil, nil, err + } + account.PerformancePaused = paused[accountID] group, err := clientFromContext(ctx, r.client).Group.Get(ctx, groupID) if err != nil { return nil, nil, translatePersistenceError(err, service.ErrGroupNotFound, nil) diff --git a/backend/internal/repository/gateway_request_candidates.go b/backend/internal/repository/gateway_request_candidates.go new file mode 100644 index 000000000000..5489d2122e5d --- /dev/null +++ b/backend/internal/repository/gateway_request_candidates.go @@ -0,0 +1,56 @@ +package repository + +import ( + "context" + "database/sql" + + dbent "github.com/Wei-Shaw/sub2api/ent" + dbaccount "github.com/Wei-Shaw/sub2api/ent/account" + dbaccountgroup "github.com/Wei-Shaw/sub2api/ent/accountgroup" + "github.com/Wei-Shaw/sub2api/internal/service" +) + +var _ service.GatewayRequestCandidateReader = (*accountRepository)(nil) + +// This request-only SELECT never expands the platform bucket queries. It reads +// policy, explicit membership, credentials and runtime state in one SQL snapshot. +func (r *accountRepository) ListGatewayRequestCandidates(ctx context.Context, groupID int64, target string) ([]service.Account, *service.Group, error) { + if groupID <= 0 || target != service.PlatformAnthropic { + return nil, nil, nil + } + tx, err := r.client.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead}) + if err != nil { + return nil, nil, err + } + defer func() { _ = tx.Rollback() }() + reader := &accountRepository{client: tx.Client()} + txctx := dbent.NewTxContext(ctx, tx) + g, err := reader.client.Group.Get(txctx, groupID) + if err != nil { + return nil, nil, translatePersistenceError(err, service.ErrGroupNotFound, nil) + } + group := groupEntityToService(g) + if g.DeletedAt != nil || !group.IsActive() || group.Platform != target || group.RequireOAuthOnly { + return nil, group, nil + } + ids, err := observerAccountQuery(txctx, reader.client.Account.Query()).Where( + dbaccount.PlatformEQ(service.PlatformGateway), dbaccount.TypeEQ(service.AccountTypeGateway), + dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true), + dbaccount.HasAccountGroupsWith(dbaccountgroup.GroupIDEQ(groupID)), + ).Order(dbent.Asc(dbaccount.FieldPriority), dbent.Asc(dbaccount.FieldID)).IDs(txctx) + if err != nil { + return nil, nil, err + } + accounts := make([]service.Account, 0, len(ids)) + for _, id := range ids { + account, _, err := reader.gatewayRequestAccount(txctx, id, groupID) + if err != nil { + return nil, nil, err + } + accounts = append(accounts, *account) + } + if err := tx.Commit(); err != nil { + return nil, nil, err + } + return accounts, group, nil +} diff --git a/backend/internal/repository/gateway_request_candidates_integration_test.go b/backend/internal/repository/gateway_request_candidates_integration_test.go new file mode 100644 index 000000000000..58da481e379d --- /dev/null +++ b/backend/internal/repository/gateway_request_candidates_integration_test.go @@ -0,0 +1,42 @@ +//go:build integration + +package repository + +import "github.com/Wei-Shaw/sub2api/internal/service" + +func (s *AccountRepoSuite) TestGatewayRequestCandidatesRequireLiveExplicitAnthropicGroup() { + group, err := s.client.Group.Create().SetName("gateway-candidates").SetPlatform(service.PlatformAnthropic).Save(s.ctx) + s.Require().NoError(err) + a := &service.Account{Name: "gateway-candidate", Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Status: service.StatusActive, Concurrency: 2, + Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://gateway.example", "api_key": "synthetic-only"}} + s.Require().NoError(s.repo.CreateWithAccountGroups(s.ctx, a, []service.AccountGroup{{GroupID: group.ID}})) + _, err = s.client.Account.UpdateOneID(a.ID).SetSchedulable(true).Save(s.ctx) + s.Require().NoError(err) + accounts, live, err := s.repo.ListGatewayRequestCandidates(s.ctx, group.ID, service.PlatformAnthropic) + s.Require().NoError(err) + s.Require().Len(accounts, 1) + s.Equal(a.ID, accounts[0].ID) + s.Equal(service.PlatformGateway, accounts[0].Platform) + s.Equal([]int64{group.ID}, accounts[0].GroupIDs) + s.False(accounts[0].IsSchedulable(), "SELECT returns a neutral account, never a globally eligible view") + s.Equal(service.PlatformAnthropic, live.Platform) + legacyBucket, err := s.repo.ListSchedulableByGroupIDAndPlatform(s.ctx, group.ID, service.PlatformAnthropic) + s.Require().NoError(err) + s.Empty(legacyBucket, "shared snapshot queries still exclude gateway") + for _, target := range []string{service.PlatformOpenAI, service.PlatformGemini, service.PlatformAntigravity, service.PlatformGrok, service.PlatformKimi, service.PlatformComposite} { + accounts, _, err = s.repo.ListGatewayRequestCandidates(s.ctx, group.ID, target) + s.Require().NoError(err) + s.Empty(accounts) + } + s.Require().NoError(s.repo.BindGroups(s.ctx, a.ID, nil)) + accounts, _, err = s.repo.ListGatewayRequestCandidates(s.ctx, group.ID, service.PlatformAnthropic) + s.Require().NoError(err) + s.Empty(accounts, "warm prior reads cannot retain removed membership") + _, err = s.client.Group.UpdateOneID(group.ID).SetRequireOauthOnly(true).Save(s.ctx) + s.Require().NoError(err) + accounts, live, err = s.repo.ListGatewayRequestCandidates(s.ctx, group.ID, service.PlatformAnthropic) + s.Require().NoError(err) + s.Empty(accounts) + s.True(live.RequireOAuthOnly) +} diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 18cbbfe6880b..3e730d49dc5c 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -83,6 +83,7 @@ type Account struct { // admission compares the neutral gateway identity before rebuilding a view. gatewayProtocolSource *Account gatewayProtocolModel string + gatewayMessagesView *Account // model_mapping 热路径缓存(非持久化字段) modelMappingCache map[string]string diff --git a/backend/internal/service/gateway_anthropic_passthrough.go b/backend/internal/service/gateway_anthropic_passthrough.go index 5ef43a3ef008..eceeb56b1c08 100644 --- a/backend/internal/service/gateway_anthropic_passthrough.go +++ b/backend/internal/service/gateway_anthropic_passthrough.go @@ -96,6 +96,24 @@ func (s *GatewayService) forwardAnthropicAPIKeyPassthroughWithInput( var resp *http.Response retryStart := time.Now() for attempt := 1; attempt <= maxRetryAttempts; attempt++ { + if account.gatewayProtocolSource != nil { + latest, err := s.gatewayProtocolAccount(ctx, account.gatewayProtocolSource, "anthropic", account.gatewayProtocolModel) + if err != nil { + return nil, err + } + if openAITurnRouteFingerprint(latest) != openAITurnRouteFingerprint(account) { + return nil, ErrGatewayAccountIdentity + } + account = latest + token, _, err = s.GetAccessToken(ctx, account) + if err != nil { + return nil, err + } + proxyURL = "" + if account.ProxyID != nil && account.Proxy != nil { + proxyURL = account.Proxy.URL() + } + } upstreamCtx, releaseUpstreamCtx := detachStreamUpstreamContext(ctx, input.RequestStream) upstreamReq, wireBody, err := s.buildUpstreamRequestAnthropicAPIKeyPassthrough(upstreamCtx, c, account, input.Body, token) releaseUpstreamCtx() diff --git a/backend/internal/service/gateway_messages_selection.go b/backend/internal/service/gateway_messages_selection.go new file mode 100644 index 000000000000..ee45f17b6647 --- /dev/null +++ b/backend/internal/service/gateway_messages_selection.go @@ -0,0 +1,98 @@ +package service + +import ( + "context" + "log/slog" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" +) + +type gatewayMessagesSelectionKey struct{} + +// WithGatewayMessagesSelection enables only the native Messages handler's +// concrete Anthropic selection. Other protocols and composite selection remain +// closed until their scheduler/forward/usage contracts are covered together. +func WithGatewayMessagesSelection(ctx context.Context, model string) context.Context { + return context.WithValue(ctx, gatewayMessagesSelectionKey{}, model) +} + +// GatewayRequestCandidateReader is deliberately separate from shared snapshot +// queries: a neutral account must never enter a platform bucket or group zero. +// Membership and group policy must come from the same primary SQL snapshot. +type GatewayRequestCandidateReader interface { + ListGatewayRequestCandidates(context.Context, int64, string) ([]Account, *Group, error) +} + +func gatewayMessagesSelectionModel(ctx context.Context, groupID *int64, platform string) (string, bool) { + model, _ := ctx.Value(gatewayMessagesSelectionKey{}).(string) + group, _ := ctx.Value(ctxkey.Group).(*Group) + if model == "" || groupID == nil || *groupID <= 0 || platform != PlatformAnthropic || + group == nil || group.ID != *groupID || group.Platform != PlatformAnthropic || !group.IsActive() || group.RequireOAuthOnly { + return "", false + } + if target, ok := ResolvedTargetPlatformFromContext(ctx); ok && target != PlatformAnthropic { + return "", false + } + if forced, _ := ctx.Value(ctxkey.ForcePlatform).(string); forced != "" && forced != PlatformAnthropic { + return "", false + } + return model, true +} + +func (s *GatewayService) appendGatewayMessagesCandidates(ctx context.Context, groupID *int64, platform string, accounts []Account) ([]Account, error) { + model, enabled := gatewayMessagesSelectionModel(ctx, groupID, platform) + if !enabled || (s.schedulerSnapshot != nil && s.schedulerSnapshot.localSnapshotReader != nil) { + return accounts, nil + } + reader, ok := s.accountRepo.(GatewayRequestCandidateReader) + if !ok { + return accounts, nil + } + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + candidates, group, err := reader.ListGatewayRequestCandidates(ctx, *groupID, platform) + if err != nil { + slog.Warn("gateway candidate read unavailable", "group_id", *groupID, "error", err) + return accounts, nil + } + // An invalidated group contributes no gateway candidates. Legacy candidates + // retain their existing scheduler policy, independent of this capability. + if group == nil || group.Platform != PlatformAnthropic { + return accounts, nil + } + seen := make(map[int64]bool, len(accounts)) + accounts = append([]Account(nil), accounts...) + for i := range accounts { + seen[accounts[i].ID] = true + } + for i := range candidates { + candidate := candidates[i] + view, err := gatewayProtocolAccountFromSnapshot(ctx, &candidate, &candidate, group, "anthropic", model) + if err != nil || seen[candidate.ID] { + continue + } + candidate.gatewayMessagesView = view + accounts = append(accounts, candidate) + seen[candidate.ID] = true + } + return accounts, nil +} + +func (s *GatewayService) refreshGatewayMessagesSelection(ctx context.Context, account *Account) (*Account, error) { + group, _ := ctx.Value(ctxkey.Group).(*Group) + if group == nil { + return nil, ErrGatewayProtocolsPending + } + model, enabled := gatewayMessagesSelectionModel(ctx, &group.ID, PlatformAnthropic) + if !enabled || (s.schedulerSnapshot != nil && s.schedulerSnapshot.localSnapshotReader != nil) { + return nil, ErrGatewayProtocolsPending + } + view, err := s.gatewayProtocolAccount(ctx, account, "anthropic", model) + if err != nil { + return nil, err + } + neutral := *view.gatewayProtocolSource + neutral.gatewayMessagesView = view + return &neutral, nil +} diff --git a/backend/internal/service/gateway_messages_selection_test.go b/backend/internal/service/gateway_messages_selection_test.go new file mode 100644 index 000000000000..3f6eb4fbddb9 --- /dev/null +++ b/backend/internal/service/gateway_messages_selection_test.go @@ -0,0 +1,105 @@ +//go:build unit + +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" + "github.com/stretchr/testify/require" +) + +type gatewayMessagesCandidateRepo struct { + *gatewayProtocolAdmissionRepo + queries int + err error +} + +func (r *gatewayMessagesCandidateRepo) ListGatewayRequestCandidates(context.Context, int64, string) ([]Account, *Group, error) { + r.queries++ + return []Account{*r.account}, r.group, r.err +} + +func TestGatewayProtocolMessagesCandidatesStayRequestScoped(t *testing.T) { + for _, scenario := range []string{"eligible", "unbound", "oauth-only", "other-target", "composite", "disabled", "paused", "cooling", "429", "401", "low-balance", "wrong-model", "unscoped"} { + t.Run(scenario, func(t *testing.T) { + base, ctx := gatewayProtocolFixture(PlatformAnthropic) + repo := &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base} + ctx = WithGatewayMessagesSelection(ctx, "public-model") + switch scenario { + case "unbound": + repo.account.GroupIDs, repo.account.AccountGroups = nil, nil + case "oauth-only": + repo.group.RequireOAuthOnly = true + case "other-target": + ctx = WithResolvedTargetPlatform(ctx, PlatformGemini) + case "composite": + repo.group.Platform = PlatformComposite + ctx = WithResolvedTargetPlatform(ctx, PlatformAnthropic) + case "disabled": + repo.account.Status = StatusDisabled + case "paused": + repo.account.PerformancePaused = true + case "cooling": + until := time.Now().Add(time.Hour) + repo.account.TempUnschedulableUntil = &until + case "429": + until := time.Now().Add(time.Hour) + repo.account.RateLimitResetAt = &until + case "401", "low-balance": + repo.account.Status = StatusError + case "wrong-model": + repo.account.Credentials["model_mapping"] = map[string]any{"other": "other"} + case "unscoped": + ctx = context.WithValue(context.Background(), ctxkey.Group, repo.group) + } + svc := &GatewayService{accountRepo: repo} + accounts, err := svc.appendGatewayMessagesCandidates(ctx, &repo.group.ID, PlatformAnthropic, nil) + require.NoError(t, err) + if scenario != "eligible" { + require.Empty(t, accounts) + return + } + require.Len(t, accounts, 1) + require.Equal(t, repo.account.ID, accounts[0].ID) + require.True(t, svc.isAccountSchedulableForSelection(&accounts[0])) + require.True(t, svc.isAccountAllowedForPlatform(&accounts[0], PlatformAnthropic, true)) + require.False(t, accounts[0].IsSchedulable(), "neutral identity never becomes globally schedulable") + require.Nil(t, repo.account.gatewayMessagesView, "shared repository snapshot stays untouched") + repo.account.Status = StatusDisabled + _, err = svc.hydrateSelectedAccount(ctx, &accounts[0]) + require.Error(t, err, "post-selection hydration must consult fresh authority") + }) + } +} + +func TestGatewayProtocolMessagesCandidateReadFailurePreservesLegacy(t *testing.T) { + base, ctx := gatewayProtocolFixture(PlatformAnthropic) + repo := &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base, err: errors.New("primary unavailable")} + ctx = WithGatewayMessagesSelection(ctx, "public-model") + legacy := Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeAPIKey, Status: StatusActive, Schedulable: true} + svc := &GatewayService{accountRepo: repo} + accounts, err := svc.appendGatewayMessagesCandidates(ctx, &repo.group.ID, PlatformAnthropic, []Account{legacy}) + require.NoError(t, err) + require.Equal(t, []Account{legacy}, accounts) + require.Equal(t, 1, repo.queries) +} + +func TestGatewayProtocolMessagesCandidateSourceRefreshesAfterWarmSnapshot(t *testing.T) { + base, ctx := gatewayProtocolFixture(PlatformAnthropic) + repo := &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base} + ctx = WithGatewayMessagesSelection(ctx, "public-model") + snapshot := NewSchedulerSnapshotService(&snapshotReaderCache{hit: true}, nil, nil, nil, nil) + svc := &GatewayService{accountRepo: repo, schedulerSnapshot: snapshot} + first, _, err := svc.listSchedulableAccounts(ctx, &repo.group.ID, PlatformAnthropic, false) + require.NoError(t, err) + require.Len(t, first, 1) + repo.account.GroupIDs, repo.account.AccountGroups = nil, nil + second, _, err := svc.listSchedulableAccounts(ctx, &repo.group.ID, PlatformAnthropic, false) + require.NoError(t, err) + require.Empty(t, second, "outbox lag cannot retain a revoked candidate") + require.Equal(t, 2, repo.queries) +} diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index e47bf70434c5..32fe43743e3a 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -1019,7 +1019,12 @@ func (s *GatewayService) resolvePlatform(ctx context.Context, groupID *int64, gr return PlatformAnthropic, false, nil } -func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) ([]Account, bool, error) { +func (s *GatewayService) listSchedulableAccounts(ctx context.Context, groupID *int64, platform string, hasForcePlatform bool) (accountsResult []Account, mixedResult bool, resultErr error) { + defer func() { + if resultErr == nil { + accountsResult, resultErr = s.appendGatewayMessagesCandidates(ctx, groupID, platform, accountsResult) + } + }() if s.schedulerSnapshot != nil { accounts, useMixed, err := s.schedulerSnapshot.ListSchedulableAccounts(ctx, groupID, platform, hasForcePlatform) if err == nil { @@ -1157,6 +1162,9 @@ func (s *GatewayService) isAccountAllowedForPlatform(account *Account, platform if account == nil { return false } + if account.IsGateway() { + return account.gatewayMessagesView != nil && platform == PlatformAnthropic + } if useMixed { if account.Platform == platform { return true @@ -1170,6 +1178,9 @@ func (s *GatewayService) isAccountSchedulableForSelection(account *Account) bool if account == nil { return false } + if account.IsGateway() { + return account.gatewayMessagesView != nil && account.gatewayMessagesView.IsSchedulable() + } return account.IsSchedulable() } @@ -1177,6 +1188,9 @@ func (s *GatewayService) isAccountSchedulableForModelSelection(ctx context.Conte if account == nil { return false } + if account.IsGateway() { + return account.gatewayMessagesView != nil && account.gatewayMessagesView.IsSchedulableForModelWithContext(ctx, requestedModel) + } return account.IsSchedulableForModelWithContext(ctx, requestedModel) } @@ -1490,6 +1504,16 @@ func (s *GatewayService) ReleaseAccountSession(ctx context.Context, account *Acc } func (s *GatewayService) getSchedulableAccount(ctx context.Context, accountID int64) (*Account, error) { + if group, _ := ctx.Value(ctxkey.Group).(*Group); group != nil { + if _, enabled := gatewayMessagesSelectionModel(ctx, &group.ID, PlatformAnthropic); enabled && (s.schedulerSnapshot == nil || s.schedulerSnapshot.localSnapshotReader == nil) { + if reader, ok := s.accountRepo.(GatewayRequestAccountReader); ok { + fresh, _, err := reader.GatewayRequestAccount(ctx, accountID, group.ID) + if err == nil && fresh != nil && fresh.gatewayProtocolsPending() { + return s.refreshGatewayMessagesSelection(ctx, fresh) + } + } + } + } var ( account *Account err error @@ -1540,6 +1564,9 @@ func (s *GatewayService) isAccountBlockedBySchedulingThreshold(ctx context.Conte } func (s *GatewayService) hydrateSelectedAccount(ctx context.Context, account *Account) (*Account, error) { + if account != nil && account.gatewayProtocolsPending() { + return s.refreshGatewayMessagesSelection(ctx, account) + } if account == nil || s.schedulerSnapshot == nil { return account, nil } @@ -1917,7 +1944,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context, if clearSticky { _ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), sessionHash) } - if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && account.Platform == platform && (requestedModel == "" || s.isModelSupportedByAccountInGroup(ctx, account, groupID, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) && !s.isStickyAccountUpstreamRestricted(ctx, groupID, account, requestedModel) { + if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && s.isAccountAllowedForPlatform(account, platform, false) && (requestedModel == "" || s.isModelSupportedByAccountInGroup(ctx, account, groupID, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) && !s.isStickyAccountUpstreamRestricted(ctx, groupID, account, requestedModel) { if s.debugModelRoutingEnabled() { logger.LegacyPrintf("service.gateway", "[ModelRoutingDebug] legacy routed sticky hit: group_id=%v model=%s session=%s account=%d", derefGroupID(groupID), requestedModel, shortSessionHash(sessionHash), accountID) } @@ -2039,7 +2066,7 @@ func (s *GatewayService) selectAccountForModelWithPlatform(ctx context.Context, if clearSticky { _ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), sessionHash) } - if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && account.Platform == platform && (requestedModel == "" || s.isModelSupportedByAccountInGroup(ctx, account, groupID, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) { + if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && s.isAccountAllowedForPlatform(account, platform, false) && (requestedModel == "" || s.isModelSupportedByAccountInGroup(ctx, account, groupID, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) { return account, nil } } @@ -2314,7 +2341,7 @@ func (s *GatewayService) selectAccountWithMixedScheduling(ctx context.Context, g _ = s.cache.DeleteSessionAccountID(ctx, derefGroupID(groupID), sessionHash) } if !clearSticky && s.isGatewayAccountProfitEligible(ctx, account) && s.isAccountInGroup(account, groupID) && (requestedModel == "" || s.isModelSupportedByAccountInGroup(ctx, account, groupID, requestedModel)) && s.isAccountSchedulableForModelSelection(ctx, account, requestedModel) && s.isAccountSchedulableForQuota(account) && s.isAccountSchedulableForWindowCost(ctx, account, true) && s.isAccountSchedulableForRPM(ctx, account, true) && !s.isStickyAccountUpstreamRestricted(ctx, groupID, account, requestedModel) { - if account.Platform == nativePlatform || (account.Platform == PlatformAntigravity && account.IsMixedSchedulingEnabled()) { + if s.isAccountAllowedForPlatform(account, nativePlatform, true) { return account, nil } } @@ -2573,6 +2600,9 @@ func isPlatformFilteredForSelection(acc *Account, platform string, allowMixedSch if acc == nil { return true } + if acc.IsGateway() && acc.gatewayMessagesView != nil { + return platform != PlatformAnthropic + } if allowMixedScheduling { if acc.Platform == PlatformAntigravity { return !acc.IsMixedSchedulingEnabled() diff --git a/backend/internal/service/gateway_service.go b/backend/internal/service/gateway_service.go index e3ca35f72612..6598e7374ed7 100644 --- a/backend/internal/service/gateway_service.go +++ b/backend/internal/service/gateway_service.go @@ -629,6 +629,9 @@ func shouldClearStickySession(account *Account, requestedModel string) bool { if account == nil { return false } + if account.IsGateway() && account.gatewayMessagesView != nil { + account = account.gatewayMessagesView + } if !account.IsSchedulable() { return true } From 39aeef69c79b4dce246bbc38fa2e34bb944e6f07 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 11:49:24 +0800 Subject: [PATCH 14/26] fix: normalize gateway Anthropic URL and bridge SSE fixture --- .../service/gateway_protocol_admission.go | 2 +- .../gateway_protocol_admission_test.go | 2 +- .../service/gateway_protocol_forward_test.go | 25 +++++++++++++++++++ .../gateway_protocol_openai_admission_test.go | 9 ++++++- 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/gateway_protocol_admission.go b/backend/internal/service/gateway_protocol_admission.go index 793d624559e3..c72cfef2b9e5 100644 --- a/backend/internal/service/gateway_protocol_admission.go +++ b/backend/internal/service/gateway_protocol_admission.go @@ -191,7 +191,7 @@ func gatewayProtocolAccountFromSnapshot(ctx context.Context, selected, current * // Only normalize a terminal protocol version. Tenant prefixes stay intact; // native builders append the protocol's own /v1 or /v1beta exactly once. base := strings.TrimSuffix(strings.TrimRight(view.GetCredential("base_url"), "/"), "/v1beta") - if family == domain.PlatformGatewayGemini { + if family == domain.PlatformGatewayGemini || family == domain.PlatformGatewayAnthropic { base = strings.TrimSuffix(base, "/v1") } view.Credentials["base_url"] = base diff --git a/backend/internal/service/gateway_protocol_admission_test.go b/backend/internal/service/gateway_protocol_admission_test.go index 207b81082c20..c3e55f7f758a 100644 --- a/backend/internal/service/gateway_protocol_admission_test.go +++ b/backend/internal/service/gateway_protocol_admission_test.go @@ -53,7 +53,7 @@ func TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity(t *testing.T) { require.Equal(t, AccountTypeAPIKey, view.Type) require.Equal(t, "synthetic-only", view.GetCredential("api_key")) wantBase := "https://gateway.example/tenant/v1" - if family == domain.PlatformGatewayGemini { + if family == domain.PlatformGatewayGemini || family == domain.PlatformGatewayAnthropic { wantBase = "https://gateway.example/tenant" } require.Equal(t, wantBase, view.GetCredential("base_url")) diff --git a/backend/internal/service/gateway_protocol_forward_test.go b/backend/internal/service/gateway_protocol_forward_test.go index 9c4faca4142c..d60c06ba4655 100644 --- a/backend/internal/service/gateway_protocol_forward_test.go +++ b/backend/internal/service/gateway_protocol_forward_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" @@ -33,6 +34,30 @@ func (u *gatewayProtocolTransport) DoWithTLS(req *http.Request, proxy string, id return u.Do(req, proxy, id, concurrency) } +func TestGatewayProtocolAnthropicBaseVersionsReachNativeBuilder(t *testing.T) { + for _, target := range []string{PlatformAnthropic, PlatformAntigravity} { + for _, prefix := range []string{"", "/tenant"} { + for _, suffix := range []string{"", "/v1", "/v1/", "/v1beta"} { + t.Run(target+prefix+suffix, func(t *testing.T) { + repo, ctx := gatewayProtocolFixture(target) + base := "https://gateway.example" + prefix + suffix + repo.account.Credentials["base_url"] = base + view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayAnthropic, "public-model") + require.NoError(t, err) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + svc := &GatewayService{cfg: rawChatCompletionsTestConfig()} + req, _, err := svc.buildUpstreamRequestAnthropicAPIKeyPassthrough(ctx, c, view, []byte(`{"model":"public-model","messages":[]}`), "synthetic-only") + require.NoError(t, err) + require.Equal(t, prefix+"/v1/messages", req.URL.Path) + require.Equal(t, "gateway.example", req.URL.Host) + require.Equal(t, base, repo.account.GetCredential("base_url"), "stored site and tenant prefix stay intact") + }) + } + } + } +} + func TestGatewayProtocolForwardUsesNativeBuildersAndSharedIdentity(t *testing.T) { for _, route := range []string{"anthropic", "openai", "gemini", "antigravity-messages", "antigravity-gemini"} { t.Run(route, func(t *testing.T) { diff --git a/backend/internal/service/gateway_protocol_openai_admission_test.go b/backend/internal/service/gateway_protocol_openai_admission_test.go index f5e51ee3bafd..9a7d3c2effe2 100644 --- a/backend/internal/service/gateway_protocol_openai_admission_test.go +++ b/backend/internal/service/gateway_protocol_openai_admission_test.go @@ -55,7 +55,9 @@ func gatewayProtocolOpenAIForward(t *testing.T, route string, stream bool, repo } content := `{"id":"resp_fixture","object":"response","status":"completed","model":"upstream-model","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":10,"output_tokens":2,"total_tokens":12}}` contentType := "application/json" - if stream { + // Chat/Messages bridges always request upstream Responses SSE, including + // buffered downstream clients. Their fixture must supply a terminal event. + if stream || route == "chat" || route == "messages" { contentType = "text/event-stream" content = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"OK\"}\n\ndata: {\"type\":\"response.completed\",\"response\":" + content + "}\n\ndata: [DONE]\n\n" } @@ -103,6 +105,11 @@ func TestGatewayProtocolOpenAIAuthoritativeAdmission(t *testing.T) { require.GreaterOrEqual(t, repo.turnReads, 2, "initial and actual-send admission must both read authority") require.NotNil(t, upstream.lastReq) require.Equal(t, "upstream-model", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, route != "responses", gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.False(t, result.Stream, "buffered downstream stays buffered while bridges consume upstream SSE") + require.Equal(t, "public-model", result.Model) + require.Equal(t, "upstream-model", result.UpstreamModel) + require.Equal(t, 10, result.Usage.InputTokens) require.Equal(t, int64(959), upstream.accountID) require.Equal(t, 2, upstream.concurrency) require.Equal(t, "http://proxy.invalid:8080", upstream.proxyURL) From 63aa16563d8a2b4779c5f99ac88210dcf5bee40d Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 11:49:24 +0800 Subject: [PATCH 15/26] fix: normalize gateway Anthropic URL and bridge SSE fixture (cherry picked from commit 39aeef69c79b4dce246bbc38fa2e34bb944e6f07) --- .../service/gateway_protocol_admission.go | 2 +- .../gateway_protocol_admission_test.go | 2 +- .../service/gateway_protocol_forward_test.go | 25 +++++++++++++++++++ .../gateway_protocol_openai_admission_test.go | 9 ++++++- 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/gateway_protocol_admission.go b/backend/internal/service/gateway_protocol_admission.go index 793d624559e3..c72cfef2b9e5 100644 --- a/backend/internal/service/gateway_protocol_admission.go +++ b/backend/internal/service/gateway_protocol_admission.go @@ -191,7 +191,7 @@ func gatewayProtocolAccountFromSnapshot(ctx context.Context, selected, current * // Only normalize a terminal protocol version. Tenant prefixes stay intact; // native builders append the protocol's own /v1 or /v1beta exactly once. base := strings.TrimSuffix(strings.TrimRight(view.GetCredential("base_url"), "/"), "/v1beta") - if family == domain.PlatformGatewayGemini { + if family == domain.PlatformGatewayGemini || family == domain.PlatformGatewayAnthropic { base = strings.TrimSuffix(base, "/v1") } view.Credentials["base_url"] = base diff --git a/backend/internal/service/gateway_protocol_admission_test.go b/backend/internal/service/gateway_protocol_admission_test.go index 207b81082c20..c3e55f7f758a 100644 --- a/backend/internal/service/gateway_protocol_admission_test.go +++ b/backend/internal/service/gateway_protocol_admission_test.go @@ -53,7 +53,7 @@ func TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity(t *testing.T) { require.Equal(t, AccountTypeAPIKey, view.Type) require.Equal(t, "synthetic-only", view.GetCredential("api_key")) wantBase := "https://gateway.example/tenant/v1" - if family == domain.PlatformGatewayGemini { + if family == domain.PlatformGatewayGemini || family == domain.PlatformGatewayAnthropic { wantBase = "https://gateway.example/tenant" } require.Equal(t, wantBase, view.GetCredential("base_url")) diff --git a/backend/internal/service/gateway_protocol_forward_test.go b/backend/internal/service/gateway_protocol_forward_test.go index 9c4faca4142c..d60c06ba4655 100644 --- a/backend/internal/service/gateway_protocol_forward_test.go +++ b/backend/internal/service/gateway_protocol_forward_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/domain" "github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint" "github.com/gin-gonic/gin" "github.com/stretchr/testify/require" @@ -33,6 +34,30 @@ func (u *gatewayProtocolTransport) DoWithTLS(req *http.Request, proxy string, id return u.Do(req, proxy, id, concurrency) } +func TestGatewayProtocolAnthropicBaseVersionsReachNativeBuilder(t *testing.T) { + for _, target := range []string{PlatformAnthropic, PlatformAntigravity} { + for _, prefix := range []string{"", "/tenant"} { + for _, suffix := range []string{"", "/v1", "/v1/", "/v1beta"} { + t.Run(target+prefix+suffix, func(t *testing.T) { + repo, ctx := gatewayProtocolFixture(target) + base := "https://gateway.example" + prefix + suffix + repo.account.Credentials["base_url"] = base + view, err := prepareGatewayProtocolAccount(ctx, repo.account, repo, domain.PlatformGatewayAnthropic, "public-model") + require.NoError(t, err) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil) + svc := &GatewayService{cfg: rawChatCompletionsTestConfig()} + req, _, err := svc.buildUpstreamRequestAnthropicAPIKeyPassthrough(ctx, c, view, []byte(`{"model":"public-model","messages":[]}`), "synthetic-only") + require.NoError(t, err) + require.Equal(t, prefix+"/v1/messages", req.URL.Path) + require.Equal(t, "gateway.example", req.URL.Host) + require.Equal(t, base, repo.account.GetCredential("base_url"), "stored site and tenant prefix stay intact") + }) + } + } + } +} + func TestGatewayProtocolForwardUsesNativeBuildersAndSharedIdentity(t *testing.T) { for _, route := range []string{"anthropic", "openai", "gemini", "antigravity-messages", "antigravity-gemini"} { t.Run(route, func(t *testing.T) { diff --git a/backend/internal/service/gateway_protocol_openai_admission_test.go b/backend/internal/service/gateway_protocol_openai_admission_test.go index f5e51ee3bafd..9a7d3c2effe2 100644 --- a/backend/internal/service/gateway_protocol_openai_admission_test.go +++ b/backend/internal/service/gateway_protocol_openai_admission_test.go @@ -55,7 +55,9 @@ func gatewayProtocolOpenAIForward(t *testing.T, route string, stream bool, repo } content := `{"id":"resp_fixture","object":"response","status":"completed","model":"upstream-model","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"OK"}]}],"usage":{"input_tokens":10,"output_tokens":2,"total_tokens":12}}` contentType := "application/json" - if stream { + // Chat/Messages bridges always request upstream Responses SSE, including + // buffered downstream clients. Their fixture must supply a terminal event. + if stream || route == "chat" || route == "messages" { contentType = "text/event-stream" content = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"OK\"}\n\ndata: {\"type\":\"response.completed\",\"response\":" + content + "}\n\ndata: [DONE]\n\n" } @@ -103,6 +105,11 @@ func TestGatewayProtocolOpenAIAuthoritativeAdmission(t *testing.T) { require.GreaterOrEqual(t, repo.turnReads, 2, "initial and actual-send admission must both read authority") require.NotNil(t, upstream.lastReq) require.Equal(t, "upstream-model", gjson.GetBytes(upstream.lastBody, "model").String()) + require.Equal(t, route != "responses", gjson.GetBytes(upstream.lastBody, "stream").Bool()) + require.False(t, result.Stream, "buffered downstream stays buffered while bridges consume upstream SSE") + require.Equal(t, "public-model", result.Model) + require.Equal(t, "upstream-model", result.UpstreamModel) + require.Equal(t, 10, result.Usage.InputTokens) require.Equal(t, int64(959), upstream.accountID) require.Equal(t, 2, upstream.concurrency) require.Equal(t, "http://proxy.invalid:8080", upstream.proxyURL) From 4394bd965116bc5737d53b89e147dc4e6fd9b9fc Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 12:01:16 +0800 Subject: [PATCH 16/26] fix: retain selection model during gateway channel admission --- .../workflows/issue959-gateway-regression.yml | 1 + .../gateway_messages_selection_test.go | 166 +++++++++++++++++- .../service/gateway_protocol_admission.go | 18 +- 3 files changed, 177 insertions(+), 8 deletions(-) diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index 67e2a888ebcc..16abdd43f83b 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -101,6 +101,7 @@ jobs: grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidateSourceRefreshesAfterWarmSnapshot' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolMessagesCandidateReadFailurePreservesLegacy' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolMessagesHandlerSchedulerToUsage' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolMessagesChannelMappingPreservesBindingModel' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayProtocolAdmissionAllFamiliesKeepOneIdentity' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementUpdateRequiresAtomicCapability' ../evidence/unit-race.log grep -F -- '--- PASS: TestGatewayManagementRepositoryBindingGuard' ../evidence/unit-race.log diff --git a/backend/internal/handler/gateway_messages_selection_test.go b/backend/internal/handler/gateway_messages_selection_test.go index 3b0097bc6729..aa834e0133c0 100644 --- a/backend/internal/handler/gateway_messages_selection_test.go +++ b/backend/internal/handler/gateway_messages_selection_test.go @@ -23,10 +23,11 @@ import ( type gatewayMessagesHandlerRepo struct { service.AccountRepository - account *service.Account - group *service.Group - queries int - reads int + account *service.Account + group *service.Group + queries int + reads int + afterRead func() } func (r *gatewayMessagesHandlerRepo) ListGatewayRequestCandidates(context.Context, int64, string) ([]service.Account, *service.Group, error) { @@ -36,7 +37,12 @@ func (r *gatewayMessagesHandlerRepo) ListGatewayRequestCandidates(context.Contex func (r *gatewayMessagesHandlerRepo) GatewayRequestAccount(context.Context, int64, int64) (*service.Account, *service.Group, error) { r.reads++ - return r.account, r.group, nil + snapshot := *r.account + snapshot.AccountGroups = append([]service.AccountGroup(nil), r.account.AccountGroups...) + if r.afterRead != nil { + r.afterRead() + } + return &snapshot, r.group, nil } type gatewayMessagesSlotCache struct { @@ -163,3 +169,153 @@ func TestGatewayProtocolMessagesHandlerSchedulerToUsage(t *testing.T) { } } } + +type gatewayMessagesChannelRepo struct { + service.ChannelRepository + channel service.Channel + groupID int64 +} + +func (r *gatewayMessagesChannelRepo) ListAll(context.Context) ([]service.Channel, error) { + return []service.Channel{r.channel}, nil +} + +func (r *gatewayMessagesChannelRepo) GetGroupPlatforms(context.Context, []int64) (map[int64]string, error) { + return map[int64]string{r.groupID: service.PlatformAnthropic}, nil +} + +func TestGatewayProtocolMessagesChannelMappingPreservesBindingModel(t *testing.T) { + for _, batch := range []bool{false, true} { + for _, scenario := range []string{"channel", "channel-account-mapping", "revoke-selection-model", "no-mapping", "legacy-channel", "legacy-no-mapping"} { + name := "fallback/" + scenario + if batch { + name = "load-aware/" + scenario + } + t.Run(name, func(t *testing.T) { + const publicModel = "claude-sonnet-4.5" + mapped := scenario != "no-mapping" && scenario != "legacy-no-mapping" + legacy := strings.HasPrefix(scenario, "legacy-") + wantWire := publicModel + if mapped { + wantWire = "relay-sonnet" + } + if scenario == "channel-account-mapping" { + wantWire = "account-relay-sonnet" + } + var peerCalls atomic.Int32 + peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + peerCalls.Add(1) + body, err := io.ReadAll(req.Body) + require.NoError(t, err) + require.Equal(t, "/tenant/v1/messages", req.URL.Path) + require.Equal(t, wantWire, gjson.GetBytes(body, "model").String()) + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"msg_mapping","type":"message","role":"assistant","model":"`+wantWire+`","content":[{"type":"text","text":"OK"}],"stop_reason":"end_turn","usage":{"input_tokens":12,"output_tokens":7}}`) + })) + defer peer.Close() + cfg := &config.Config{} + cfg.Security.URLAllowlist.AllowPrivateHosts = true + cfg.Security.URLAllowlist.AllowInsecureHTTP = true + cfg.Gateway.Scheduling.LoadBatchEnabled = batch + groupID := int64(9595) + group := &service.Group{ID: groupID, Hydrated: true, Platform: service.PlatformAnthropic, Status: service.StatusActive, RateMultiplier: 1, + ModelAllowlist: service.GroupModelAllowlist{Enabled: true, Models: []string{publicModel}}} + if scenario == "revoke-selection-model" { + // Isolate the binding guard: a separate public allowlist must not + // mask a final admission that incorrectly accepts the wire alias. + group.ModelAllowlist = service.GroupModelAllowlist{} + } + account := &service.Account{ID: 9596, Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Status: service.StatusActive, Schedulable: true, Concurrency: 2, + Credentials: map[string]any{"upstream_kind": "new_api", "api_key": "synthetic-only", "base_url": peer.URL + "/tenant/v1"}, + GroupIDs: []int64{groupID}, AccountGroups: []service.AccountGroup{{AccountID: 9596, GroupID: groupID, AllowedModels: []string{publicModel}}}} + if scenario == "channel-account-mapping" { + // Selection checks source keys; forwarding maps the channel result, + // exactly as the existing handler and legacy account contract do. + account.Credentials["model_mapping"] = map[string]any{publicModel: "selection-target-not-wire", "relay-sonnet": wantWire} + } + sharedCache := &fakeSchedulerCache{} + if legacy { + account.Platform, account.Type = service.PlatformAnthropic, service.AccountTypeAPIKey + account.Credentials["base_url"] = peer.URL + "/tenant" + account.Extra = map[string]any{"anthropic_passthrough": true} + sharedCache.accounts = []*service.Account{account} + } + repo := &gatewayMessagesHandlerRepo{account: account, group: group} + slots := &gatewayMessagesSlotCache{} + revokedAtRead := 0 + if scenario == "revoke-selection-model" { + repo.afterRead = func() { + if slots.active > 0 && revokedAtRead == 0 { + // The returned hydration snapshot still permits selection. + // The next authority read sees only the wire alias permitted. + revokedAtRead = repo.reads + account.AccountGroups = []service.AccountGroup{{AccountID: account.ID, GroupID: groupID, AllowedModels: []string{"relay-sonnet"}}} + } + } + } + channelRepo := &gatewayMessagesChannelRepo{groupID: groupID, channel: service.Channel{ID: 9597, Status: service.StatusActive, + GroupIDs: []int64{groupID}, BillingModelSource: service.BillingModelSourceRequested}} + if mapped { + channelRepo.channel.ModelMapping = map[string]map[string]string{service.PlatformAnthropic: {publicModel: "relay-sonnet"}} + } + channels := service.NewChannelService(channelRepo, nil, nil, nil, nil) + concurrency := service.NewConcurrencyService(slots) + usage := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 2)} + billingCache := service.NewBillingCacheService(newHandlerInflightCache(100), nil, nil, nil, nil, nil, cfg, nil) + t.Cleanup(billingCache.Stop) + gw := service.NewGatewayService( + repo, &fakeGroupRepo{group: group}, usage, &compatStreamUsageBillingRepo{}, nil, nil, nil, nil, cfg, + service.NewSchedulerSnapshotService(sharedCache, nil, nil, nil, nil), concurrency, service.NewBillingService(cfg, nil), nil, nil, nil, repository.NewHTTPUpstream(cfg), + &service.DeferredService{}, nil, nil, nil, nil, nil, nil, channels, nil, nil, nil, nil, + ) + h := &GatewayHandler{gatewayService: gw, billingCacheService: billingCache, cfg: cfg, maxAccountSwitches: 1, + concurrencyHelper: NewConcurrencyHelper(concurrency, SSEPingFormatClaude, 0)} + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"`+publicModel+`","max_tokens":32,"messages":[{"role":"user","content":"hello"}]}`)) + c.Request.Header.Set("Content-Type", "application/json") + key := &service.APIKey{ID: 9598, UserID: 9599, GroupID: &groupID, Group: group, User: &service.User{ID: 9599, Balance: 100}} + c.Set(string(middleware.ContextKeyAPIKey), key) + c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9599}) + h.Messages(c) + require.Equal(t, account.ID, slots.id) + require.Equal(t, 2, slots.limit) + require.Zero(t, slots.active) + require.Positive(t, slots.releases) + if scenario == "revoke-selection-model" { + require.Positive(t, revokedAtRead) + require.Greater(t, repo.reads, revokedAtRead, "final admission must read the changed binding after hydration") + require.Zero(t, peerCalls.Load()) + require.Empty(t, usage.created) + return + } + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Equal(t, int32(1), peerCalls.Load()) + select { + case log := <-usage.created: + require.Equal(t, account.ID, log.AccountID) + require.Equal(t, publicModel, log.RequestedModel) + channelModel := publicModel + if mapped { + channelModel = "relay-sonnet" + } + require.Equal(t, channelModel, log.Model, "retain the existing Forward model; RequestedModel records the public name") + require.NotNil(t, log.UpstreamModel) + require.Equal(t, wantWire, *log.UpstreamModel) + require.Equal(t, 12, log.InputTokens) + if mapped { + chain := publicModel + "→relay-sonnet" + if scenario == "channel-account-mapping" { + chain += "→" + wantWire + } + require.NotNil(t, log.ModelMappingChain) + require.Equal(t, chain, *log.ModelMappingChain) + } + case <-time.After(3 * time.Second): + t.Fatal("handler did not deliver mapped usage") + } + }) + } + } +} diff --git a/backend/internal/service/gateway_protocol_admission.go b/backend/internal/service/gateway_protocol_admission.go index c72cfef2b9e5..34ad263ae9c8 100644 --- a/backend/internal/service/gateway_protocol_admission.go +++ b/backend/internal/service/gateway_protocol_admission.go @@ -168,11 +168,23 @@ func gatewayProtocolAccountFromSnapshot(ctx context.Context, selected, current * scope.Credentials = maps.Clone(current.Credentials) scope.modelMappingCacheReady = false id := liveGroup.ID - publicModel := model + selectionModel := model + if family == domain.PlatformGatewayAnthropic { + if requested, enabled := gatewayMessagesSelectionModel(ctx, &id, target); enabled { + selectionModel = requested + if scheduling, _ := ctx.Value(gatewaySchedulingModelContextKey{}).(string); scheduling != "" { + selectionModel = scheduling + } + } + } + publicModel := selectionModel if original, ok := RequestedPublicModelFromContext(ctx); ok { publicModel = original } - if !liveGroup.ModelAllowlist.Allows(publicModel) || !scope.isModelMappingSupported(model) || !scope.IsModelAllowedInGroup(&id, model) { + // Account source-key scope and binding eligibility follow selection, before + // channel rewriting. Forward retains model as the channel input and applies + // the existing account mapping to it; a wire alias grants no binding rights. + if !liveGroup.ModelAllowlist.Allows(publicModel) || !scope.isModelMappingSupported(selectionModel) || !scope.IsModelAllowedInGroup(&id, selectionModel) { return nil, ErrGatewayAccountGroup } view := scope @@ -204,7 +216,7 @@ func gatewayProtocolAccountFromSnapshot(ctx context.Context, selected, current * delete(view.Extra, key) } view.modelMappingCacheReady = false - if !view.IsSchedulableForModelWithContext(ctx, model) { + if !view.IsSchedulableForModelWithContext(ctx, selectionModel) || !view.IsSchedulableForModelWithContext(ctx, model) { return nil, ErrGatewayProtocolsPending } if family == domain.PlatformGatewayAnthropic { From a01e8751cc438baaf1ef4826caafdeb06d83b740 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 15:03:47 +0800 Subject: [PATCH 17/26] =?UTF-8?q?fix:=20=E5=A4=8D=E7=94=A8=E7=BD=91?= =?UTF-8?q?=E5=85=B3=E8=AF=BB=E5=8F=96=E4=BA=8B=E5=8A=A1=E5=B9=B6=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=20Messages=20=E8=B0=83=E5=BA=A6=E5=9B=9E=E5=BD=92?= =?UTF-8?q?=E5=A4=B9=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../scripts/upstream-v0222-red-fixtures.txt | 3 ++ .../gateway_messages_selection_test.go | 9 +++- .../repository/gateway_request_admission.go | 51 +++++++++++-------- .../repository/gateway_request_candidates.go | 25 ++++----- .../service/gateway_protocol_admission.go | 3 +- .../gateway_protocol_openai_admission_test.go | 4 +- 6 files changed, 56 insertions(+), 39 deletions(-) diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index 1ce6e1af0098..352d7f913619 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -200,3 +200,6 @@ backend/internal/handler/request_body_read_log_test.go # Probe penalty tests use receipt types absent from historical WS sources. backend/internal/handler/probe_penalty_response_test.go backend/internal/service/account_probe_penalty_test.go + +# Native Messages gateway selection requires the request-scoped account and group reader. +backend/internal/handler/gateway_messages_selection_test.go diff --git a/backend/internal/handler/gateway_messages_selection_test.go b/backend/internal/handler/gateway_messages_selection_test.go index aa834e0133c0..bc9f1507ff1f 100644 --- a/backend/internal/handler/gateway_messages_selection_test.go +++ b/backend/internal/handler/gateway_messages_selection_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey" "github.com/Wei-Shaw/sub2api/internal/repository" middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware" "github.com/Wei-Shaw/sub2api/internal/service" @@ -30,6 +31,10 @@ type gatewayMessagesHandlerRepo struct { afterRead func() } +func (r *gatewayMessagesHandlerRepo) ListModelAvailabilityCandidates(context.Context, *int64, []string, bool) ([]service.Account, error) { + return nil, nil +} + func (r *gatewayMessagesHandlerRepo) ListGatewayRequestCandidates(context.Context, int64, string) ([]service.Account, *service.Group, error) { r.queries++ return []service.Account{*r.account}, r.group, nil @@ -136,6 +141,7 @@ func TestGatewayProtocolMessagesHandlerSchedulerToUsage(t *testing.T) { rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"claude-sonnet-4.5","max_tokens":32,"messages":[{"role":"user","content":"hello"}]}`)) + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, group)) c.Request.Header.Set("Content-Type", "application/json") key := &service.APIKey{ID: 9593, UserID: 9594, GroupID: &groupID, Group: group, User: &service.User{ID: 9594, Balance: 100}} c.Set(string(middleware.ContextKeyAPIKey), key) @@ -228,7 +234,7 @@ func TestGatewayProtocolMessagesChannelMappingPreservesBindingModel(t *testing.T account := &service.Account{ID: 9596, Platform: service.PlatformGateway, Type: service.AccountTypeGateway, Status: service.StatusActive, Schedulable: true, Concurrency: 2, Credentials: map[string]any{"upstream_kind": "new_api", "api_key": "synthetic-only", "base_url": peer.URL + "/tenant/v1"}, - GroupIDs: []int64{groupID}, AccountGroups: []service.AccountGroup{{AccountID: 9596, GroupID: groupID, AllowedModels: []string{publicModel}}}} + GroupIDs: []int64{groupID}, AccountGroups: []service.AccountGroup{{AccountID: 9596, GroupID: groupID, AllowedModels: []string{publicModel}}}} if scenario == "channel-account-mapping" { // Selection checks source keys; forwarding maps the channel result, // exactly as the existing handler and legacy account contract do. @@ -274,6 +280,7 @@ func TestGatewayProtocolMessagesChannelMappingPreservesBindingModel(t *testing.T rec := httptest.NewRecorder() c, _ := gin.CreateTestContext(rec) c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"`+publicModel+`","max_tokens":32,"messages":[{"role":"user","content":"hello"}]}`)) + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), ctxkey.Group, group)) c.Request.Header.Set("Content-Type", "application/json") key := &service.APIKey{ID: 9598, UserID: 9599, GroupID: &groupID, Group: group, User: &service.User{ID: 9599, Balance: 100}} c.Set(string(middleware.ContextKeyAPIKey), key) diff --git a/backend/internal/repository/gateway_request_admission.go b/backend/internal/repository/gateway_request_admission.go index a2434a9cd5be..3394320a9038 100644 --- a/backend/internal/repository/gateway_request_admission.go +++ b/backend/internal/repository/gateway_request_admission.go @@ -3,7 +3,6 @@ package repository import ( "context" "database/sql" - "errors" dbent "github.com/Wei-Shaw/sub2api/ent" "github.com/Wei-Shaw/sub2api/internal/service" @@ -12,25 +11,37 @@ import ( var _ service.GatewayRequestAccountReader = (*accountRepository)(nil) func (r *accountRepository) GatewayRequestAccount(ctx context.Context, accountID, groupID int64) (*service.Account, *service.Group, error) { - if dbent.TxFromContext(ctx) == nil { - tx, err := r.client.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead}) - if errors.Is(err, dbent.ErrTxStarted) { - return r.gatewayRequestAccount(ctx, accountID, groupID) - } - if err != nil { - return nil, nil, err - } - defer func() { _ = tx.Rollback() }() - account, group, err := r.gatewayRequestAccount(dbent.NewTxContext(ctx, tx), accountID, groupID) - if err != nil { - return nil, nil, err - } - if err := tx.Commit(); err != nil { - return nil, nil, err - } - return account, group, nil - } - return r.gatewayRequestAccount(ctx, accountID, groupID) + return withGatewayReadSnapshot(ctx, r, func(ctx context.Context, reader *accountRepository) (*service.Account, *service.Group, error) { + return reader.gatewayRequestAccount(ctx, accountID, groupID) + }) +} + +// Reuse the caller's transaction when present. Otherwise keep the account, +// bindings and group policy in one repeatable-read snapshot. +func withGatewayReadSnapshot[T any](ctx context.Context, r *accountRepository, read func(context.Context, *accountRepository) (T, *service.Group, error)) (T, *service.Group, error) { + tx := dbent.TxFromContext(ctx) + if tx == nil { + tx, _ = r.sql.(*dbent.Tx) + } + if tx != nil { + ctx = dbent.NewTxContext(ctx, tx) + return read(ctx, r.accountTransactionScope(ctx)) + } + var zero T + tx, err := r.client.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead}) + if err != nil { + return zero, nil, err + } + defer func() { _ = tx.Rollback() }() + ctx = dbent.NewTxContext(ctx, tx) + value, group, err := read(ctx, r.accountTransactionScope(ctx)) + if err != nil { + return zero, nil, err + } + if err := tx.Commit(); err != nil { + return zero, nil, err + } + return value, group, nil } func (r *accountRepository) gatewayRequestAccount(ctx context.Context, accountID, groupID int64) (*service.Account, *service.Group, error) { diff --git a/backend/internal/repository/gateway_request_candidates.go b/backend/internal/repository/gateway_request_candidates.go index 5489d2122e5d..177bb24fa2b7 100644 --- a/backend/internal/repository/gateway_request_candidates.go +++ b/backend/internal/repository/gateway_request_candidates.go @@ -2,7 +2,6 @@ package repository import ( "context" - "database/sql" dbent "github.com/Wei-Shaw/sub2api/ent" dbaccount "github.com/Wei-Shaw/sub2api/ent/account" @@ -18,14 +17,13 @@ func (r *accountRepository) ListGatewayRequestCandidates(ctx context.Context, gr if groupID <= 0 || target != service.PlatformAnthropic { return nil, nil, nil } - tx, err := r.client.BeginTx(ctx, &sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead}) - if err != nil { - return nil, nil, err - } - defer func() { _ = tx.Rollback() }() - reader := &accountRepository{client: tx.Client()} - txctx := dbent.NewTxContext(ctx, tx) - g, err := reader.client.Group.Get(txctx, groupID) + return withGatewayReadSnapshot(ctx, r, func(ctx context.Context, reader *accountRepository) ([]service.Account, *service.Group, error) { + return reader.gatewayRequestCandidates(ctx, groupID, target) + }) +} + +func (r *accountRepository) gatewayRequestCandidates(ctx context.Context, groupID int64, target string) ([]service.Account, *service.Group, error) { + g, err := r.client.Group.Get(ctx, groupID) if err != nil { return nil, nil, translatePersistenceError(err, service.ErrGroupNotFound, nil) } @@ -33,24 +31,21 @@ func (r *accountRepository) ListGatewayRequestCandidates(ctx context.Context, gr if g.DeletedAt != nil || !group.IsActive() || group.Platform != target || group.RequireOAuthOnly { return nil, group, nil } - ids, err := observerAccountQuery(txctx, reader.client.Account.Query()).Where( + ids, err := observerAccountQuery(ctx, r.client.Account.Query()).Where( dbaccount.PlatformEQ(service.PlatformGateway), dbaccount.TypeEQ(service.AccountTypeGateway), dbaccount.StatusEQ(service.StatusActive), dbaccount.SchedulableEQ(true), dbaccount.HasAccountGroupsWith(dbaccountgroup.GroupIDEQ(groupID)), - ).Order(dbent.Asc(dbaccount.FieldPriority), dbent.Asc(dbaccount.FieldID)).IDs(txctx) + ).Order(dbent.Asc(dbaccount.FieldPriority), dbent.Asc(dbaccount.FieldID)).IDs(ctx) if err != nil { return nil, nil, err } accounts := make([]service.Account, 0, len(ids)) for _, id := range ids { - account, _, err := reader.gatewayRequestAccount(txctx, id, groupID) + account, _, err := r.gatewayRequestAccount(ctx, id, groupID) if err != nil { return nil, nil, err } accounts = append(accounts, *account) } - if err := tx.Commit(); err != nil { - return nil, nil, err - } return accounts, group, nil } diff --git a/backend/internal/service/gateway_protocol_admission.go b/backend/internal/service/gateway_protocol_admission.go index 34ad263ae9c8..19f871634e6a 100644 --- a/backend/internal/service/gateway_protocol_admission.go +++ b/backend/internal/service/gateway_protocol_admission.go @@ -159,7 +159,8 @@ func gatewayProtocolAccountFromSnapshot(ctx context.Context, selected, current * if !concrete || (liveGroup.Platform != PlatformComposite && liveGroup.Platform != target) { return nil, ErrGatewayAccountGroup } - if spec.Gateway != family && !(target == PlatformAntigravity && (family == domain.PlatformGatewayAnthropic || family == domain.PlatformGatewayGemini)) { + nativeAntigravity := target == PlatformAntigravity && (family == domain.PlatformGatewayAnthropic || family == domain.PlatformGatewayGemini) + if spec.Gateway != family && !nativeAntigravity { return nil, ErrGatewayProtocolsPending } // Validate model scope while the account still has its neutral identity: no diff --git a/backend/internal/service/gateway_protocol_openai_admission_test.go b/backend/internal/service/gateway_protocol_openai_admission_test.go index 9a7d3c2effe2..cc3634d023b2 100644 --- a/backend/internal/service/gateway_protocol_openai_admission_test.go +++ b/backend/internal/service/gateway_protocol_openai_admission_test.go @@ -22,8 +22,8 @@ import ( type gatewayProtocolOpenAIRepo struct { *gatewayProtocolAdmissionRepo turnReads int - changeAt int - change func(*Account) + changeAt int + change func(*Account) } func (r *gatewayProtocolOpenAIRepo) GetOpenAITurnAdmission(context.Context, int64) (*Account, *Account, error) { From 44ecd221ac1582c833b0b1e29c136fed950b551e Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sat, 21 Nov 2026 15:12:49 +0800 Subject: [PATCH 18/26] =?UTF-8?q?feat:=20=E6=8E=A5=E5=85=A5=E8=B7=A8?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E7=BD=91=E5=85=B3=E8=B4=A6=E5=8F=B7=E8=A1=A8?= =?UTF-8?q?=E5=8D=95=E3=80=81=E5=88=86=E7=BB=84=E9=80=89=E6=8B=A9=E5=92=8C?= =?UTF-8?q?=E4=B8=8A=E6=B8=B8=E4=BD=99=E9=A2=9D=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/internal/repository/account_repo.go | 2 +- ...nt_repo_upstream_billing_probe_due_test.go | 4 +- .../internal/service/new_api_authorization.go | 12 +++++- .../service/new_api_authorization_test.go | 26 ++++++++++- .../service/upstream_billing_probe.go | 18 ++++---- .../components/account/CreateAccountModal.vue | 30 ++++++++++++- .../components/account/EditAccountModal.vue | 14 ++++++ .../account/GatewayAccountFields.vue | 43 +++++++++++++++++++ .../account/NewAPIUpstreamConfigDialog.vue | 6 ++- .../account/UpstreamBillingRateCell.vue | 5 ++- .../__tests__/CreateAccountModal.spec.ts | 19 ++++++++ .../src/components/common/GroupSelector.vue | 4 +- .../components/common/PlatformTypeBadge.vue | 3 +- frontend/src/constants/newFeatureNotices.ts | 1 + frontend/src/constants/platformCatalog.ts | 1 + .../src/i18n/locales/en/admin/accounts.ts | 2 + .../src/i18n/locales/zh/admin/accounts.ts | 2 + frontend/src/types/index.ts | 2 +- frontend/src/views/admin/AccountsView.vue | 4 +- 19 files changed, 173 insertions(+), 25 deletions(-) create mode 100644 frontend/src/components/account/GatewayAccountFields.vue diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 94ab0665b502..2e1c04f73959 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -4563,7 +4563,7 @@ func (r *accountRepository) ListDueUpstreamBillingProbeAccounts(ctx context.Cont FROM accounts WHERE deleted_at IS NULL AND status = 'active' - AND type = 'apikey' + AND (type = 'apikey' OR (type = 'gateway' AND platform = 'gateway')) AND extra @> '{"upstream_billing_probe_enabled": true}'::jsonb ), parsed AS MATERIALIZED ( SELECT diff --git a/backend/internal/repository/account_repo_upstream_billing_probe_due_test.go b/backend/internal/repository/account_repo_upstream_billing_probe_due_test.go index 113725063664..a13678034453 100644 --- a/backend/internal/repository/account_repo_upstream_billing_probe_due_test.go +++ b/backend/internal/repository/account_repo_upstream_billing_probe_due_test.go @@ -28,9 +28,7 @@ func TestAccountRepositoryListDueUpstreamBillingProbeAccountsBoundsQuery(t *test normalized := normalizeSQLWhitespace(capturedSQL) require.Contains(t, normalized, "deleted_at IS NULL") require.Contains(t, normalized, "status = 'active'") - // 探测资格已放宽到全部 API-key 平台:候选 SQL 不得再按 platform 过滤。 - require.NotContains(t, normalized, "platform") - require.Contains(t, normalized, "type = 'apikey'") + require.Contains(t, normalized, "(type = 'apikey' OR (type = 'gateway' AND platform = 'gateway'))") require.Contains(t, normalized, `extra @> '{"upstream_billing_probe_enabled": true}'::jsonb`) require.Contains(t, normalized, "jsonb_path_query_first_tz") require.Contains(t, normalized, `'(\.[0-9]{6})[0-9]+(Z|[+-][0-9]{2}:[0-9]{2})$'`) diff --git a/backend/internal/service/new_api_authorization.go b/backend/internal/service/new_api_authorization.go index fc5eca5fbf97..85380979c21d 100644 --- a/backend/internal/service/new_api_authorization.go +++ b/backend/internal/service/new_api_authorization.go @@ -101,7 +101,8 @@ func (s *UpstreamBillingProbeService) newAPIAccount(ctx context.Context, id int6 if e != nil { return nil, "", e } - if !isUpstreamBillingProbeAccount(a) || a.GetCredential("api_key") == "" { + if !isUpstreamBillingProbeAccount(a) || a.GetCredential("api_key") == "" || + (a.IsGateway() && a.GetCredential(GatewayUpstreamKindCredentialKey) != "new_api") { return nil, "", ErrUpstreamBillingProbeAccountInvalid } site, e := CanonicalNewAPISite(a.GetCredential("base_url")) @@ -117,6 +118,15 @@ func (s *UpstreamBillingProbeService) GetNewAPIConfig(ctx context.Context, id in if e != nil { return nil, e } + gateways, e := s.accountRepo.ListAllWithFilters(ctx, PlatformGateway, AccountTypeGateway, "", "", 0, "") + if e != nil { + return nil, e + } + for i := range gateways { + if gateways[i].IsGateway() && gateways[i].GetCredential(GatewayUpstreamKindCredentialKey) == "new_api" { + accounts = append(accounts, gateways[i]) + } + } found := false for i := range accounts { if accounts[i].ID == id { diff --git a/backend/internal/service/new_api_authorization_test.go b/backend/internal/service/new_api_authorization_test.go index 99b51e1b09f6..44c613d5c32b 100644 --- a/backend/internal/service/new_api_authorization_test.go +++ b/backend/internal/service/new_api_authorization_test.go @@ -13,10 +13,12 @@ type newAPIAccounts struct { *upstreamBillingProbeAccountRepo } -func (r *newAPIAccounts) ListAllWithFilters(context.Context, string, string, string, string, int64, string) ([]Account, error) { +func (r *newAPIAccounts) ListAllWithFilters(_ context.Context, platform, kind, _, _ string, _ int64, _ string) ([]Account, error) { out := []Account{} for _, a := range r.accounts { - out = append(out, *a) + if (platform == "" || platform == a.Platform) && (kind == "" || kind == a.Type) { + out = append(out, *a) + } } return out, nil } @@ -67,6 +69,26 @@ func TestNewAPIConfigNoSaveForForeignOrUnmatchedAccounts(t *testing.T) { require.Empty(t, r.bindings) } } +func TestNewAPIGatewayAuthorizationUsesDeclaredProvider(t *testing.T) { + s, auth, _, repo := newAPIConfigFixture() + gateway := repo.accounts[1] + gateway.Platform, gateway.Type = PlatformGateway, AccountTypeGateway + gateway.Credentials[GatewayUpstreamKindCredentialKey] = "sub2api" + _, err := s.GetNewAPIConfig(context.Background(), gateway.ID) + require.ErrorIs(t, err, ErrUpstreamBillingProbeAccountInvalid) + + gateway.Credentials[GatewayUpstreamKindCredentialKey] = "new_api" + preview, err := s.SaveNewAPIConfig(context.Background(), gateway.ID, NewAPIConfigRequest{UserID: 7, AccountIDs: []int64{gateway.ID}, AccessToken: "synthetic-management-token"}) + require.NoError(t, err) + require.Len(t, preview.Accounts, 1) + require.Nil(t, preview.Accounts[0].CostMultiplier) + require.Equal(t, 2.5, preview.Wallet.Amount) + config, err := s.GetNewAPIConfig(context.Background(), repo.accounts[2].ID) + require.NoError(t, err) + require.Len(t, config.Accounts, 2) + require.NotNil(t, auth.bindings[gateway.ID]) +} + func TestNewAPIConfigSharedEncryptedAuthAndSafeRead(t *testing.T) { s, r, h, accounts := newAPIConfigFixture() h.bodies["GET /api/token/?p=0&page_size=100"] = `{"success":true,"data":{"items":[{"id":3,"key":"abcd**********wxyz","group":"vip"},{"id":4,"key":"nope**********xxxx","group":"auto"}],"total":2,"page":1,"page_size":100}}` diff --git a/backend/internal/service/upstream_billing_probe.go b/backend/internal/service/upstream_billing_probe.go index 674f23cc672f..8557e359776e 100644 --- a/backend/internal/service/upstream_billing_probe.go +++ b/backend/internal/service/upstream_billing_probe.go @@ -152,7 +152,7 @@ func BuildUpstreamBillingRateSnapshotItems(accounts []Account) []UpstreamBilling // The billing endpoint is supported by every API-key platform; limiting // this projection to OpenAI would make the background refresh erase the // other platforms' persisted snapshots from the table. - if account.Type == AccountTypeAPIKey { + if account.Type == AccountTypeAPIKey || account.IsGateway() { snapshot = decodeUpstreamBillingProbeSnapshot(account.Extra) } items = append(items, UpstreamBillingRateSnapshotItem{ @@ -630,7 +630,7 @@ func (s *UpstreamBillingProbeService) SetAccountEnabled(ctx context.Context, acc func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, account *Account, intervalMinutes int) (*UpstreamBillingProbeSnapshot, error) { now := s.currentTime().UTC() - if s.newAPIRepo != nil { + if s.newAPIRepo != nil && (!account.IsGateway() || account.GetCredential(GatewayUpstreamKindCredentialKey) == "new_api") { binding, err := s.newAPIRepo.GetBinding(ctx, account.ID) if err != nil { return nil, newAPIError("storage_unavailable") @@ -639,6 +639,9 @@ func (s *UpstreamBillingProbeService) probeLoadedAccount(ctx context.Context, ac return s.probeNewAPIAccount(ctx, account, binding, intervalMinutes) } } + if account.IsGateway() && account.GetCredential(GatewayUpstreamKindCredentialKey) == "new_api" { + return s.persistProbeFailure(ctx, account, intervalMinutes, now, 0, "new_api_authorization_required", 0) + } if s.accountTestService == nil || s.accountTestService.httpUpstream == nil { return s.persistProbeFailure(ctx, account, intervalMinutes, now, 0, "transport_unavailable", 0) } @@ -1125,14 +1128,11 @@ func isUpstreamBillingProbeStatus(status string) bool { // CN providers, whose official-domain accounts are short-circuited to // "unsupported" by upstreamBillingProbeTargetIsOfficialAPI). // Non-sub2api upstreams return 404 and the snapshot records "unsupported". -// Only AccountTypeAPIKey is in scope. OAuth/Bedrock hold no static API key to -// present at all; AccountTypeUpstream (antigravity relay accounts) does carry -// a base_url plus a static api_key, but it is deliberately left out of the -// current supported set. New antigravity relay accounts are created with -// type=apikey by the admin form, so only pre-existing type=upstream rows -// cannot turn the probe on. +// Explicit gateway accounts use either the configured New API authorization +// or the Sub2API declaration endpoint. Other relay types retain their policy. func IsUpstreamBillingProbeIdentity(platform, accountType string) bool { - return accountType == AccountTypeAPIKey && domain.IsConcretePlatform(platform) + return (accountType == AccountTypeAPIKey && domain.IsConcretePlatform(platform)) || + (accountType == AccountTypeGateway && platform == PlatformGateway) } func isUpstreamBillingProbeAccount(account *Account) bool { diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index e831dc0665f6..95b7d122e1f4 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -250,6 +250,12 @@ OpenCode +
+ + +