From 1f77c771286d814b91cde0db1ade9dcede0f0695 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Sun, 22 Nov 2026 20:47:41 +0800 Subject: [PATCH 1/5] fix: support account-scoped gateway model discovery --- .../workflows/issue959-gateway-regression.yml | 16 ++- Makefile | 1 + .../internal/handler/admin/account_handler.go | 25 +++- .../account_handler_gateway_models_test.go | 100 ++++++++++++++ ...po_upstream_model_sync_integration_test.go | 34 +++++ .../gateway_account_management_test.go | 10 ++ .../gateway_messages_selection_test.go | 21 +++ .../internal/service/gateway_model_catalog.go | 5 + .../service/gateway_upstream_models_test.go | 124 ++++++++++++++++++ backend/internal/service/upstream_models.go | 27 ++++ frontend/src/api/admin/accounts.ts | 2 + .../components/account/CreateAccountModal.vue | 11 +- .../components/account/EditAccountModal.vue | 11 ++ .../account/GatewayModelSettings.vue | 33 +++++ .../account/ModelWhitelistSelector.vue | 2 + .../__tests__/CreateAccountModal.spec.ts | 15 ++- .../__tests__/EditAccountModal.spec.ts | 55 ++++++++ .../__tests__/ModelWhitelistSelector.spec.ts | 16 ++- frontend/src/constants/newFeatureNotices.ts | 1 + frontend/src/constants/platformCatalog.ts | 1 + frontend/src/views/admin/AccountsView.vue | 26 ++++ .../AccountsView.newAPIConfig.spec.ts | 16 ++- 22 files changed, 543 insertions(+), 9 deletions(-) create mode 100644 backend/internal/handler/admin/account_handler_gateway_models_test.go create mode 100644 backend/internal/service/gateway_upstream_models_test.go create mode 100644 frontend/src/components/account/GatewayModelSettings.vue diff --git a/.github/workflows/issue959-gateway-regression.yml b/.github/workflows/issue959-gateway-regression.yml index 0fce8d978b67..70c57af98c84 100644 --- a/.github/workflows/issue959-gateway-regression.yml +++ b/.github/workflows/issue959-gateway-regression.yml @@ -10,6 +10,7 @@ on: - 'backend/internal/handler/admin/account*' - 'backend/internal/handler/dto/account_mapper_redact_test.go' - 'backend/internal/repository/account_repo.go' + - 'backend/internal/repository/account_repo_upstream_model_sync*' - 'backend/internal/repository/group_repo.go' - 'backend/internal/repository/gateway_account*' - 'backend/internal/repository/gateway_request_admission*' @@ -84,7 +85,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|GatewayProtocol|GatewayDataImport|AccountGatewayDTO|NewAPIGateway|NewAPICostRequest|NewAPICostScale|UsagePlatformSnapshots|ProcurementSnapshot|ObserverProcurementSnapshot)' \ + -run '^Test(GatewayIdentity|GatewayUsage|GatewayManagement|GatewayProtocol|GatewayUpstreamModels|AccountHandlerGatewayModels|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,9 @@ 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: TestGatewayUpstreamModelsDiscoveryAndApply' ../evidence/unit-race.log + grep -F -- '--- PASS: TestAccountHandlerGatewayModelsDraftAndSavedConnection' ../evidence/unit-race.log + grep -F -- '--- PASS: TestGatewayProtocolCatalogSavedModelsAndGroupPrecedence' ../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 @@ -148,6 +152,16 @@ jobs: grep -F -- '--- PASS: TestProcurementSnapshotDurableReplayDoesNotRepriceOrRecharge' ../evidence/procurement-cost.log grep -F -- '--- PASS: TestProcurementSnapshotProfitUsesMixedRequestTargetsAndUnknowns' ../evidence/procurement-cost.log grep -F -- '--- PASS: TestProcurementSnapshotMigrationLeavesHistoryAndChargesUntouched' ../evidence/procurement-cost.log + - name: Gateway account-only model persistence + working-directory: backend + shell: bash + run: | + set -euo pipefail + go test -race -tags=integration ./internal/repository \ + -run '^Test(GatewayUpstreamModelsPersistOnlyAccountMapping|ApplyUpstreamModelsPreservesCredentialsAndInvalidatesScheduler)$' \ + -count=1 -v -timeout=10m 2>&1 | tee ../evidence/gateway-model-persistence.log + if grep -Eq -- 'no tests to run|--- SKIP:' ../evidence/gateway-model-persistence.log; then exit 1; fi + grep -F -- '--- PASS: TestGatewayUpstreamModelsPersistOnlyAccountMapping' ../evidence/gateway-model-persistence.log - uses: actions/upload-artifact@v7 if: always() with: diff --git a/Makefile b/Makefile index 75004f36c0e3..272c45c77a70 100644 --- a/Makefile +++ b/Makefile @@ -84,6 +84,7 @@ FRONTEND_CRITICAL_VITEST := \ src/views/admin/__tests__/AccountQualityView.spec.ts \ src/views/admin/__tests__/AccountsView.bulkEdit.spec.ts \ src/views/admin/__tests__/AccountsView.declarationRefresh.spec.ts \ + src/views/admin/__tests__/AccountsView.newAPIConfig.spec.ts \ src/utils/__tests__/accountUpstreamModelAutoSync.spec.ts \ src/utils/__tests__/qualityRulePatch.spec.ts \ src/components/admin/operations/__tests__/QualityOwnershipReview.spec.ts \ diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index 858ed72e44f0..0eb9fc4f2026 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -3415,14 +3415,36 @@ func (h *AccountHandler) SyncUpstreamModelsPreview(c *gin.Context) { Platform string `json:"platform" binding:"required"` Type string `json:"type" binding:"required"` BaseURL string `json:"base_url"` - APIKey string `json:"api_key" binding:"required"` + APIKey string `json:"api_key"` + AccountID *int64 `json:"account_id" binding:"omitempty,gt=0"` ProxyID *int64 `json:"proxy_id" binding:"omitempty,gte=0"` ModelMapping map[string]string `json:"model_mapping"` + UpstreamKind string `json:"upstream_kind"` } if err := c.ShouldBindJSON(&req); err != nil { response.BadRequest(c, "Invalid request: "+err.Error()) return } + // Gateway edits may preview a draft URL/proxy without returning the saved + // calling key to the browser. Resolve only an accessible gateway account. + if req.AccountID != nil { + if _, observer := service.ObserverGroupIDs(c.Request.Context()); observer { + response.ErrorFrom(c, service.ErrObserverScope) + return + } + account, err := h.adminService.GetAccount(c.Request.Context(), *req.AccountID) + if err != nil || account == nil || !account.IsGateway() || req.Platform != service.PlatformGateway || req.Type != service.AccountTypeGateway { + response.BadRequest(c, "Invalid gateway preview account") + return + } + if strings.TrimSpace(req.APIKey) == "" { + req.APIKey = account.GetCredential("api_key") + } + } + if strings.TrimSpace(req.APIKey) == "" { + response.BadRequest(c, "API key is required") + return + } modelMapping := make(map[string]any, len(req.ModelMapping)) for sourceModel, upstreamModel := range req.ModelMapping { modelMapping[sourceModel] = upstreamModel @@ -3432,6 +3454,7 @@ func (h *AccountHandler) SyncUpstreamModelsPreview(c *gin.Context) { Platform: req.Platform, Type: req.Type, Credentials: map[string]any{ + "upstream_kind": req.UpstreamKind, "api_key": req.APIKey, "base_url": req.BaseURL, "model_mapping": modelMapping, diff --git a/backend/internal/handler/admin/account_handler_gateway_models_test.go b/backend/internal/handler/admin/account_handler_gateway_models_test.go new file mode 100644 index 000000000000..7f17b2b8c3c4 --- /dev/null +++ b/backend/internal/handler/admin/account_handler_gateway_models_test.go @@ -0,0 +1,100 @@ +//go:build unit + +package admin + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +type gatewayPreviewAdminService struct { + *availableModelsAdminService +} + +func (s *gatewayPreviewAdminService) GetProxy(context.Context, int64) (*service.Proxy, error) { + return nil, nil +} + +func TestAccountHandlerGatewayModelsDraftAndSavedConnection(t *testing.T) { + for _, kind := range []string{"new_api", "sub2api"} { + for _, draft := range []bool{false, true} { + t.Run(kind+map[bool]string{false: "/saved", true: "/draft"}[draft], func(t *testing.T) { + svc := &availableModelsAdminService{stubAdminService: newStubAdminService(), account: service.Account{ + ID: 1003, Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Credentials: map[string]any{"upstream_kind": kind, "base_url": "https://saved.example/v1", "api_key": "saved-synthetic-key"}, + }} + upstream := &syncUpstreamHTTPUpstream{resp: &http.Response{StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"data":[{"id":"live"}]}`))}} + router := setupSyncUpstreamModelsRouter(svc, upstream) + path, payload := "/api/v1/admin/accounts/1003/models/sync-upstream", map[string]any{} + if draft { + path = "/api/v1/admin/accounts/models/sync-upstream-preview" + payload = map[string]any{"platform": "gateway", "type": "gateway", "upstream_kind": kind, + "account_id": 1003, "base_url": "https://draft.example/tenant", "api_key": ""} + } + body, err := json.Marshal(payload) + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(string(body))) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + require.Len(t, upstream.requests, 1) + wantURL := "https://saved.example/v1/models" + if draft { + wantURL = "https://draft.example/tenant/v1/models" + } + require.Equal(t, wantURL, upstream.requests[0].URL.String()) + require.Equal(t, "Bearer saved-synthetic-key", upstream.requests[0].Header.Get("Authorization")) + require.Contains(t, rec.Body.String(), `"discovery_source":"upstream"`) + require.NotContains(t, rec.Body.String(), "saved-synthetic-key") + }) + } + } +} + +func TestAccountHandlerGatewayModelsPreviewRejectsObserverAndMissingProxy(t *testing.T) { + for _, scenario := range []string{"observer", "proxy", "invalid-kind", "missing-key"} { + t.Run(scenario, func(t *testing.T) { + svc := &availableModelsAdminService{stubAdminService: newStubAdminService(), account: service.Account{ + ID: 1003, Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Credentials: map[string]any{"upstream_kind": "new_api", "base_url": "https://saved.example", "api_key": "synthetic-key"}, + }} + payload := map[string]any{"platform": "gateway", "type": "gateway", "upstream_kind": "new_api", + "base_url": "https://draft.example", "api_key": "synthetic-key"} + want := http.StatusBadRequest + switch scenario { + case "observer": + payload["account_id"] = 1003 + want = http.StatusForbidden + case "proxy": + payload["proxy_id"] = 7 + case "invalid-kind": + payload["upstream_kind"] = "other" + case "missing-key": + delete(payload, "api_key") + } + upstream := &syncUpstreamHTTPUpstream{} + router := setupSyncUpstreamModelsRouter(&gatewayPreviewAdminService{availableModelsAdminService: svc}, upstream) + body, err := json.Marshal(payload) + require.NoError(t, err) + req := httptest.NewRequest(http.MethodPost, "/api/v1/admin/accounts/models/sync-upstream-preview", strings.NewReader(string(body))) + req.Header.Set("Content-Type", "application/json") + if scenario == "observer" { + req = req.WithContext(service.WithObserverScope(req.Context(), []int64{1})) + } + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + require.Equal(t, want, rec.Code, rec.Body.String()) + require.Empty(t, upstream.requests) + }) + } +} diff --git a/backend/internal/repository/account_repo_upstream_model_sync_integration_test.go b/backend/internal/repository/account_repo_upstream_model_sync_integration_test.go index 2dadb9336fde..8902247ef54e 100644 --- a/backend/internal/repository/account_repo_upstream_model_sync_integration_test.go +++ b/backend/internal/repository/account_repo_upstream_model_sync_integration_test.go @@ -88,6 +88,40 @@ func TestApplyUpstreamModelsPreservesCredentialsAndInvalidatesScheduler(t *testi require.Len(t, cache.setAccounts, 1, "a skipped CAS must not publish a stale scheduler snapshot") } +func TestGatewayUpstreamModelsPersistOnlyAccountMapping(t *testing.T) { + for _, kind := range []string{"new_api", "sub2api"} { + t.Run(kind, func(t *testing.T) { + ctx := t.Context() + tx := testEntTx(t) + repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil) + account := mustCreateAccount(t, tx.Client(), &service.Account{ + Name: "gateway-model-sync", Platform: service.PlatformGateway, Type: service.AccountTypeGateway, + Credentials: map[string]any{"upstream_kind": kind, "api_key": "synthetic-key", "base_url": "https://relay.example", + "unrelated": map[string]any{"keep": true}, "model_mapping": map[string]any{"old": "old"}}, + }) + group, err := tx.Client().Group.Create().SetName("gateway-model-group").SetPlatform(service.PlatformOpenAI).Save(ctx) + require.NoError(t, err) + require.NoError(t, repo.BindGroups(ctx, account.ID, []int64{group.ID})) + beforeGroup, err := tx.Client().Group.Get(ctx, group.ID) + require.NoError(t, err) + expected, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + applied, err := repo.UpdateUpstreamModelMappingIfUnchanged(ctx, expected, map[string]string{"live": "live", "public": "live"}) + require.NoError(t, err) + require.True(t, applied) + latest, err := repo.GetByID(ctx, account.ID) + require.NoError(t, err) + require.Equal(t, "synthetic-key", latest.GetCredential("api_key")) + require.Equal(t, map[string]any{"keep": true}, latest.Credentials["unrelated"]) + require.Equal(t, map[string]any{"live": "live", "public": "live"}, latest.Credentials["model_mapping"]) + require.Equal(t, []int64{group.ID}, latest.GroupIDs) + afterGroup, err := tx.Client().Group.Get(ctx, group.ID) + require.NoError(t, err) + require.Equal(t, beforeGroup.ModelAllowlist, afterGroup.ModelAllowlist, "fetch/apply must never distribute models into groups") + }) + } +} + func TestOAuthDegradationNativeModelSyncFencesAccountAvailabilityChanges(t *testing.T) { for _, change := range []string{"scheduling paused", "status changed"} { t.Run(change, func(t *testing.T) { diff --git a/backend/internal/service/gateway_account_management_test.go b/backend/internal/service/gateway_account_management_test.go index 0420cee59e62..619c32e41865 100644 --- a/backend/internal/service/gateway_account_management_test.go +++ b/backend/internal/service/gateway_account_management_test.go @@ -108,6 +108,8 @@ func TestGatewayManagementCreateValidatesBeforeWritesAndBindsExplicitGroups(t *t func TestGatewayManagementUpdatePreservesKeyAndRejectsIdentityConversion(t *testing.T) { a := gatewayManagementFixture() + a.Credentials["model_mapping"] = map[string]any{"public": "upstream"} + a.Credentials["unknown_option"] = map[string]any{"keep": true} repo := &gatewayManagementAtomicRepo{accountRepoStubForBulkUpdate: &accountRepoStubForBulkUpdate{getByIDAccounts: map[int64]*Account{959: a}}} svc := &adminServiceImpl{accountRepo: repo} updated, err := svc.UpdateAccount(context.Background(), 959, &UpdateAccountInput{ @@ -116,6 +118,14 @@ func TestGatewayManagementUpdatePreservesKeyAndRejectsIdentityConversion(t *test require.Equal(t, 1, repo.transactions) require.Equal(t, "synthetic-key", updated.Credentials["api_key"]) require.Equal(t, "new_api", updated.Credentials["upstream_kind"]) + require.Equal(t, map[string]any{"public": "upstream"}, updated.Credentials["model_mapping"]) + require.Equal(t, map[string]any{"keep": true}, updated.Credentials["unknown_option"]) + _, err = svc.UpdateAccount(context.Background(), 959, &UpdateAccountInput{Credentials: map[string]any{"api_key": "rotated-synthetic-key"}}) + require.NoError(t, err) + _, err = svc.UpdateAccount(context.Background(), 959, &UpdateAccountInput{GroupIDs: &[]int64{}}) + require.NoError(t, err) + require.Equal(t, map[string]any{"public": "upstream"}, a.Credentials["model_mapping"]) + require.Equal(t, map[string]any{"keep": true}, a.Credentials["unknown_option"]) 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) diff --git a/backend/internal/service/gateway_messages_selection_test.go b/backend/internal/service/gateway_messages_selection_test.go index ef19bcb6db69..aac689ca0aea 100644 --- a/backend/internal/service/gateway_messages_selection_test.go +++ b/backend/internal/service/gateway_messages_selection_test.go @@ -194,6 +194,27 @@ func TestGatewayProtocolCatalogFollowsLiveBindings(t *testing.T) { require.Empty(t, svc.GetAvailableModels(ctx, &base.group.ID, PlatformOpenAI)) } +func TestGatewayProtocolCatalogSavedModelsAndGroupPrecedence(t *testing.T) { + base, ctx := gatewayProtocolFixture(PlatformOpenAI) + base.account.Credentials["model_mapping"] = map[string]any{"saved": "wire", "other": "other"} + svc := &GatewayService{accountRepo: &gatewayMessagesCandidateRepo{gatewayProtocolAdmissionRepo: base}} + models, err := svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformOpenAI) + require.NoError(t, err) + require.Equal(t, []string{"other", "saved"}, models, "saved IDs replace platform defaults") + base.group.ModelAllowlist = GroupModelAllowlist{Enabled: true, Models: []string{"saved"}} + models, err = svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformOpenAI) + require.NoError(t, err) + require.Equal(t, []string{"saved"}, models) + base.account.Credentials["model_mapping"] = map[string]any{"*": "wire"} + models, err = svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformOpenAI) + require.NoError(t, err) + require.Equal(t, []string{"saved"}, models, "explicit group IDs seed wildcard account mappings") + base.account.AccountGroups[0].AllowedModels = []string{"other"} + models, err = svc.GetGroupModelCatalog(ctx, base.group.ID, PlatformOpenAI) + require.NoError(t, err) + require.Empty(t, models, "a fetched catalog must not bypass binding admission") +} + func TestGatewayProtocolOpenAIChannelModelKeepsBinding(t *testing.T) { base, ctx := gatewayProtocolFixture(PlatformOpenAI) ctx = WithGatewayOpenAISelection(ctx, "public", "public") diff --git a/backend/internal/service/gateway_model_catalog.go b/backend/internal/service/gateway_model_catalog.go index 02da6b61fa9a..cdadc135818b 100644 --- a/backend/internal/service/gateway_model_catalog.go +++ b/backend/internal/service/gateway_model_catalog.go @@ -77,6 +77,11 @@ func (catalog gatewayModelCatalog) directModels(target string) []string { for name := range account.GetModelMapping() { models = append(models, name) } + // Concrete group entries also seed wildcard account mappings. The same + // admission below remains authoritative for both group and account policy. + if group.ModelAllowlist.Enabled { + models = append(models, group.ModelAllowlist.Models...) + } if len(models) == 0 { models = append(models, group.ModelAllowlist.Models...) if !IsMultiProtocolAPIKeyProvider(target) { diff --git a/backend/internal/service/gateway_upstream_models_test.go b/backend/internal/service/gateway_upstream_models_test.go new file mode 100644 index 000000000000..6a4c18b2698d --- /dev/null +++ b/backend/internal/service/gateway_upstream_models_test.go @@ -0,0 +1,124 @@ +//go:build unit + +package service + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestGatewayUpstreamModelsDiscoveryAndApply(t *testing.T) { + for _, kind := range []string{"new_api", "sub2api"} { + for _, apply := range []bool{false, true} { + t.Run(kind+map[bool]string{false: "/discovery", true: "/apply"}[apply], func(t *testing.T) { + svc, repo, upstream := modelMappingSyncFixture(http.StatusOK, `{"data":[{"id":"new"},{"id":"new"}]}`) + readOnlyRepo := &batchWhitelistReadOnlyRepo{upstreamModelMappingRepoStub: repo} + svc.accountRepo = readOnlyRepo + a := repo.account + a.Platform, a.Type = PlatformGateway, AccountTypeGateway + a.Credentials["upstream_kind"] = kind + a.Credentials["unrelated"] = "keep" + proxyID := int64(7) + a.ProxyID = &proxyID + a.Proxy = &Proxy{ID: proxyID, Protocol: "http", Host: "proxy.example", Port: 8080} + before := cloneTestCredentials(a.Credentials) + // Record metadata/health writes separately from explicit mapping + // application. Discovery must only issue the authenticated listing. + catalog, err := svc.SyncUpstreamModelCatalogWithOptions(context.Background(), a, UpstreamModelSyncOptions{Apply: apply}) + require.NoError(t, err) + require.Equal(t, []string{"new"}, catalog.Models) + require.Equal(t, "upstream", catalog.DiscoverySource) + require.Len(t, upstream.requests, 1, "no provider registry request") + require.Equal(t, "https://provider.example/v1/models", upstream.lastReq.URL.String()) + require.Equal(t, http.MethodGet, upstream.lastReq.Method) + require.Equal(t, "Bearer test-key", upstream.lastReq.Header.Get("Authorization")) + require.Equal(t, "http://proxy.example:8080", upstream.lastProxyURL) + require.Equal(t, before, a.Credentials) + require.Zero(t, repo.claimCalls) + require.Zero(t, readOnlyRepo.extraWrites.Load()) + require.Zero(t, readOnlyRepo.credentialWrites.Load()) + require.Zero(t, readOnlyRepo.authErrors.Load()) + require.Zero(t, readOnlyRepo.tempUnsched.Load()) + if apply { + require.True(t, catalog.Applied) + require.Equal(t, map[string]string{"new": "new", "public-new": "new"}, repo.mapping) + require.Equal(t, 1, repo.applyCalls) + } else { + require.Zero(t, repo.applyCalls) + } + }) + } + } +} + +func cloneTestCredentials(in map[string]any) map[string]any { + out := make(map[string]any, len(in)) + for key, value := range in { + out[key] = value + } + return out +} + +func TestGatewayUpstreamModelsRejectInvalidConnection(t *testing.T) { + for _, scenario := range []string{"kind", "key", "http", "userinfo", "query", "fragment", "allowlist", "private", "proxy", "type"} { + t.Run(scenario, func(t *testing.T) { + a := gatewayManagementFixture() + upstream := &httpUpstreamRecorder{} + svc := &AccountTestService{httpUpstream: upstream, cfg: upstreamModelSyncTestConfig()} + switch scenario { + case "kind": + a.Credentials["upstream_kind"] = "other" + case "key": + a.Credentials["api_key"] = "" + case "http": + a.Credentials["base_url"] = "http://gateway.example" + case "userinfo": + a.Credentials["base_url"] = "https://user:secret@gateway.example" + case "query": + a.Credentials["base_url"] = "https://gateway.example?key=secret" + case "fragment": + a.Credentials["base_url"] = "https://gateway.example/#secret" + case "allowlist": + svc.cfg.Security.URLAllowlist.Enabled = true + svc.cfg.Security.URLAllowlist.UpstreamHosts = []string{"allowed.example"} + case "private": + a.Credentials["base_url"] = "https://127.0.0.1" + svc.cfg.Security.URLAllowlist.Enabled = true + svc.cfg.Security.URLAllowlist.UpstreamHosts = []string{"127.0.0.1"} + case "proxy": + id := int64(7) + a.ProxyID = &id + case "type": + a.Type = AccountTypeAPIKey + } + _, err := svc.SyncUpstreamModelCatalog(context.Background(), a) + require.Error(t, err) + require.Empty(t, upstream.requests) + }) + } +} + +func TestGatewayUpstreamModelsFailureKeepsMapping(t *testing.T) { + for _, status := range []int{http.StatusUnauthorized, http.StatusTooManyRequests, http.StatusBadGateway} { + svc, repo, _ := modelMappingSyncFixture(status, `{"error":"private-detail"}`) + repo.account.Platform, repo.account.Type = PlatformGateway, AccountTypeGateway + repo.account.Credentials["upstream_kind"] = "sub2api" + _, err := svc.SyncUpstreamModelCatalogWithOptions(context.Background(), repo.account, UpstreamModelSyncOptions{Apply: true}) + require.Error(t, err) + require.Zero(t, repo.applyCalls) + } + for _, body := range []string{`not-json`, `{"data":[]}`, `{"data":[{"id":"new"}],"has_more":true}`} { + svc, repo, upstream := modelMappingSyncFixture(http.StatusOK, body) + repo.account.Platform, repo.account.Type = PlatformGateway, AccountTypeGateway + repo.account.Credentials["upstream_kind"] = "new_api" + upstream.resp.Body = io.NopCloser(strings.NewReader(body)) + catalog, err := svc.SyncUpstreamModelCatalogWithOptions(context.Background(), repo.account, UpstreamModelSyncOptions{Apply: true}) + require.True(t, err != nil || catalog.Skipped == "unverified_catalog") + require.Zero(t, repo.applyCalls) + } +} diff --git a/backend/internal/service/upstream_models.go b/backend/internal/service/upstream_models.go index 2d0ad2e3f03a..08fbf9ab59c5 100644 --- a/backend/internal/service/upstream_models.go +++ b/backend/internal/service/upstream_models.go @@ -237,6 +237,11 @@ func visibleUpstreamModelIDs(account *Account, models []string) []string { // snapshot. When no model is complete, the existing account snapshot is left // untouched. func (s *AccountTestService) SyncUpstreamModelCatalog(ctx context.Context, account *Account) (*UpstreamModelCatalog, error) { + // A gateway aggregates providers. Discovery must neither infer provider + // capabilities nor write metadata/health state; only explicit apply saves IDs. + if account != nil && (account.IsGateway() || account.Platform == PlatformGateway) { + return s.fetchWhitelistCatalog(ctx, account) + } fetched, err := s.fetchUpstreamModelListWithObservation(ctx, account) var ( models []string @@ -1035,6 +1040,8 @@ func listVertexGeminiPublisherModels(location string, fetchPage func(page int, l func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, account *Account) (*http.Request, error) { switch { + case account.IsGateway() || account.Platform == PlatformGateway: + return s.buildGatewayUpstreamModelsRequest(ctx, account) case account.Platform == PlatformAntigravity: return s.buildAntigravityAPIKeyModelsRequest(ctx, account) case account.IsGrok(): @@ -1053,6 +1060,26 @@ func (s *AccountTestService) buildUpstreamModelsRequest(ctx context.Context, acc } } +func (s *AccountTestService) buildGatewayUpstreamModelsRequest(ctx context.Context, account *Account) (*http.Request, error) { + if err := ValidateGatewayAccountIdentity(account.Platform, account.Type, account.Credentials); err != nil { + return nil, newUpstreamModelSyncConfigError("Invalid gateway account credentials", err) + } + if account.ProxyID != nil && *account.ProxyID > 0 && account.Proxy == nil { + return nil, newUpstreamModelSyncConfigError("Selected proxy is unavailable", nil) + } + baseURL, err := s.validateUpstreamBaseURL(account.GetCredential("base_url")) + if err != nil { + return nil, newUpstreamModelSyncConfigError("Invalid gateway base URL", err) + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, buildV1ModelsURL(baseURL), nil) + if err != nil { + return nil, newUpstreamModelSyncConfigError("Invalid gateway model list URL", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(account.GetCredential("api_key"))) + return req, nil +} + func (s *AccountTestService) buildGrokUpstreamModelsRequest(ctx context.Context, account *Account) (*http.Request, error) { if account == nil { return nil, newUpstreamModelSyncConfigError("Account is required", nil) diff --git a/frontend/src/api/admin/accounts.ts b/frontend/src/api/admin/accounts.ts index bfaf8b93bfac..33e8288106ce 100644 --- a/frontend/src/api/admin/accounts.ts +++ b/frontend/src/api/admin/accounts.ts @@ -685,6 +685,8 @@ export async function syncUpstreamModels( export interface SyncUpstreamPreviewParams { platform: string type: string + upstream_kind?: 'sub2api' | 'new_api' + account_id?: number base_url?: string api_key: string proxy_id?: number diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 95b7d122e1f4..a35c96afd96b 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -280,6 +280,8 @@ + @@ -4449,6 +4451,7 @@ import ProxySelector from '@/components/common/ProxySelector.vue' import ProxyAdBanner from '@/components/common/ProxyAdBanner.vue' import GroupSelector from '@/components/common/GroupSelector.vue' import ModelWhitelistSelector from '@/components/account/ModelWhitelistSelector.vue' +import GatewayModelSettings from '@/components/account/GatewayModelSettings.vue' import AccountAutoBPSSection from '@/components/account/AccountAutoBPSSection.vue' import QuotaLimitCard from '@/components/account/QuotaLimitCard.vue' import Toggle from '@/components/common/Toggle.vue' @@ -5004,6 +5007,11 @@ const openAICompactModelMappings = ref([]) const modelRestrictionMode = ref<'whitelist' | 'mapping'>('whitelist') const allowedModels = ref([]) const upstreamModelsPreviewed = ref(false) +const gatewaySyncCredentials = computed(() => gatewayApiKey.value.trim() ? { + platform: 'gateway', type: 'gateway', upstream_kind: gatewayKind.value, + base_url: gatewayBaseUrl.value.trim(), api_key: gatewayApiKey.value.trim(), + proxy_id: authStore.isObserver ? undefined : form.proxy_id ?? undefined +} : undefined) const DEFAULT_POOL_MODE_RETRY_COUNT = 3 const MAX_POOL_MODE_RETRY_COUNT = 10 const DEFAULT_POOL_MODE_RETRY_STATUS_CODES = [401, 403, 429] @@ -6558,7 +6566,8 @@ const handleSubmit = async () => { await createAccountAndFinish('gateway', 'gateway', { upstream_kind: gatewayKind.value, base_url: gatewayBaseUrl.value, - api_key: gatewayApiKey.value + api_key: gatewayApiKey.value, + model_mapping: buildModelMappingObject('combined', allowedModels.value, modelMappings.value) ?? {} }) return } diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index 3e17e759925d..acd41b11bb30 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -33,6 +33,8 @@ +
@@ -3921,6 +3923,7 @@ import ProxySelector from '@/components/common/ProxySelector.vue' import ProxyAdBanner from '@/components/common/ProxyAdBanner.vue' import GroupSelector from '@/components/common/GroupSelector.vue' import ModelWhitelistSelector from '@/components/account/ModelWhitelistSelector.vue' +import GatewayModelSettings from '@/components/account/GatewayModelSettings.vue' import AccountGroupModelLimits from '@/components/account/AccountGroupModelLimits.vue' import AccountAutoBPSSection from '@/components/account/AccountAutoBPSSection.vue' import { @@ -5254,6 +5257,12 @@ const loadModelRestrictionFromMapping = (rawMapping?: Record) = const buildModelRestrictionMapping = () => buildModelMappingObject('combined', allowedModels.value, modelMappings.value) +const gatewaySyncCredentials = computed(() => editingAccount.value?.type === 'gateway' ? { + platform: 'gateway', type: 'gateway', upstream_kind: gatewayKind.value, + account_id: editingAccount.value.id, base_url: editBaseUrl.value.trim(), api_key: editApiKey.value.trim(), + proxy_id: authStore.isObserver ? undefined : form.proxy_id ?? undefined +} : undefined) + const applyOpenAIModelMappingCredentials = (credentials: Record) => { if (editingAccount.value?.type === 'oauth' && !isSparkShadow.value) { credentials.model_mapping_mode = openaiModelAliases.value ? 'aliases' : 'whitelist' @@ -5776,6 +5785,7 @@ const syncFormFromAccount = (newAccount: Account | null) => { } else if (newAccount.type === 'gateway') { gatewayKind.value = newAccount.credentials?.upstream_kind === 'new_api' ? 'new_api' : 'sub2api' editBaseUrl.value = String(newAccount.credentials?.base_url || '') + loadModelRestrictionFromMapping(newAccount.credentials?.model_mapping as Record | undefined) } else if (newAccount.type === 'upstream' && newAccount.credentials) { const credentials = newAccount.credentials as Record editBaseUrl.value = (credentials.base_url as string) || '' @@ -6755,6 +6765,7 @@ const handleSubmit = async () => { updatePayload.credentials = { upstream_kind: gatewayKind.value, base_url: editBaseUrl.value.trim(), + model_mapping: buildModelRestrictionMapping() ?? {}, ...(editApiKey.value.trim() ? { api_key: editApiKey.value.trim() } : {}) } if (gatewayKind.value === 'sub2api') updatePayload.upstream_billing_probe_enabled = upstreamBillingAutoProbeEnabled.value diff --git a/frontend/src/components/account/GatewayModelSettings.vue b/frontend/src/components/account/GatewayModelSettings.vue new file mode 100644 index 000000000000..536b255e0a7d --- /dev/null +++ b/frontend/src/components/account/GatewayModelSettings.vue @@ -0,0 +1,33 @@ + + + diff --git a/frontend/src/components/account/ModelWhitelistSelector.vue b/frontend/src/components/account/ModelWhitelistSelector.vue index e0f7d60fd698..82ed377fbf6c 100644 --- a/frontend/src/components/account/ModelWhitelistSelector.vue +++ b/frontend/src/components/account/ModelWhitelistSelector.vue @@ -192,6 +192,8 @@ watch( () => props.accountId, () => props.syncCredentials?.platform, () => props.syncCredentials?.type, + () => props.syncCredentials?.upstream_kind, + () => props.syncCredentials?.account_id, () => props.syncCredentials?.base_url, () => props.syncCredentials?.api_key, () => props.syncCredentials?.proxy_id diff --git a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts index a9aa724283f8..bac924b09bb4 100644 --- a/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/CreateAccountModal.spec.ts @@ -2176,21 +2176,30 @@ describe('mature provider import entry', () => { }) }) -it('creates a cross-platform gateway with the selected provider and one calling key', async () => { +it.each(['new_api', 'sub2api'])('creates a %s gateway with editable account models and one calling key', async (kind) => { const wrapper = mountModal() await wrapper.get('[data-testid="platform-button-gateway"]').trigger('click') await wrapper.get('[data-tour="account-form-name"]').setValue('fixture gateway') const fields = wrapper.get('[data-testid="gateway-account-fields"]') - await fields.get('select').setValue('new_api') + await fields.get('select').setValue(kind) await fields.get('input[type="url"]').setValue('https://relay.example.com') await fields.get('input[type="password"]').setValue('fixture-only') + const selector = wrapper.getComponent(ModelWhitelistSelectorStub) + expect(selector.props('syncCredentials')).toMatchObject({ + platform: 'gateway', type: 'gateway', upstream_kind: kind, + base_url: 'https://relay.example.com', api_key: 'fixture-only' + }) + selector.vm.$emit('update:modelValue', ['live']) + selector.vm.$emit('update:modelMappings', [{ from: 'public', to: 'live' }]) + await flushPromises() await wrapper.get('#create-account-form').trigger('submit.prevent') await flushPromises() expect(createAccountMock).toHaveBeenCalledWith(expect.objectContaining({ platform: 'gateway', type: 'gateway', credentials: expect.objectContaining({ - upstream_kind: 'new_api', base_url: 'https://relay.example.com', api_key: 'fixture-only' + upstream_kind: kind, base_url: 'https://relay.example.com', api_key: 'fixture-only', + model_mapping: { live: 'live', public: 'live' } }) })) }) diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts index 4e2f4f932a55..fb6abc9d2b7b 100644 --- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts @@ -100,6 +100,7 @@ const BaseDialogStub = defineComponent({ const ModelWhitelistSelectorStub = defineComponent({ name: 'ModelWhitelistSelector', props: { + syncCredentials: Object, modelMappings: { type: Array, default: () => [] }, modelValue: { type: Array, @@ -356,6 +357,60 @@ function mountModal(account = buildAccount(), renderGroupSelector = false) { } describe('EditAccountModal', () => { + it('announces gateway model settings independently and shares persistent dismissal', async () => { + localStorage.removeItem('sub2api:new-feature-notices:v1:41') + const pinia = createPinia() + setActivePinia(pinia) + const notices = useNewFeatureNoticeStore() + notices.dismiss(41, NEW_FEATURE_NOTICES.crossPlatformGatewayAccounts) + const account = { ...buildAccount(), platform: 'gateway', type: 'gateway', + credentials: { upstream_kind: 'new_api', base_url: 'https://relay.example.com' } } as any + const wrapper = mountModal(account) + await flushPromises() + const badge = wrapper.findAllComponents(NewFeatureBadge).find(item => item.props('noticeId') === NEW_FEATURE_NOTICES.gatewayModelSync)! + expect(badge.find('button').exists()).toBe(true) + const sibling = mount(NewFeatureBadge, { props: { noticeId: NEW_FEATURE_NOTICES.gatewayModelSync, userId: 41 }, global: { plugins: [pinia] } }) + await badge.get('button').trigger('click') + expect(sibling.find('button').exists()).toBe(false) + wrapper.unmount() + sibling.unmount() + setActivePinia(createPinia()) + const reloaded = mountModal(account) + await flushPromises() + const reloadedBadge = reloaded.findAllComponents(NewFeatureBadge).find(item => item.props('noticeId') === NEW_FEATURE_NOTICES.gatewayModelSync)! + expect(reloadedBadge.find('button').exists()).toBe(false) + expect(useNewFeatureNoticeStore().isDismissed(41, NEW_FEATURE_NOTICES.crossPlatformGatewayAccounts)).toBe(true) + const future = mount(NewFeatureBadge, { props: { noticeId: 'fixture-future-gateway-notice-C', userId: 41 } }) + expect(future.find('button').exists()).toBe(true) + future.unmount() + }) + + it.each(['new_api', 'sub2api'])('keeps %s gateway models across connection and group edits', async (kind) => { + const account = { ...buildAccount(), platform: 'gateway', type: 'gateway', group_ids: [10], + credentials: { upstream_kind: kind, base_url: 'https://relay.example.com', + model_mapping: { live: 'live', public: 'live' }, unknown_option: { keep: true } } } as any + updateAccountMock.mockReset().mockResolvedValue(account) + checkMixedChannelRiskMock.mockReset().mockResolvedValue({ has_risk: false }) + const wrapper = mountModal(account) + await flushPromises() + const selector = wrapper.getComponent(ModelWhitelistSelectorStub) + expect(selector.props('modelValue')).toEqual(['live']) + expect(selector.props('modelMappings')).toEqual([{ from: 'public', to: 'live' }]) + const fields = wrapper.get('[data-testid="gateway-account-fields"]') + await fields.get('input[type="url"]').setValue('https://edited.example.com') + await fields.get('input[type="password"]').setValue('synthetic-new-key') + wrapper.getComponent(GroupSelectorStub).vm.$emit('update:modelValue', [20]) + await flushPromises() + expect(selector.props('syncCredentials')).toMatchObject({ account_id: account.id, + upstream_kind: kind, base_url: 'https://edited.example.com', api_key: 'synthetic-new-key' }) + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + await flushPromises() + expect(updateAccountMock.mock.calls[0]?.[1]).toMatchObject({ group_ids: [20], credentials: { + upstream_kind: kind, base_url: 'https://edited.example.com', api_key: 'synthetic-new-key', + model_mapping: account.credentials.model_mapping + } }) + }) + it('keeps the target platform announcement independent, shared and persistent', async () => { const noticeId = NEW_FEATURE_NOTICES.accountEditPlatform localStorage.removeItem('sub2api:new-feature-notices:v1:41') diff --git a/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts b/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts index 2f63c3497f63..e8db1a4544c2 100644 --- a/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts +++ b/frontend/src/components/account/__tests__/ModelWhitelistSelector.spec.ts @@ -105,6 +105,20 @@ function findModelRow(wrapper: ReturnType, modelId: string } describe('ModelWhitelistSelector', () => { + it.each(['new_api', 'sub2api'] as const)('fetches %s gateway preview into an editable whitelist and preserves live aliases', async (kind) => { + syncUpstreamModelsPreview.mockResolvedValue({ models: ['live', 'new'], discovery_source: 'upstream' }) + const credentials = { platform: 'gateway', type: 'gateway', upstream_kind: kind, + account_id: 46, api_key: '', base_url: 'https://draft.example', proxy_id: 7 } + const wrapper = mountSelector({ platform: 'gateway', modelValue: ['old'], + modelMappings: [{ from: 'public', to: 'live' }], syncCredentials: credentials }) + await syncButton(wrapper).trigger('click') + await flushPromises() + expect(syncUpstreamModelsPreview).toHaveBeenCalledWith(credentials) + expect(syncUpstreamModels).not.toHaveBeenCalled() + expect(wrapper.emitted('update:modelValue')?.at(-1)).toEqual([['live', 'new']]) + expect(wrapper.emitted('update:modelMappings')?.at(-1)).toEqual([[{ from: 'public', to: 'live' }]]) + }) + beforeEach(() => { copyToClipboard.mockClear() showError.mockReset() @@ -119,7 +133,7 @@ describe('ModelWhitelistSelector', () => { resetPlatformCatalog() }) - it.each(['anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'command_code', 'cline', 'mistral'])( + it.each(['gateway', 'anthropic', 'openai', 'gemini', 'antigravity', 'grok', 'kimi', 'zhipu', 'deepseek', 'minimax', 'opencode_go', 'command_code', 'cline', 'mistral'])( 'supports upstream sync for %s saved accounts and creation previews', (platform) => { const wrappers = [ diff --git a/frontend/src/constants/newFeatureNotices.ts b/frontend/src/constants/newFeatureNotices.ts index ef99f72337c5..03ada7d0986e 100644 --- a/frontend/src/constants/newFeatureNotices.ts +++ b/frontend/src/constants/newFeatureNotices.ts @@ -12,6 +12,7 @@ export const NEW_FEATURE_NOTICES = { channelConfig: 'channel-configuration-20261119', imageUsageBilling: 'image-usage-minimum-charge-20261119', crossPlatformGatewayAccounts: 'cross-platform-gateway-accounts', + gatewayModelSync: 'gateway-account-model-sync-20261122', newAPICostConversion: 'new-api-cost-conversion-20261119', accountOpsBalanceNotification: 'account-ops-per-account-balance-notification-20261119', channelUltrafastPricing: 'channel-ultrafast-pricing-initial-announcement', diff --git a/frontend/src/constants/platformCatalog.ts b/frontend/src/constants/platformCatalog.ts index bb988dec3a00..ffb04c7ae2ee 100644 --- a/frontend/src/constants/platformCatalog.ts +++ b/frontend/src/constants/platformCatalog.ts @@ -87,6 +87,7 @@ export function isKnownPlatform(platform: string | null | undefined): boolean { /** 与后端 buildUpstreamModelsRequest 支持的平台保持一致。 */ export function supportsUpstreamModelSync(platform: string | null | undefined): boolean { + if (platform?.trim().toLowerCase() === 'gateway') return true const spec = getPlatformSpec(platform?.trim().toLowerCase()) if (!spec) return false return !!spec.multi_protocol || ['anthropic', 'openai', 'gemini', 'antigravity', 'grok'].includes(spec.id) diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index 08ea21b4e16f..1c8473f69fa9 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -494,6 +494,13 @@