diff --git a/backend/dev-docs/API_KEY_ROTATION.md b/backend/dev-docs/API_KEY_ROTATION.md new file mode 100644 index 000000000..e3b89d94e --- /dev/null +++ b/backend/dev-docs/API_KEY_ROTATION.md @@ -0,0 +1,12 @@ +# API Key 手动轮转 + +在 **API 密钥** 页找到要更换的 Key,点击 **轮转** 并确认。服务端在原记录上生成替代密钥,不改变 Key ID、分组、状态、有效期、额度、用量或历史记录。 + +轮转成功后,旧 Key 不再用于新请求。请立即复制保存只显示一次的新 Key,并更新客户端配置。已禁用或过期的 Key 不会因轮转重新启用。如果没有保存新 Key,可以重新发起轮转。 + +## 接口 + +- `POST /api/v1/keys/:id/rotate`:使用登录会话认证,只能轮转自己名下的 Key;无请求体。 +- 请求头 `Idempotency-Key` 必填。每次发起新的轮转应使用新的操作 ID;重试同一次请求应复用原 ID。 +- 首次成功响应中,`data` 包含 `id`、`key_hint` 和新凭证 `key`。幂等重放只返回 `id` 与 `key_hint`,不会再次轮转,也不会返回完整 Key。 +- 响应设置 `Cache-Control: no-store`。列表和详情仍只返回掩码,不返回完整 Key。 diff --git a/backend/internal/handler/admin/account_codex_import.go b/backend/internal/handler/admin/account_codex_import.go index 833748893..d48d73240 100644 --- a/backend/internal/handler/admin/account_codex_import.go +++ b/backend/internal/handler/admin/account_codex_import.go @@ -163,7 +163,7 @@ func (h *AccountHandler) importCodexSessions(ctx context.Context, req CodexSessi Items: make([]CodexSessionImportItem, 0, len(entries)), } - existingAccounts, err := h.listAccountsFiltered(ctx, service.PlatformOpenAI, service.AccountTypeOAuth, "", "", 0, "", "created_at", "desc") + existingAccounts, err := h.listAccountsFiltered(ctx, service.PlatformOpenAI, service.AccountTypeOAuth, "", "", 0, "", "", "created_at", "desc") if err != nil { return result, err } diff --git a/backend/internal/handler/admin/account_data.go b/backend/internal/handler/admin/account_data.go index ea1cff840..5d4379c0e 100644 --- a/backend/internal/handler/admin/account_data.go +++ b/backend/internal/handler/admin/account_data.go @@ -506,12 +506,12 @@ func (h *AccountHandler) listAllProxies(ctx context.Context) ([]service.Proxy, e return out, nil } -func (h *AccountHandler) listAccountsFiltered(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode, sortBy, sortOrder string) ([]service.Account, error) { +func (h *AccountHandler) listAccountsFiltered(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode, model, sortBy, sortOrder string) ([]service.Account, error) { page := 1 pageSize := dataPageCap var out []service.Account for { - items, total, err := h.adminService.ListAccounts(ctx, page, pageSize, platform, accountType, status, search, groupID, privacyMode, sortBy, sortOrder) + items, total, err := h.adminService.ListAccounts(ctx, page, pageSize, platform, accountType, status, search, groupID, privacyMode, model, sortBy, sortOrder) if err != nil { return nil, err } @@ -544,12 +544,16 @@ func (h *AccountHandler) resolveExportAccounts(ctx context.Context, ids []int64, accountType := c.Query("type") status := c.Query("status") privacyMode := strings.TrimSpace(c.Query("privacy_mode")) + modelFilter := strings.TrimSpace(c.Query("model")) search := strings.TrimSpace(c.Query("search")) sortBy := c.DefaultQuery("sort_by", "name") sortOrder := c.DefaultQuery("sort_order", "asc") if len(search) > 100 { search = search[:100] } + if len(modelFilter) > 100 { + modelFilter = modelFilter[:100] + } groupID := int64(0) if groupIDStr := c.Query("group"); groupIDStr != "" { @@ -564,7 +568,7 @@ func (h *AccountHandler) resolveExportAccounts(ctx context.Context, ids []int64, } } - return h.listAccountsFiltered(ctx, platform, accountType, status, search, groupID, privacyMode, sortBy, sortOrder) + return h.listAccountsFiltered(ctx, platform, accountType, status, search, groupID, privacyMode, modelFilter, sortBy, sortOrder) } func (h *AccountHandler) resolveExportProxies(ctx context.Context, accounts []service.Account) ([]service.Proxy, error) { diff --git a/backend/internal/handler/admin/account_handler.go b/backend/internal/handler/admin/account_handler.go index f2a206c79..49742c89a 100644 --- a/backend/internal/handler/admin/account_handler.go +++ b/backend/internal/handler/admin/account_handler.go @@ -193,6 +193,7 @@ type BulkUpdateAccountFilters struct { Group string `json:"group"` Search string `json:"search"` PrivacyMode string `json:"privacy_mode"` + Model string `json:"model"` } // CheckMixedChannelRequest represents check mixed channel risk request @@ -629,14 +630,14 @@ func (h *AccountHandler) listAccountSchedulerScoreFilterPool( ctx context.Context, platform, accountType, status, search string, groupID int64, - privacyMode string, + privacyMode, model string, ) []service.Account { if h.adminService == nil || (platform != "" && platform != service.PlatformOpenAI) { return nil } // 池只用于 OpenAI 分数计算(非 OpenAI 账号会在打分时被丢弃), // 无论列表页平台过滤为何,查询一律限定 openai,避免无过滤时全表扫描。 - accounts, err := h.adminService.ListAccountsForSchedulerScoreFilter(ctx, service.PlatformOpenAI, accountType, status, search, groupID, privacyMode) + accounts, err := h.adminService.ListAccountsForSchedulerScoreFilter(ctx, service.PlatformOpenAI, accountType, status, search, groupID, privacyMode, model) if err != nil { slog.Warn("openai_scheduler_filter_score_pool_failed", "error", err) return nil @@ -653,6 +654,7 @@ func (h *AccountHandler) List(c *gin.Context) { status := c.Query("status") search := c.Query("search") privacyMode := strings.TrimSpace(c.Query("privacy_mode")) + modelFilter := strings.TrimSpace(c.Query("model")) sortBy := c.DefaultQuery("sort_by", "name") sortOrder := c.DefaultQuery("sort_order", "asc") // 标准化和验证 search 参数 @@ -660,6 +662,9 @@ func (h *AccountHandler) List(c *gin.Context) { if len(search) > 100 { search = search[:100] } + if len(modelFilter) > 100 { + modelFilter = modelFilter[:100] + } lite := parseBoolQueryWithDefault(c.Query("lite"), false) // 调度分需要跨候选池批量打分并读取负载,默认列表不计算;只有前端列可见时才显式开启。 includeSchedulerScore := parseBoolQueryWithDefault(c.Query("include_scheduler_score"), false) @@ -682,7 +687,7 @@ func (h *AccountHandler) List(c *gin.Context) { } } - accounts, total, err := h.adminService.ListAccounts(c.Request.Context(), page, pageSize, platform, accountType, status, search, groupID, privacyMode, sortBy, sortOrder) + accounts, total, err := h.adminService.ListAccounts(c.Request.Context(), page, pageSize, platform, accountType, status, search, groupID, privacyMode, modelFilter, sortBy, sortOrder) if err != nil { response.ErrorFrom(c, err) return @@ -727,7 +732,7 @@ func (h *AccountHandler) List(c *gin.Context) { } } if includeSchedulerScore && pageHasOpenAIAccounts { - schedulerFilterPool := h.listAccountSchedulerScoreFilterPool(c.Request.Context(), platform, accountType, status, search, groupID, privacyMode) + schedulerFilterPool := h.listAccountSchedulerScoreFilterPool(c.Request.Context(), platform, accountType, status, search, groupID, privacyMode, modelFilter) schedulerScores, schedulerGroupScores = h.buildOpenAIAccountSchedulerScores(c.Request.Context(), accounts, schedulerFilterPool) } @@ -862,7 +867,7 @@ func (h *AccountHandler) List(c *gin.Context) { CurrentRPM: item.CurrentRPM, } } - etag := buildAccountsListETag(compact, total, page, pageSize, platform, accountType, status, search, true) + etag := buildAccountsListETag(compact, total, page, pageSize, platform, accountType, status, search, modelFilter, true) if etag != "" { c.Header("ETag", etag) c.Header("Vary", "If-None-Match") @@ -875,7 +880,7 @@ func (h *AccountHandler) List(c *gin.Context) { return } - etag := buildAccountsListETag(result, total, page, pageSize, platform, accountType, status, search, false) + etag := buildAccountsListETag(result, total, page, pageSize, platform, accountType, status, search, modelFilter, false) if etag != "" { c.Header("ETag", etag) c.Header("Vary", "If-None-Match") @@ -892,7 +897,7 @@ func buildAccountsListETag[T any]( items []T, total int64, page, pageSize int, - platform, accountType, status, search string, + platform, accountType, status, search, model string, lite bool, ) string { payload := struct { @@ -903,6 +908,7 @@ func buildAccountsListETag[T any]( AccountType string `json:"type"` Status string `json:"status"` Search string `json:"search"` + Model string `json:"model"` Lite bool `json:"lite"` Items []T `json:"items"` }{ @@ -913,6 +919,7 @@ func buildAccountsListETag[T any]( AccountType: accountType, Status: status, Search: search, + Model: model, Lite: lite, Items: items, } @@ -2416,6 +2423,10 @@ func toServiceBulkUpdateAccountFilters(filters *BulkUpdateAccountFilters) *servi if filters == nil { return nil } + model := strings.TrimSpace(filters.Model) + if len(model) > 100 { + model = model[:100] + } return &service.BulkUpdateAccountFilters{ Platform: filters.Platform, Type: filters.Type, @@ -2423,6 +2434,7 @@ func toServiceBulkUpdateAccountFilters(filters *BulkUpdateAccountFilters) *servi Group: filters.Group, Search: filters.Search, PrivacyMode: filters.PrivacyMode, + Model: model, } } @@ -3074,7 +3086,7 @@ func (h *AccountHandler) BatchRefreshTier(c *gin.Context) { accounts := make([]*service.Account, 0) if len(req.AccountIDs) == 0 { - allAccounts, _, err := h.adminService.ListAccounts(ctx, 1, 10000, "gemini", "oauth", "", "", 0, "", "name", "asc") + allAccounts, _, err := h.adminService.ListAccounts(ctx, 1, 10000, "gemini", "oauth", "", "", 0, "", "", "name", "asc") if err != nil { response.ErrorFrom(c, err) return diff --git a/backend/internal/handler/admin/account_handler_list_test.go b/backend/internal/handler/admin/account_handler_list_test.go index f4304eb93..3265762bb 100644 --- a/backend/internal/handler/admin/account_handler_list_test.go +++ b/backend/internal/handler/admin/account_handler_list_test.go @@ -405,3 +405,56 @@ func TestAccountHandlerListSchedulerScoreIgnoresPagination(t *testing.T) { require.Less(t, payload.Data.Items[0].SchedulerScore.BaseScore, 3.75) require.Empty(t, payload.Data.Items[0].SchedulerScores) } + +func TestAccountHandlerListFiltersByModelAndScopesETag(t *testing.T) { + router, adminSvc := setupAccountListRouter() + adminSvc.accounts = []service.Account{{ + ID: 901, + Name: "model-filtered", + Platform: service.PlatformAnthropic, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + }} + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts?page=1&page_size=20&lite=1&model=%20claude-opus-5%20", nil) + router.ServeHTTP(rec, req) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "claude-opus-5", adminSvc.lastListAccounts.model, "模型参数应去空格后传给服务层") + modelETag := rec.Header().Get("ETag") + require.NotEmpty(t, modelETag) + + // 同一份账号数据在不同模型筛选下必须有不同的表示标识,避免缓存串用筛选结果。 + recUnfiltered := httptest.NewRecorder() + router.ServeHTTP(recUnfiltered, httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts?page=1&page_size=20&lite=1", nil)) + require.Equal(t, http.StatusOK, recUnfiltered.Code) + require.Empty(t, adminSvc.lastListAccounts.model) + require.NotEqual(t, modelETag, recUnfiltered.Header().Get("ETag")) + + rec304 := httptest.NewRecorder() + req304 := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts?page=1&page_size=20&lite=1&model=claude-opus-5", nil) + req304.Header.Set("If-None-Match", modelETag) + router.ServeHTTP(rec304, req304) + require.Equal(t, http.StatusNotModified, rec304.Code) +} + +func TestAccountHandlerListModelFilterScopesSchedulerScorePool(t *testing.T) { + router, adminSvc := setupAccountListRouter() + adminSvc.accounts = []service.Account{{ + ID: 902, + Name: "openai-model-filtered", + Platform: service.PlatformOpenAI, + Type: service.AccountTypeAPIKey, + Status: service.StatusActive, + Schedulable: true, + Concurrency: 10, + }} + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/accounts?page=1&page_size=20&include_scheduler_score=1&model=gpt-5.6", nil) + router.ServeHTTP(rec, req) + + require.Equal(t, http.StatusOK, rec.Code) + require.Equal(t, "gpt-5.6", adminSvc.lastListAccounts.model) +} diff --git a/backend/internal/handler/admin/account_upstream_billing_rates.go b/backend/internal/handler/admin/account_upstream_billing_rates.go index 5c3b322b7..7123e10fe 100644 --- a/backend/internal/handler/admin/account_upstream_billing_rates.go +++ b/backend/internal/handler/admin/account_upstream_billing_rates.go @@ -44,6 +44,7 @@ func (h *AccountHandler) GetUpstreamBillingRates(c *gin.Context) { search = search[:100] } privacyMode := strings.TrimSpace(c.Query("privacy_mode")) + modelFilter := strings.TrimSpace(c.Query("model")) sortBy := c.DefaultQuery("sort_by", "name") sortOrder := c.DefaultQuery("sort_order", "asc") @@ -61,9 +62,13 @@ func (h *AccountHandler) GetUpstreamBillingRates(c *gin.Context) { } } + if len(modelFilter) > 100 { + modelFilter = modelFilter[:100] + } + accounts, total, err := h.adminService.ListAccounts( c.Request.Context(), page, pageSize, platform, accountType, status, - search, groupID, privacyMode, sortBy, sortOrder, + search, groupID, privacyMode, modelFilter, sortBy, sortOrder, ) if err != nil { response.ErrorFrom(c, err) diff --git a/backend/internal/handler/admin/admin_service_stub_test.go b/backend/internal/handler/admin/admin_service_stub_test.go index c808d1a18..4073ce44f 100644 --- a/backend/internal/handler/admin/admin_service_stub_test.go +++ b/backend/internal/handler/admin/admin_service_stub_test.go @@ -58,6 +58,7 @@ type stubAdminService struct { search string groupID int64 privacyMode string + model string sortBy string sortOrder string calls int @@ -424,13 +425,14 @@ func (s *stubAdminService) BatchSetGroupRPMOverrides(_ context.Context, _ int64, return nil } -func (s *stubAdminService) ListAccounts(ctx context.Context, page, pageSize int, platform, accountType, status, search string, groupID int64, privacyMode string, sortBy, sortOrder string) ([]service.Account, int64, error) { +func (s *stubAdminService) ListAccounts(ctx context.Context, page, pageSize int, platform, accountType, status, search string, groupID int64, privacyMode, model, sortBy, sortOrder string) ([]service.Account, int64, error) { s.lastListAccounts.platform = platform s.lastListAccounts.accountType = accountType s.lastListAccounts.status = status s.lastListAccounts.search = search s.lastListAccounts.groupID = groupID s.lastListAccounts.privacyMode = privacyMode + s.lastListAccounts.model = model s.lastListAccounts.sortBy = sortBy s.lastListAccounts.sortOrder = sortOrder s.lastListAccounts.calls++ @@ -453,7 +455,7 @@ func (s *stubAdminService) ListAccounts(ctx context.Context, page, pageSize int, return accounts[start:end], int64(total), nil } -func (s *stubAdminService) ListAccountsForSchedulerScoreFilter(_ context.Context, platform, accountType, status, search string, groupID int64, privacyMode string) ([]service.Account, error) { +func (s *stubAdminService) ListAccountsForSchedulerScoreFilter(_ context.Context, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]service.Account, error) { s.schedulerScoreFilterCalls++ if s.accountSchedulerScoreFilterAccounts != nil { return s.accountSchedulerScoreFilterAccounts, nil diff --git a/backend/internal/handler/admin/user_handler.go b/backend/internal/handler/admin/user_handler.go index c050931b1..e875e317b 100644 --- a/backend/internal/handler/admin/user_handler.go +++ b/backend/internal/handler/admin/user_handler.go @@ -124,6 +124,7 @@ type BindUserAuthIdentityChannelRequest struct { // - attr[{id}]: filter by custom attribute value, e.g. attr[1]=company // - group_name: fuzzy filter by allowed group name // - api_key_group_id: filter by the exact group bound to the user's API keys +// - hide_enterprise_employees: when true, only list active enterprise owners func (h *UserHandler) List(c *gin.Context) { page, pageSize := response.ParsePagination(c) @@ -154,6 +155,7 @@ func (h *UserHandler) List(c *gin.Context) { } filters.EnterpriseID = id } + filters.HideEnterpriseEmployees = parseBoolQueryWithDefault(c.Query("hide_enterprise_employees"), false) sortBy := c.DefaultQuery("sort_by", "created_at") sortOrder := c.DefaultQuery("sort_order", "desc") if raw, ok := c.GetQuery("include_subscriptions"); ok { diff --git a/backend/internal/handler/admin/user_handler_hide_enterprise_employees_test.go b/backend/internal/handler/admin/user_handler_hide_enterprise_employees_test.go new file mode 100644 index 000000000..56a4b409a --- /dev/null +++ b/backend/internal/handler/admin/user_handler_hide_enterprise_employees_test.go @@ -0,0 +1,58 @@ +package admin + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +func TestAdminUserList_ParsesHideEnterpriseEmployees(t *testing.T) { + gin.SetMode(gin.TestMode) + cases := []struct { + name string + query string + want bool + }{ + {"missing defaults off", "", false}, + {"true", "?hide_enterprise_employees=true", true}, + {"one", "?hide_enterprise_employees=1", true}, + {"false", "?hide_enterprise_employees=false", false}, + {"zero", "?hide_enterprise_employees=0", false}, + {"invalid defaults off", "?hide_enterprise_employees=abc", false}, + {"empty defaults off", "?hide_enterprise_employees=", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + stub := &listUsersFilterStub{AdminService: newStubAdminService()} + r := gin.New() + h := NewUserHandler(stub, nil, nil, nil, nil, nil, nil) + r.GET("/admin/users", h.List) + + w := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodGet, "/admin/users"+tc.query, nil) + r.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code) + require.Equal(t, tc.want, stub.captured.HideEnterpriseEmployees) + }) + } +} + +func TestAdminUserList_HideEnterpriseEmployeesCombinesWithEnterpriseID(t *testing.T) { + gin.SetMode(gin.TestMode) + stub := &listUsersFilterStub{AdminService: newStubAdminService()} + r := gin.New() + h := NewUserHandler(stub, nil, nil, nil, nil, nil, nil) + r.GET("/admin/users", h.List) + + w := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodGet, "/admin/users?enterprise_id=7&hide_enterprise_employees=true", nil) + r.ServeHTTP(w, req) + + require.Equal(t, http.StatusOK, w.Code) + require.EqualValues(t, 7, stub.captured.EnterpriseID) + require.True(t, stub.captured.HideEnterpriseEmployees) +} diff --git a/backend/internal/handler/api_key_handler.go b/backend/internal/handler/api_key_handler.go index e913089e2..a0535c560 100644 --- a/backend/internal/handler/api_key_handler.go +++ b/backend/internal/handler/api_key_handler.go @@ -313,6 +313,45 @@ func (h *APIKeyHandler) Update(c *gin.Context) { response.Success(c, dto.APIKeyFromService(key).Localized(c.GetHeader("Accept-Language"))) } +// Rotate handles POST /api/v1/keys/:id/rotate. +func (h *APIKeyHandler) Rotate(c *gin.Context) { + subject, ok := middleware2.GetAuthSubjectFromContext(c) + if !ok { + response.Unauthorized(c, "User not authenticated") + return + } + keyID, err := strconv.ParseInt(c.Param("id"), 10, 64) + if err != nil || keyID <= 0 { + response.BadRequest(c, "Invalid key ID") + return + } + + c.Header("Cache-Control", "no-store") + operationID, err := service.NormalizeIdempotencyKey(c.GetHeader("Idempotency-Key")) + if err != nil { + response.ErrorFrom(c, err) + return + } + if operationID == "" { + response.ErrorFrom(c, service.ErrIdempotencyKeyRequired) + return + } + var credential string + executeUserIdempotentJSONWithTimeout(c, "user.api_keys.rotate", gin.H{"id": keyID}, service.DefaultWriteIdempotencyTTL(), 10*time.Second, func(ctx context.Context) (any, error) { + result, err := h.apiKeyService.Rotate(ctx, keyID, subject.UserID) + if err != nil { + return nil, err + } + credential = result.Key + return gin.H{"id": keyID, "key_hint": result.KeyHint}, nil + }, func(data any) any { + if result, ok := data.(gin.H); ok && credential != "" { + return gin.H{"id": result["id"], "key_hint": result["key_hint"], "key": credential} + } + return data + }) +} + // Delete handles deleting an API key // DELETE /api/v1/api-keys/:id func (h *APIKeyHandler) Delete(c *gin.Context) { diff --git a/backend/internal/handler/api_key_show_once_test.go b/backend/internal/handler/api_key_show_once_test.go index e4dd120d3..90833caa3 100644 --- a/backend/internal/handler/api_key_show_once_test.go +++ b/backend/internal/handler/api_key_show_once_test.go @@ -42,6 +42,27 @@ func (r *showOnceAPIKeyRepository) GetByID(_ context.Context, id int64) (*servic return key, nil } +func (r *showOnceAPIKeyRepository) GetKeyHashAndOwnerID(ctx context.Context, id int64) (string, int64, error) { + key, err := r.GetByID(ctx, id) + if err != nil { + return "", 0, err + } + return key.KeyHash, key.UserID, nil +} + +func (r *showOnceAPIKeyRepository) RotateCredential(ctx context.Context, id, userID int64, previousHash, credential string) error { + key, err := r.GetByID(ctx, id) + if err != nil { + return err + } + if key.UserID != userID || key.KeyHash != previousHash { + return service.ErrAPIKeyRotationConflict + } + key.KeyHash = service.HashAPIKey(credential) + key.KeyHint = service.MaskAPIKey(credential) + return nil +} + func (r *showOnceAPIKeyRepository) ExistsByKey(_ context.Context, credential string) (bool, error) { for _, key := range r.keys { if key.KeyHash == service.HashAPIKey(credential) { @@ -84,9 +105,44 @@ func newShowOnceAPIKeyRouter(t *testing.T, coordinator *service.IdempotencyCoord router.POST("/api/v1/api-keys", handler.Create) router.GET("/api/v1/api-keys", handler.List) router.GET("/api/v1/api-keys/:id", handler.GetByID) + router.POST("/api/v1/keys/:id/rotate", handler.Rotate) return router, repo } +func TestAPIKeyRotationShowsCredentialOnce(t *testing.T) { + store := newUserMemoryIdempotencyRepoStub() + coordinator := service.NewIdempotencyCoordinator(store, service.DefaultIdempotencyConfig()) + router, repo := newShowOnceAPIKeyRouter(t, coordinator) + created := showOnceAPIKeyRequest(router, http.MethodPost, "/api/v1/api-keys", `{"name":"rotate-once"}`, "create-key") + require.Equal(t, http.StatusOK, created.Code, created.Body.String()) + oldKey := gjson.GetBytes(created.Body.Bytes(), "data.key").String() + path := "/api/v1/keys/1/rotate" + missingHeader := showOnceAPIKeyRequest(router, http.MethodPost, path, "", "") + require.Equal(t, http.StatusBadRequest, missingHeader.Code, missingHeader.Body.String()) + require.Equal(t, service.HashAPIKey(oldKey), repo.keys[1].KeyHash) + rotated := showOnceAPIKeyRequest(router, http.MethodPost, path, "", "rotate-key") + require.Equal(t, http.StatusOK, rotated.Code, rotated.Body.String()) + require.Equal(t, "no-store", rotated.Header().Get("Cache-Control")) + credential := gjson.GetBytes(rotated.Body.Bytes(), "data.key").String() + require.NotEmpty(t, credential) + require.NotEqual(t, oldKey, credential) + hint := service.MaskAPIKey(credential) + require.Equal(t, hint, gjson.GetBytes(rotated.Body.Bytes(), "data.key_hint").String()) + for _, record := range store.data { + require.NotNil(t, record.ResponseBody) + require.NotContains(t, *record.ResponseBody, credential) + require.NotContains(t, *record.ResponseBody, service.HashAPIKey(credential)) + } + replayed := showOnceAPIKeyRequest(router, http.MethodPost, path, "", "rotate-key") + require.Equal(t, http.StatusOK, replayed.Code, replayed.Body.String()) + require.Equal(t, "true", replayed.Header().Get("X-Idempotency-Replayed")) + require.Equal(t, "no-store", replayed.Header().Get("Cache-Control")) + require.False(t, gjson.GetBytes(replayed.Body.Bytes(), "data.key").Exists()) + require.Equal(t, hint, gjson.GetBytes(replayed.Body.Bytes(), "data.key_hint").String()) + require.Equal(t, service.HashAPIKey(credential), repo.keys[1].KeyHash) + requireShowOnceReadResponses(t, router, credential, hint) +} + func showOnceAPIKeyRequest(router *gin.Engine, method, path, body, idempotencyKey string) *httptest.ResponseRecorder { request := httptest.NewRequest(method, path, strings.NewReader(body)) request.Header.Set("Content-Type", "application/json") diff --git a/backend/internal/handler/idempotency_helper.go b/backend/internal/handler/idempotency_helper.go index 2f3d8021d..4919a9d5d 100644 --- a/backend/internal/handler/idempotency_helper.go +++ b/backend/internal/handler/idempotency_helper.go @@ -32,6 +32,17 @@ func executeUserIdempotentJSONWithPresenter( ttl time.Duration, execute func(context.Context) (any, error), present func(any) any, +) { + executeUserIdempotentJSONWithTimeout(c, scope, payload, ttl, 0, execute, present) +} + +func executeUserIdempotentJSONWithTimeout( + c *gin.Context, + scope string, + payload any, + ttl, executionTimeout time.Duration, + execute func(context.Context) (any, error), + present func(any) any, ) { writeSuccess := func(data any) { if present != nil { @@ -41,7 +52,13 @@ func executeUserIdempotentJSONWithPresenter( } coordinator := service.DefaultIdempotencyCoordinator() if coordinator == nil { - data, err := execute(c.Request.Context()) + ctx := c.Request.Context() + if executionTimeout > 0 { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(context.WithoutCancel(ctx), executionTimeout) + defer cancel() + } + data, err := execute(ctx) if err != nil { response.ErrorFrom(c, err) return @@ -56,14 +73,15 @@ func executeUserIdempotentJSONWithPresenter( } result, err := coordinator.Execute(c.Request.Context(), service.IdempotencyExecuteOptions{ - Scope: scope, - ActorScope: actorScope, - Method: c.Request.Method, - Route: c.FullPath(), - IdempotencyKey: c.GetHeader("Idempotency-Key"), - Payload: payload, - RequireKey: true, - TTL: ttl, + Scope: scope, + ActorScope: actorScope, + Method: c.Request.Method, + Route: c.FullPath(), + IdempotencyKey: c.GetHeader("Idempotency-Key"), + Payload: payload, + RequireKey: true, + TTL: ttl, + ExecutionTimeout: executionTimeout, }, execute) if err != nil { if infraerrors.Code(err) == infraerrors.Code(service.ErrIdempotencyStoreUnavail) { diff --git a/backend/internal/repository/account_repo.go b/backend/internal/repository/account_repo.go index 56f7edd76..51547c482 100644 --- a/backend/internal/repository/account_repo.go +++ b/backend/internal/repository/account_repo.go @@ -1000,7 +1000,7 @@ func (r *accountRepository) Delete(ctx context.Context, id int64) error { } func (r *accountRepository) List(ctx context.Context, params pagination.PaginationParams) ([]service.Account, *pagination.PaginationResult, error) { - return r.ListWithFilters(ctx, params, "", "", "", "", 0, "") + return r.ListWithFilters(ctx, params, "", "", "", "", 0, "", "") } func (r *accountRepository) accountListFilteredQuery(platform, accountType, status, search string, groupID int64, privacyMode string) *dbent.AccountQuery { @@ -1099,8 +1099,12 @@ func (r *accountRepository) accountListFilteredQuery(platform, accountType, stat return q } -func (r *accountRepository) ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode string) ([]service.Account, *pagination.PaginationResult, error) { +func (r *accountRepository) ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]service.Account, *pagination.PaginationResult, error) { q := r.accountListFilteredQuery(platform, accountType, status, search, groupID, privacyMode) + model = strings.TrimSpace(model) + if model != "" { + return r.listWithFiltersByModel(ctx, q, params, model) + } // Clone before Count so interceptor-appended predicates (SoftDeleteMixin's // deleted_at IS NULL) don't accumulate on the shared builder and pollute the // subsequent list query. Same pattern used in group_repo/promo_code_repo/user_repo @@ -1129,6 +1133,40 @@ func (r *accountRepository) ListWithFilters(ctx context.Context, params paginati return outAccounts, paginationResultFromTotal(int64(total), params), nil } +// listWithFiltersByModel 在既有筛选与排序之上按账号的模型支持语义过滤后再分页。 +// 模型支持依赖 model_mapping 通配符、平台默认目录与 OpenAI 透传例外,无法在 SQL 中 +// 精确表达,因此先按同一 SQL 顺序取出候选账号做 Go 过滤(纯本地数据,不访问上游), +// 再按排序结果切出当前页并为该页批量补齐分组/代理。 +func (r *accountRepository) listWithFiltersByModel(ctx context.Context, q *dbent.AccountQuery, params pagination.PaginationParams, model string) ([]service.Account, *pagination.PaginationResult, error) { + candidatesQuery := q + for _, order := range accountListOrder(params) { + candidatesQuery = candidatesQuery.Order(order) + } + candidates, err := candidatesQuery.All(ctx) + if err != nil { + return nil, nil, err + } + + matched := make([]*dbent.Account, 0, len(candidates)) + for _, candidate := range candidates { + account := accountEntityToService(candidate) + if account != nil && account.IsModelSupported(model) { + matched = append(matched, candidate) + } + } + + result := paginationResultFromTotal(int64(len(matched)), params) + pageRows := paginateSlice(matched, params) + if len(pageRows) == 0 { + return []service.Account{}, result, nil + } + outAccounts, err := r.accountsToService(ctx, pageRows) + if err != nil { + return nil, nil, err + } + return outAccounts, result, nil +} + func (r *accountRepository) ListAllWithFilters(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode string) ([]service.Account, error) { accounts, err := r.accountListFilteredQuery(platform, accountType, status, search, groupID, privacyMode).All(ctx) if err != nil { diff --git a/backend/internal/repository/account_repo_integration_test.go b/backend/internal/repository/account_repo_integration_test.go index 4ce01a2c9..f4bc402bb 100644 --- a/backend/internal/repository/account_repo_integration_test.go +++ b/backend/internal/repository/account_repo_integration_test.go @@ -615,7 +615,7 @@ func (s *AccountRepoSuite) TestListWithFilters() { tt.setup(client) - accounts, page, err := repo.ListWithFilters(ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, tt.platform, tt.accType, tt.status, tt.search, tt.groupID, tt.privacyMode) + accounts, page, err := repo.ListWithFilters(ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, tt.platform, tt.accType, tt.status, tt.search, tt.groupID, tt.privacyMode, "") s.Require().NoError(err) s.Require().Len(accounts, tt.wantCount) // Regression guard for issue #3601: when the whole result set fits on a single page, @@ -687,7 +687,7 @@ func (s *AccountRepoSuite) TestPreload_And_VirtualFields() { s.Require().Len(got.Groups, 1, "expected Groups to be populated") s.Require().Equal(group.ID, got.Groups[0].ID) - accounts, page, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "", "acc", 0, "") + accounts, page, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, "", "", "", "acc", 0, "", "") s.Require().NoError(err, "ListWithFilters") s.Require().Equal(int64(1), page.Total) s.Require().Len(accounts, 1) diff --git a/backend/internal/repository/account_repo_model_filter_test.go b/backend/internal/repository/account_repo_model_filter_test.go new file mode 100644 index 000000000..210f28ff1 --- /dev/null +++ b/backend/internal/repository/account_repo_model_filter_test.go @@ -0,0 +1,87 @@ +package repository + +import ( + "context" + "testing" + + "github.com/DATA-DOG/go-sqlmock" + dbent "github.com/Wei-Shaw/sub2api/ent" + _ "github.com/Wei-Shaw/sub2api/ent/runtime" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" + + "entgo.io/ent/dialect" + entsql "entgo.io/ent/dialect/sql" +) + +func modelFilterAccountRows() *sqlmock.Rows { + return sqlmock.NewRows([]string{"id", "platform", "type", "credentials", "extra", "parent_account_id"}). + AddRow(int64(1), service.PlatformAnthropic, service.AccountTypeAPIKey, []byte(`{"model_mapping":{"claude-opus-5":"upstream-opus"}}`), []byte(`{}`), nil). + AddRow(int64(2), service.PlatformAnthropic, service.AccountTypeAPIKey, []byte(`{"model_mapping":{"claude-haiku-5-5":"upstream-haiku"}}`), []byte(`{}`), nil). + AddRow(int64(3), service.PlatformAnthropic, service.AccountTypeAPIKey, []byte(`{"model_mapping":{"claude-*":"upstream-claude"}}`), []byte(`{}`), nil). + AddRow(int64(4), service.PlatformGemini, service.AccountTypeOAuth, nil, []byte(`{}`), nil) +} + +func newModelFilterRepository(t *testing.T) (*accountRepository, sqlmock.Sqlmock) { + t.Helper() + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { _ = db.Close() }) + client := dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db))) + t.Cleanup(func() { _ = client.Close() }) + return newAccountRepositoryWithSQL(client, db, nil), mock +} + +func TestListWithFilters_ModelFilterAppliesBeforePagination(t *testing.T) { + repo, mock := newModelFilterRepository(t) + + // 候选集按 SQL 顺序取回后由模型支持语义过滤:精确映射、通配符映射与无映射账号命中, + // 映射了其它模型的账号被排除;分页在过滤结果之上进行。 + mock.ExpectQuery(`SELECT`).WillReturnRows(modelFilterAccountRows()) + mock.ExpectQuery(`SELECT`).WillReturnRows(sqlmock.NewRows([]string{"id", "account_id", "group_id", "priority", "created_at"})) + + accounts, result, err := repo.ListWithFilters( + context.Background(), + pagination.PaginationParams{Page: 1, PageSize: 1, SortBy: "name", SortOrder: "asc"}, + "", "", "", "", 0, "", "claude-opus-5", + ) + require.NoError(t, err) + require.Equal(t, int64(3), result.Total) + require.Equal(t, 3, result.Pages) + require.Len(t, accounts, 1) + require.Equal(t, int64(1), accounts[0].ID) + + // 第 2 页落在通配符命中的账号上,证明分页发生在过滤之后。 + mock.ExpectQuery(`SELECT`).WillReturnRows(modelFilterAccountRows()) + mock.ExpectQuery(`SELECT`).WillReturnRows(sqlmock.NewRows([]string{"id", "account_id", "group_id", "priority", "created_at"})) + accounts, result, err = repo.ListWithFilters( + context.Background(), + pagination.PaginationParams{Page: 2, PageSize: 1, SortBy: "name", SortOrder: "asc"}, + "", "", "", "", 0, "", "claude-opus-5", + ) + require.NoError(t, err) + require.Equal(t, int64(3), result.Total) + require.Len(t, accounts, 1) + require.Equal(t, int64(3), accounts[0].ID) + require.NoError(t, mock.ExpectationsWereMet()) +} + +func TestListWithFilters_ModelFilterKeepsUnfilteredPathWhenEmpty(t *testing.T) { + repo, mock := newModelFilterRepository(t) + + mock.ExpectQuery(`SELECT COUNT`).WillReturnRows(sqlmock.NewRows([]string{"count"}).AddRow(2)) + mock.ExpectQuery(`SELECT`).WillReturnRows(modelFilterAccountRows()) + mock.ExpectQuery(`SELECT`).WillReturnRows(sqlmock.NewRows([]string{"id", "account_id", "group_id", "priority", "created_at"})) + + accounts, result, err := repo.ListWithFilters( + context.Background(), + pagination.PaginationParams{Page: 1, PageSize: 2, SortBy: "name", SortOrder: "asc"}, + "", "", "", "", 0, "", "", + ) + require.NoError(t, err) + // 无模型筛选时仍走 Count + SQL 分页路径(total 来自 COUNT 而非本地过滤)。 + require.Equal(t, int64(2), result.Total) + require.NotEmpty(t, accounts) + require.NoError(t, mock.ExpectationsWereMet()) +} diff --git a/backend/internal/repository/account_repo_sort_integration_test.go b/backend/internal/repository/account_repo_sort_integration_test.go index 19c974f37..1465ed20a 100644 --- a/backend/internal/repository/account_repo_sort_integration_test.go +++ b/backend/internal/repository/account_repo_sort_integration_test.go @@ -30,7 +30,7 @@ func (s *AccountRepoSuite) TestListWithFilters_SortByPriorityDesc() { PageSize: 10, SortBy: "priority", SortOrder: "desc", - }, "", "", "", "", 0, "") + }, "", "", "", "", 0, "", "") s.Require().NoError(err) s.Require().Len(accounts, 2) s.Require().Equal("high-priority", accounts[0].Name) @@ -62,7 +62,7 @@ func (s *AccountRepoSuite) TestListWithFilters_SortByUpstreamBillingRateWithMiss } { accounts, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{ Page: 1, PageSize: 10, SortBy: "upstream_billing_rate", SortOrder: tc.order, - }, "", "", "", "", 0, "") + }, "", "", "", "", 0, "", "") s.Require().NoError(err) s.Require().Len(accounts, 4) for i, name := range tc.want { @@ -130,7 +130,7 @@ func (s *AccountRepoSuite) TestListWithFilters_SortByCurrentUpstreamBillingRateD } { accounts, _, err := s.repo.ListWithFilters(s.ctx, pagination.PaginationParams{ Page: 1, PageSize: 10, SortBy: "upstream_billing_rate", SortOrder: tc.order, - }, "", "", "", "", 0, "") + }, "", "", "", "", 0, "", "") s.Require().NoError(err) s.Require().Len(accounts, 2) for i, name := range tc.want { diff --git a/backend/internal/repository/api_key_hash_storage_test.go b/backend/internal/repository/api_key_hash_storage_test.go index 72d2685a3..a43e97307 100644 --- a/backend/internal/repository/api_key_hash_storage_test.go +++ b/backend/internal/repository/api_key_hash_storage_test.go @@ -6,8 +6,10 @@ import ( "os" "strings" "testing" + "time" dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/ent/apikey" "github.com/Wei-Shaw/sub2api/internal/config" "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" "github.com/Wei-Shaw/sub2api/internal/service" @@ -118,6 +120,68 @@ func TestAPIKeyServiceLegacyShortCredentialStillAuthenticates(t *testing.T) { require.ErrorIs(t, svc.ValidateCustomKey(credential), service.ErrAPIKeyTooShort) } +func TestAPIKeyRotationPreservesRecordAndInvalidatesOldCredential(t *testing.T) { + ctx := context.Background() + repo, client := newAPIKeyRepoSQLite(t) + owner := mustCreateAPIKeyRepoUser(t, ctx, client, "rotation-owner@example.invalid") + other := mustCreateAPIKeyRepoUser(t, ctx, client, "rotation-other@example.invalid") + group, err := client.Group.Create().SetName("Rotation group").Save(ctx) + require.NoError(t, err) + expiry := time.Now().Add(time.Hour).Truncate(time.Second) + const oldCredential = "sk-rotate-test-legacy-0123456789abcdef" + key := &service.APIKey{ + UserID: owner.ID, Name: "Rotation", Key: oldCredential, Status: service.StatusActive, + GroupID: &group.ID, Quota: 100, QuotaUsed: 9, ExpiresAt: &expiry, RateLimit5h: 20, + IPWhitelist: []string{"192.0.2.10"}, + } + require.NoError(t, repo.Create(ctx, key)) + require.NoError(t, client.APIKey.UpdateOneID(key.ID).SetUsage5h(3).Exec(ctx)) + before, err := repo.GetByID(ctx, key.ID) + require.NoError(t, err) + + redisServer := miniredis.RunT(t) + redisClient := redis.NewClient(&redis.Options{Addr: redisServer.Addr()}) + t.Cleanup(func() { _ = redisClient.Close() }) + svc := service.NewAPIKeyService(repo, nil, nil, nil, nil, NewAPIKeyCache(redisClient), &config.Config{ + APIKeyAuth: config.APIKeyAuthCacheConfig{L1Size: 32, L1TTLSeconds: 60, L2TTLSeconds: 60}, + }) + _, err = svc.GetByKey(ctx, oldCredential) + require.NoError(t, err) + cacheKey := apiKeyAuthCachePrefix + key.KeyHash + require.True(t, redisServer.Exists(cacheKey)) + _, err = svc.Rotate(ctx, key.ID, other.ID) + require.ErrorIs(t, err, service.ErrAPIKeyNotFound) + require.True(t, redisServer.Exists(cacheKey)) + + rotated, err := svc.Rotate(ctx, key.ID, owner.ID) + require.NoError(t, err) + require.NotEqual(t, oldCredential, rotated.Key) + require.Equal(t, service.MaskAPIKey(rotated.Key), rotated.KeyHint) + require.False(t, redisServer.Exists(cacheKey)) + _, err = svc.GetByKey(ctx, oldCredential) + require.ErrorIs(t, err, service.ErrAPIKeyNotFound) + active, err := svc.GetByKey(ctx, rotated.Key) + require.NoError(t, err) + require.Equal(t, key.ID, active.ID) + + after, err := repo.GetByID(ctx, key.ID) + require.NoError(t, err) + require.Empty(t, after.Key) + require.Equal(t, service.HashAPIKey(rotated.Key), after.KeyHash) + require.Equal(t, rotated.KeyHint, after.KeyHint) + before.Key, before.KeyHash, before.KeyHint, before.UpdatedAt = after.Key, after.KeyHash, after.KeyHint, after.UpdatedAt + require.Equal(t, before, after) + + err = repo.RotateCredential(ctx, key.ID, owner.ID, key.KeyHash, "unused-after-stale-write") + require.ErrorIs(t, err, service.ErrAPIKeyRotationConflict) + require.NoError(t, client.APIKey.UpdateOneID(key.ID).SetDeletedAt(time.Now()).Exec(ctx)) + _, err = svc.Rotate(ctx, key.ID, owner.ID) + require.ErrorIs(t, err, service.ErrAPIKeyNotFound) + count, err := client.APIKey.Query().Where(apikey.IDEQ(key.ID)).Count(ctx) + require.NoError(t, err) + require.Zero(t, count) +} + func TestAPIKeyRepositoryPostgresHashAuthenticationSmoke(t *testing.T) { dsn := os.Getenv("ASO_TEST_POSTGRES_DSN") if dsn == "" { diff --git a/backend/internal/repository/api_key_repo.go b/backend/internal/repository/api_key_repo.go index 5706230cd..6f1291a0d 100644 --- a/backend/internal/repository/api_key_repo.go +++ b/backend/internal/repository/api_key_repo.go @@ -403,6 +403,23 @@ func (r *apiKeyRepository) Update(ctx context.Context, key *service.APIKey, fiel return nil } +func (r *apiKeyRepository) RotateCredential(ctx context.Context, id, userID int64, previousHash, credential string) error { + affected, err := clientFromContext(ctx, r.client).APIKey.Update(). + Where(apikey.IDEQ(id), apikey.UserIDEQ(userID), apikey.KeyHashEQ(previousHash), apikey.DeletedAtIsNil()). + ClearKey(). + SetKeyHash(service.HashAPIKey(credential)). + SetKeyHint(service.MaskAPIKey(credential)). + SetUpdatedAt(time.Now()). + Save(ctx) + if err != nil { + return translatePersistenceError(err, nil, service.ErrAPIKeyExists) + } + if affected == 0 { + return service.ErrAPIKeyRotationConflict + } + return nil +} + func (r *apiKeyRepository) Delete(ctx context.Context, id int64) error { // 存在唯一键约束 生成tombstone key 用来释放原key,长度远小于 128,满足 schema 限制 tombstoneKey := fmt.Sprintf("__deleted__%d__%d", id, time.Now().UnixNano()) diff --git a/backend/internal/repository/user_repo.go b/backend/internal/repository/user_repo.go index eec3d22dc..612a6db6e 100644 --- a/backend/internal/repository/user_repo.go +++ b/backend/internal/repository/user_repo.go @@ -543,6 +543,21 @@ func (r *userRepository) ListWithFilters(ctx context.Context, params pagination. }) } + if filters.HideEnterpriseEmployees { + // 与 CountActiveOwners 的"有效负责人"定义一致:成员关系未软删除、 + // role=owner、成员状态 active,且用户本身 active(未删除用户由软删除 + // 拦截器保证)。在 Count/分页之前过滤,保证 total 与结果集一致。 + q = q.Where(dbuser.StatusEQ(service.StatusActive)) + q = q.Where(func(s *entsql.Selector) { + members := entsql.Table("enterprise_members") + s.Where(entsql.Exists(entsql.Select(members.C("user_id")).From(members). + Where(entsql.And(entsql.ColumnsEQ(members.C("user_id"), s.C("id")), + entsql.EQ(members.C("role"), service.EnterpriseRoleOwner), + entsql.EQ(members.C("status"), service.EnterpriseMemberStatusActive), + entsql.IsNull(members.C("deleted_at")))))) + }) + } + if filters.Status != "" { q = q.Where(dbuser.StatusEQ(filters.Status)) } diff --git a/backend/internal/repository/user_repo_hide_enterprise_employees_integration_test.go b/backend/internal/repository/user_repo_hide_enterprise_employees_integration_test.go new file mode 100644 index 000000000..6cd529f6d --- /dev/null +++ b/backend/internal/repository/user_repo_hide_enterprise_employees_integration_test.go @@ -0,0 +1,111 @@ +//go:build integration + +package repository + +import ( + "context" + "fmt" + "testing" + "time" + + dbent "github.com/Wei-Shaw/sub2api/ent" + "github.com/Wei-Shaw/sub2api/internal/pkg/pagination" + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" +) + +// 开关语义与 CountActiveOwners 的"有效负责人"一致:成员关系未软删除、 +// role=owner、成员状态 active,且用户本身 active。非企业用户与非负责人均不显示。 +func TestUserListHideEnterpriseEmployees(t *testing.T) { + tx := testEntTx(t) + ctx := dbent.NewTxContext(context.Background(), tx) + client := tx.Client() + members := NewEnterpriseMemberRepository(client) + e := enterpriseFixture(t, ctx) + other := enterpriseFixture(t, ctx) + + newMember := func(enterpriseID int64, role, status string) *service.EnterpriseMember { + t.Helper() + user := mustCreateUser(t, client, &service.User{ + Email: fmt.Sprintf("hide-emp-%d@example.com", time.Now().UnixNano()), + Username: "hide-emp", + }) + m := &service.EnterpriseMember{EnterpriseID: enterpriseID, UserID: user.ID, Role: role, Status: status} + require.NoError(t, members.Create(ctx, m)) + return m + } + + owner := newMember(e.ID, service.EnterpriseRoleOwner, service.EnterpriseMemberStatusActive) + secondOwner := newMember(e.ID, service.EnterpriseRoleOwner, service.EnterpriseMemberStatusActive) + employee := newMember(e.ID, service.EnterpriseRoleMember, service.EnterpriseMemberStatusActive) + manager := newMember(e.ID, service.EnterpriseRoleManager, service.EnterpriseMemberStatusActive) + disabledMemberOwner := newMember(e.ID, service.EnterpriseRoleOwner, service.EnterpriseMemberStatusDisabled) + deletedOwner := newMember(e.ID, service.EnterpriseRoleOwner, service.EnterpriseMemberStatusActive) + require.NoError(t, members.Delete(ctx, e.ID, deletedOwner.ID)) + disabledUserOwner := newMember(e.ID, service.EnterpriseRoleOwner, service.EnterpriseMemberStatusActive) + require.NoError(t, client.User.UpdateOneID(disabledUserOwner.UserID).SetStatus(service.StatusDisabled).Exec(ctx)) + otherOwner := newMember(other.ID, service.EnterpriseRoleOwner, service.EnterpriseMemberStatusActive) + plain := mustCreateUser(t, client, &service.User{ + Email: fmt.Sprintf("hide-emp-plain-%d@example.com", time.Now().UnixNano()), + Username: "hide-emp-plain", + }) + + repo := newUserRepositoryWithSQL(client, client) + ids := func(users []service.User) []int64 { + out := make([]int64, 0, len(users)) + for i := range users { + out = append(out, users[i].ID) + } + return out + } + + t.Run("scoped to enterprise keeps only available owners", func(t *testing.T) { + users, page, err := repo.ListWithFilters(ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, + service.UserListFilters{EnterpriseID: e.ID, HideEnterpriseEmployees: true}) + require.NoError(t, err) + require.EqualValues(t, 2, page.Total) + require.ElementsMatch(t, []int64{owner.UserID, secondOwner.UserID}, ids(users)) + }) + + t.Run("toggle off restores the full membership list", func(t *testing.T) { + users, page, err := repo.ListWithFilters(ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, + service.UserListFilters{EnterpriseID: e.ID}) + require.NoError(t, err) + require.EqualValues(t, 6, page.Total) + require.ElementsMatch(t, []int64{ + owner.UserID, secondOwner.UserID, employee.UserID, manager.UserID, + disabledMemberOwner.UserID, disabledUserOwner.UserID, + }, ids(users)) + }) + + t.Run("global filter excludes non owners and non enterprise users", func(t *testing.T) { + users, _, err := repo.ListWithFilters(ctx, pagination.PaginationParams{Page: 1, PageSize: 100}, + service.UserListFilters{HideEnterpriseEmployees: true}) + require.NoError(t, err) + got := ids(users) + require.Subset(t, got, []int64{owner.UserID, secondOwner.UserID, otherOwner.UserID}) + for _, excluded := range []int64{ + employee.UserID, manager.UserID, disabledMemberOwner.UserID, + deletedOwner.UserID, disabledUserOwner.UserID, plain.ID, + } { + require.NotContains(t, got, excluded) + } + }) + + t.Run("filters before pagination and count", func(t *testing.T) { + users, page, err := repo.ListWithFilters(ctx, pagination.PaginationParams{Page: 1, PageSize: 1}, + service.UserListFilters{EnterpriseID: e.ID, HideEnterpriseEmployees: true}) + require.NoError(t, err) + require.EqualValues(t, 2, page.Total, "total 必须是过滤后的数量") + require.Len(t, users, 1) + require.Subset(t, []int64{owner.UserID, secondOwner.UserID}, ids(users)) + }) + + t.Run("combines with enterprise id of another enterprise", func(t *testing.T) { + users, page, err := repo.ListWithFilters(ctx, pagination.PaginationParams{Page: 1, PageSize: 10}, + service.UserListFilters{EnterpriseID: other.ID, HideEnterpriseEmployees: true}) + require.NoError(t, err) + require.EqualValues(t, 1, page.Total) + require.Equal(t, []int64{otherOwner.UserID}, ids(users)) + }) +} diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index 1691858cc..1ba416172 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -1936,7 +1936,7 @@ func (s *stubAccountRepo) ListAllWithFilters(context.Context, string, string, st return nil, nil } -func (s *stubAccountRepo) ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode string) ([]service.Account, *pagination.PaginationResult, error) { +func (s *stubAccountRepo) ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]service.Account, *pagination.PaginationResult, error) { return nil, nil, errors.New("not implemented") } diff --git a/backend/internal/server/middleware/cors.go b/backend/internal/server/middleware/cors.go index fcf6d332b..310a02d95 100644 --- a/backend/internal/server/middleware/cors.go +++ b/backend/internal/server/middleware/cors.go @@ -51,7 +51,7 @@ func CORS(cfg config.CORSConfig) gin.HandlerFunc { allowedSet[origin] = struct{}{} } allowHeaders := []string{ - "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", + "Content-Type", "Content-Length", "Accept-Encoding", "X-CSRF-Token", "Authorization", "Idempotency-Key", "accept", "origin", "Cache-Control", "X-Requested-With", "X-API-Key", "X-Admin-UI-Request", "X-User-UI-Request", } // OpenAI Node SDK 会发送 x-stainless-* 请求头,需在 CORS 中显式放行。 diff --git a/backend/internal/server/middleware/cors_test.go b/backend/internal/server/middleware/cors_test.go index 882838986..d863c8f79 100644 --- a/backend/internal/server/middleware/cors_test.go +++ b/backend/internal/server/middleware/cors_test.go @@ -105,6 +105,7 @@ func TestCORS_AllowedOrigin_HasAllowHeaders(t *testing.T) { "允许的 origin 应收到 Allow-Headers") assert.Contains(t, w.Header().Get("Access-Control-Allow-Headers"), "X-Admin-UI-Request") assert.Contains(t, w.Header().Get("Access-Control-Allow-Headers"), "X-User-UI-Request") + assert.Contains(t, w.Header().Get("Access-Control-Allow-Headers"), "Idempotency-Key") assert.NotEmpty(t, w.Header().Get("Access-Control-Allow-Methods"), "允许的 origin 应收到 Allow-Methods") assert.Contains(t, w.Header().Get("Access-Control-Expose-Headers"), "Server-Timing") diff --git a/backend/internal/server/routes/user.go b/backend/internal/server/routes/user.go index 42d567edb..4b20940d2 100644 --- a/backend/internal/server/routes/user.go +++ b/backend/internal/server/routes/user.go @@ -100,6 +100,7 @@ func RegisterUserRoutes( keys.GET("", h.APIKey.List) keys.GET("/:id", h.APIKey.GetByID) keys.POST("", h.APIKey.Create) + keys.POST("/:id/rotate", h.APIKey.Rotate) keys.PUT("/:id", h.APIKey.Update) keys.DELETE("/:id", h.APIKey.Delete) } diff --git a/backend/internal/service/account_service.go b/backend/internal/service/account_service.go index 7a35af06f..4de3a9c39 100644 --- a/backend/internal/service/account_service.go +++ b/backend/internal/service/account_service.go @@ -68,7 +68,10 @@ type AccountRepository interface { Delete(ctx context.Context, id int64) error List(ctx context.Context, params pagination.PaginationParams) ([]Account, *pagination.PaginationResult, error) - ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, *pagination.PaginationResult, error) + // ListWithFilters 按平台/类型/状态/搜索/分组/隐私模式与模型支持过滤账号。 + // model 非空时复用账号自身的模型支持语义(model_mapping 通配符、平台默认目录、 + // OpenAI 透传等)在分页前过滤,且不发起任何上游请求。 + ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]Account, *pagination.PaginationResult, error) // ListAllWithFilters 返回符合过滤条件的全部账号(不分页),用于账号列表页 // 计算 OpenAI 调度分数的过滤范围池。 ListAllWithFilters(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, error) diff --git a/backend/internal/service/account_service_delete_test.go b/backend/internal/service/account_service_delete_test.go index ed65c25c1..3aa9e2186 100644 --- a/backend/internal/service/account_service_delete_test.go +++ b/backend/internal/service/account_service_delete_test.go @@ -83,7 +83,7 @@ func (s *accountRepoStub) ListAllWithFilters(context.Context, string, string, st return nil, nil } -func (s *accountRepoStub) ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, *pagination.PaginationResult, error) { +func (s *accountRepoStub) ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]Account, *pagination.PaginationResult, error) { panic("unexpected ListWithFilters call") } diff --git a/backend/internal/service/admin_account.go b/backend/internal/service/admin_account.go index 0b932e3d9..66dbb4411 100644 --- a/backend/internal/service/admin_account.go +++ b/backend/internal/service/admin_account.go @@ -21,25 +21,45 @@ import ( ) // Account management implementations -func (s *adminServiceImpl) ListAccounts(ctx context.Context, page, pageSize int, platform, accountType, status, search string, groupID int64, privacyMode string, sortBy, sortOrder string) ([]Account, int64, error) { +func (s *adminServiceImpl) ListAccounts(ctx context.Context, page, pageSize int, platform, accountType, status, search string, groupID int64, privacyMode, model, sortBy, sortOrder string) ([]Account, int64, error) { if groupID > 0 { if err := s.ValidateAccountGroupBindings(ctx, []int64{groupID}); err != nil { return nil, 0, err } } params := pagination.PaginationParams{Page: page, PageSize: pageSize, SortBy: sortBy, SortOrder: sortOrder} - accounts, result, err := s.accountRepo.ListWithFilters(ctx, params, platform, accountType, status, search, groupID, privacyMode) + accounts, result, err := s.accountRepo.ListWithFilters(ctx, params, platform, accountType, status, search, groupID, privacyMode, model) if err != nil { return nil, 0, err } return accounts, result.Total, nil } -func (s *adminServiceImpl) ListAccountsForSchedulerScoreFilter(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, error) { +func (s *adminServiceImpl) ListAccountsForSchedulerScoreFilter(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]Account, error) { if s == nil || s.accountRepo == nil { return nil, nil } - return s.accountRepo.ListAllWithFilters(ctx, platform, accountType, status, search, groupID, privacyMode) + accounts, err := s.accountRepo.ListAllWithFilters(ctx, platform, accountType, status, search, groupID, privacyMode) + if err != nil { + return nil, err + } + return filterAccountsByModel(accounts, model), nil +} + +// filterAccountsByModel 复用账号自身的模型支持语义(model_mapping 通配符、平台默认目录、 +// OpenAI 透传等)在分页前筛选账号,避免在 SQL 或前端重复实现同一语义。空模型不过滤。 +func filterAccountsByModel(accounts []Account, model string) []Account { + model = strings.TrimSpace(model) + if model == "" { + return accounts + } + filtered := make([]Account, 0, len(accounts)) + for i := range accounts { + if accounts[i].IsModelSupported(model) { + filtered = append(filtered, accounts[i]) + } + } + return filtered } func (s *adminServiceImpl) ListOpenAISchedulableAccountsForSchedulerScore(ctx context.Context, groupID *int64) ([]Account, error) { @@ -1351,6 +1371,7 @@ func (s *adminServiceImpl) resolveBulkUpdateTargetIDs(ctx context.Context, filte filters.Search, groupID, filters.PrivacyMode, + filters.Model, "", "", ) diff --git a/backend/internal/service/admin_service.go b/backend/internal/service/admin_service.go index 30e9da2e4..8db6add60 100644 --- a/backend/internal/service/admin_service.go +++ b/backend/internal/service/admin_service.go @@ -71,10 +71,11 @@ type AdminService interface { ReplaceUserGroup(ctx context.Context, userID, oldGroupID, newGroupID int64) (*ReplaceUserGroupResult, error) // Account management - ListAccounts(ctx context.Context, page, pageSize int, platform, accountType, status, search string, groupID int64, privacyMode string, sortBy, sortOrder string) ([]Account, int64, error) + // model 非空时按账号模型支持语义筛选(复用 model_mapping/平台目录),先于分页生效。 + ListAccounts(ctx context.Context, page, pageSize int, platform, accountType, status, search string, groupID int64, privacyMode, model, sortBy, sortOrder string) ([]Account, int64, error) // ListAccountsForSchedulerScoreFilter 返回符合过滤条件的全部账号(不分页), // 作为账号列表页计算 OpenAI 调度分数的过滤范围池。 - ListAccountsForSchedulerScoreFilter(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, error) + ListAccountsForSchedulerScoreFilter(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]Account, error) // ListOpenAISchedulableAccountsForSchedulerScore 返回指定分组(nil 为未分组)内 // 可调度的 OpenAI 账号,用于按组计算调度分数。 ListOpenAISchedulableAccountsForSchedulerScore(ctx context.Context, groupID *int64) ([]Account, error) @@ -484,6 +485,7 @@ type BulkUpdateAccountFilters struct { Group string Search string PrivacyMode string + Model string } // BulkUpdateAccountResult captures the result for a single account update. diff --git a/backend/internal/service/admin_service_bulk_update_test.go b/backend/internal/service/admin_service_bulk_update_test.go index e935beaa9..374cd54b5 100644 --- a/backend/internal/service/admin_service_bulk_update_test.go +++ b/backend/internal/service/admin_service_bulk_update_test.go @@ -128,7 +128,7 @@ func (s *accountRepoStubForBulkUpdate) ListAllWithFilters(context.Context, strin return nil, nil } -func (s *accountRepoStubForBulkUpdate) ListWithFilters(_ context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, *pagination.PaginationResult, error) { +func (s *accountRepoStubForBulkUpdate) ListWithFilters(_ context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]Account, *pagination.PaginationResult, error) { s.listCalled = true s.lastListParams = params s.lastListFilters.platform = platform diff --git a/backend/internal/service/admin_service_group_test.go b/backend/internal/service/admin_service_group_test.go index 55a815bdb..55b26241f 100644 --- a/backend/internal/service/admin_service_group_test.go +++ b/backend/internal/service/admin_service_group_test.go @@ -154,7 +154,7 @@ func TestAdminServiceSimpleModeRejectsDirectCompositeGroupAccess(t *testing.T) { func TestAdminServiceSimpleModeRejectsAccountListCompositeFilter(t *testing.T) { repo := &groupRepoStubForAdmin{getByID: &Group{ID: 9, Platform: PlatformComposite}} svc := &adminServiceImpl{cfg: &config.Config{RunMode: config.RunModeSimple}, groupRepo: repo} - _, _, err := svc.ListAccounts(context.Background(), 1, 20, "", "", "", "", 9, "", "", "") + _, _, err := svc.ListAccounts(context.Background(), 1, 20, "", "", "", "", 9, "", "", "", "") require.Error(t, err) } diff --git a/backend/internal/service/admin_service_search_test.go b/backend/internal/service/admin_service_search_test.go index 76acd1b5e..138c49298 100644 --- a/backend/internal/service/admin_service_search_test.go +++ b/backend/internal/service/admin_service_search_test.go @@ -13,23 +13,25 @@ import ( type accountRepoStubForAdminList struct { accountRepoStub - listWithFiltersCalls int - listWithFiltersParams pagination.PaginationParams - listWithFiltersPlatform string - listWithFiltersType string - listWithFiltersStatus string - listWithFiltersSearch string - listWithFiltersPrivacy string - listWithFiltersAccounts []Account - listWithFiltersResult *pagination.PaginationResult - listWithFiltersErr error + listWithFiltersCalls int + listWithFiltersParams pagination.PaginationParams + listWithFiltersPlatform string + listWithFiltersType string + listWithFiltersStatus string + listWithFiltersSearch string + listWithFiltersPrivacy string + listWithFiltersModel string + listWithFiltersAccounts []Account + listWithFiltersResult *pagination.PaginationResult + listWithFiltersErr error + listAllWithFiltersAccounts []Account } func (s *accountRepoStubForAdminList) ListAllWithFilters(context.Context, string, string, string, string, int64, string) ([]Account, error) { - return nil, nil + return s.listAllWithFiltersAccounts, nil } -func (s *accountRepoStubForAdminList) ListWithFilters(_ context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, *pagination.PaginationResult, error) { +func (s *accountRepoStubForAdminList) ListWithFilters(_ context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]Account, *pagination.PaginationResult, error) { s.listWithFiltersCalls++ s.listWithFiltersParams = params s.listWithFiltersPlatform = platform @@ -37,6 +39,7 @@ func (s *accountRepoStubForAdminList) ListWithFilters(_ context.Context, params s.listWithFiltersStatus = status s.listWithFiltersSearch = search s.listWithFiltersPrivacy = privacyMode + s.listWithFiltersModel = model if s.listWithFiltersErr != nil { return nil, nil, s.listWithFiltersErr @@ -174,7 +177,7 @@ func TestAdminService_ListAccounts_WithSearch(t *testing.T) { } svc := &adminServiceImpl{accountRepo: repo} - accounts, total, err := svc.ListAccounts(context.Background(), 1, 20, PlatformGemini, AccountTypeOAuth, StatusActive, "acc", 0, "", "name", "ASC") + accounts, total, err := svc.ListAccounts(context.Background(), 1, 20, PlatformGemini, AccountTypeOAuth, StatusActive, "acc", 0, "", "", "name", "ASC") require.NoError(t, err) require.Equal(t, int64(10), total) require.Equal(t, []Account{{ID: 1, Name: "acc"}}, accounts) @@ -196,7 +199,7 @@ func TestAdminService_ListAccounts_WithPrivacyMode(t *testing.T) { } svc := &adminServiceImpl{accountRepo: repo} - accounts, total, err := svc.ListAccounts(context.Background(), 1, 20, PlatformOpenAI, AccountTypeOAuth, StatusActive, "acc2", 0, PrivacyModeCFBlocked, "", "") + accounts, total, err := svc.ListAccounts(context.Background(), 1, 20, PlatformOpenAI, AccountTypeOAuth, StatusActive, "acc2", 0, PrivacyModeCFBlocked, "", "", "") require.NoError(t, err) require.Equal(t, int64(1), total) require.Equal(t, []Account{{ID: 2, Name: "acc2"}}, accounts) @@ -266,3 +269,95 @@ func TestAdminService_ListRedeemCodes_WithSearch(t *testing.T) { require.Equal(t, "ABC", repo.listWithFiltersSearch) }) } + +func TestAdminService_ListAccounts_WithModelFilter(t *testing.T) { + t.Run("model 参数正常传递到 repository 层且不改变分页", func(t *testing.T) { + repo := &accountRepoStubForAdminList{ + listWithFiltersAccounts: []Account{{ID: 3, Name: "model-acc"}}, + listWithFiltersResult: &pagination.PaginationResult{Total: 1}, + } + svc := &adminServiceImpl{accountRepo: repo} + + accounts, total, err := svc.ListAccounts(context.Background(), 2, 20, PlatformAnthropic, AccountTypeAPIKey, StatusActive, "", 0, "", "claude-opus-5", "name", "asc") + require.NoError(t, err) + require.Equal(t, int64(1), total) + require.Equal(t, []Account{{ID: 3, Name: "model-acc"}}, accounts) + require.Equal(t, "claude-opus-5", repo.listWithFiltersModel) + require.Equal(t, pagination.PaginationParams{Page: 2, PageSize: 20, SortBy: "name", SortOrder: "asc"}, repo.listWithFiltersParams) + }) + + t.Run("空 model 保持原有列表语义", func(t *testing.T) { + repo := &accountRepoStubForAdminList{ + listWithFiltersAccounts: []Account{{ID: 4, Name: "all-acc"}}, + listWithFiltersResult: &pagination.PaginationResult{Total: 1}, + } + svc := &adminServiceImpl{accountRepo: repo} + + _, _, err := svc.ListAccounts(context.Background(), 1, 20, "", "", "", "", 0, "", "", "", "") + require.NoError(t, err) + require.Empty(t, repo.listWithFiltersModel) + }) +} + +func TestAdminService_ListAccountsForSchedulerScoreFilter_AppliesModelSupportSemantics(t *testing.T) { + mapped := Account{ + ID: 1, + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"claude-opus-5": "upstream-opus"}, + }, + } + wildcard := Account{ + ID: 2, + Platform: PlatformAnthropic, + Type: AccountTypeAPIKey, + Credentials: map[string]any{ + "model_mapping": map[string]any{"claude-*": "upstream-claude"}, + }, + } + unmapped := Account{ + ID: 3, + Platform: PlatformGemini, + Type: AccountTypeOAuth, + } + repo := &accountRepoStubForAdminList{listAllWithFiltersAccounts: []Account{mapped, wildcard, unmapped}} + svc := &adminServiceImpl{accountRepo: repo} + + got, err := svc.ListAccountsForSchedulerScoreFilter(context.Background(), PlatformOpenAI, "", "", "", 0, "", "claude-opus-5") + require.NoError(t, err) + require.Equal(t, []int64{1, 2, 3}, filteredAccountIDs(got), "mapped、通配符与无映射账号都应命中") + + got, err = svc.ListAccountsForSchedulerScoreFilter(context.Background(), PlatformOpenAI, "", "", "", 0, "", "gemini-2.5-pro") + require.NoError(t, err) + require.Equal(t, []int64{3}, filteredAccountIDs(got), "已有映射的账号不应因目录外模型被误选") + + got, err = svc.ListAccountsForSchedulerScoreFilter(context.Background(), PlatformOpenAI, "", "", "", 0, "", "") + require.NoError(t, err) + require.Equal(t, []int64{1, 2, 3}, filteredAccountIDs(got), "空模型保持全部账号") +} + +func filteredAccountIDs(accounts []Account) []int64 { + ids := make([]int64, 0, len(accounts)) + for i := range accounts { + ids = append(ids, accounts[i].ID) + } + return ids +} + +func TestAdminService_ResolveBulkUpdateTargetIDs_AppliesModelFilter(t *testing.T) { + repo := &accountRepoStubForAdminList{ + listWithFiltersAccounts: []Account{{ID: 11}, {ID: 12}}, + listWithFiltersResult: &pagination.PaginationResult{Total: 2}, + } + svc := &adminServiceImpl{accountRepo: repo} + + ids, err := svc.resolveBulkUpdateTargetIDs(context.Background(), &BulkUpdateAccountFilters{ + Platform: PlatformAnthropic, + Model: "claude-opus-5", + }) + require.NoError(t, err) + require.Equal(t, []int64{11, 12}, ids) + require.Equal(t, "claude-opus-5", repo.listWithFiltersModel) + require.Equal(t, PlatformAnthropic, repo.listWithFiltersPlatform) +} diff --git a/backend/internal/service/admin_service_spark_shadow_test.go b/backend/internal/service/admin_service_spark_shadow_test.go index 0eda0d93c..83b210fe9 100644 --- a/backend/internal/service/admin_service_spark_shadow_test.go +++ b/backend/internal/service/admin_service_spark_shadow_test.go @@ -113,7 +113,7 @@ func (s *sparkShadowRepoStub) BatchUpdateLastUsed(_ context.Context, _ map[int64 func (s *sparkShadowRepoStub) ListByGroup(_ context.Context, _ int64) ([]Account, error) { return nil, nil } -func (s *sparkShadowRepoStub) ListWithFilters(_ context.Context, _ pagination.PaginationParams, _, _, _, _ string, _ int64, _ string) ([]Account, *pagination.PaginationResult, error) { +func (s *sparkShadowRepoStub) ListWithFilters(_ context.Context, _ pagination.PaginationParams, _, _, _, _ string, _ int64, _, _ string) ([]Account, *pagination.PaginationResult, error) { return nil, nil, nil } diff --git a/backend/internal/service/api_key_service.go b/backend/internal/service/api_key_service.go index 8465b150e..bf5a7b93c 100644 --- a/backend/internal/service/api_key_service.go +++ b/backend/internal/service/api_key_service.go @@ -28,6 +28,7 @@ var ( ErrGroupNotAllowed = infraerrors.Forbidden("GROUP_NOT_ALLOWED", "user is not allowed to bind this group") ErrEnterpriseGatewayGroupRequired = infraerrors.BadRequest("ENTERPRISE_GROUP_NOT_ALLOWED", "企业成员必须绑定分组") ErrAPIKeyExists = infraerrors.Conflict("API_KEY_EXISTS", "api key already exists") + ErrAPIKeyRotationConflict = infraerrors.Conflict("API_KEY_ROTATION_CONFLICT", "API key changed; refresh and try again") ErrAPIKeyTooShort = infraerrors.BadRequest("API_KEY_TOO_SHORT", "api key must be at least 32 characters") ErrAPIKeyTooLong = infraerrors.BadRequest("API_KEY_TOO_LONG", "api key must be at most 128 characters") ErrAPIKeyInvalidChars = infraerrors.BadRequest("API_KEY_INVALID_CHARS", "api key can only contain letters, numbers, underscores, and hyphens") @@ -131,6 +132,15 @@ type apiKeyAllByUserIDLister interface { ListAllByUserID(ctx context.Context, userID int64, filters APIKeyListFilters) ([]APIKey, error) } +type apiKeyCredentialRotator interface { + RotateCredential(ctx context.Context, id, userID int64, previousHash, credential string) error +} + +type APIKeyRotationResult struct { + Key string + KeyHint string +} + // APIKeyTaskMetadata is the public identity projection used by task listings. // It deliberately cannot hold credentials, usage or enterprise membership data. type APIKeyTaskMetadata struct { @@ -1071,6 +1081,33 @@ func (s *APIKeyService) Update(ctx context.Context, id int64, userID int64, req return apiKey, nil } +func (s *APIKeyService) Rotate(ctx context.Context, id, userID int64) (*APIKeyRotationResult, error) { + previousHash, ownerID, err := s.apiKeyRepo.GetKeyHashAndOwnerID(ctx, id) + if err != nil { + return nil, fmt.Errorf("get api key: %w", err) + } + if ownerID != userID { + return nil, ErrAPIKeyNotFound + } + rotator, ok := s.apiKeyRepo.(apiKeyCredentialRotator) + if !ok { + return nil, infraerrors.ServiceUnavailable("API_KEY_ROTATION_UNAVAILABLE", "API key rotation is unavailable") + } + credential, err := s.GenerateKey() + if err != nil { + return nil, err + } + if err := rotator.RotateCredential(ctx, id, userID, previousHash, credential); err != nil { + return nil, fmt.Errorf("rotate api key: %w", err) + } + + invalidationCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) + defer cancel() + s.InvalidateAuthCacheByHash(invalidationCtx, previousHash) + s.InvalidateAuthCacheByHash(invalidationCtx, HashAPIKey(credential)) + return &APIKeyRotationResult{Key: credential, KeyHint: MaskAPIKey(credential)}, nil +} + // Delete 删除API Key func (s *APIKeyService) Delete(ctx context.Context, id int64, userID int64) error { key, ownerID, err := s.apiKeyRepo.GetKeyHashAndOwnerID(ctx, id) diff --git a/backend/internal/service/gateway_multiplatform_test.go b/backend/internal/service/gateway_multiplatform_test.go index badb2427c..e1f7575d2 100644 --- a/backend/internal/service/gateway_multiplatform_test.go +++ b/backend/internal/service/gateway_multiplatform_test.go @@ -92,7 +92,7 @@ func (m *mockAccountRepoForPlatform) Delete(ctx context.Context, id int64) error func (m *mockAccountRepoForPlatform) List(ctx context.Context, params pagination.PaginationParams) ([]Account, *pagination.PaginationResult, error) { return nil, nil, nil } -func (m *mockAccountRepoForPlatform) ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, *pagination.PaginationResult, error) { +func (m *mockAccountRepoForPlatform) ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]Account, *pagination.PaginationResult, error) { return nil, nil, nil } func (m *mockAccountRepoForPlatform) ListAllWithFilters(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, error) { diff --git a/backend/internal/service/gemini_multiplatform_test.go b/backend/internal/service/gemini_multiplatform_test.go index 3c26f8f2c..09b8f1ca1 100644 --- a/backend/internal/service/gemini_multiplatform_test.go +++ b/backend/internal/service/gemini_multiplatform_test.go @@ -79,7 +79,7 @@ func (m *mockAccountRepoForGemini) Delete(ctx context.Context, id int64) error func (m *mockAccountRepoForGemini) List(ctx context.Context, params pagination.PaginationParams) ([]Account, *pagination.PaginationResult, error) { return nil, nil, nil } -func (m *mockAccountRepoForGemini) ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, *pagination.PaginationResult, error) { +func (m *mockAccountRepoForGemini) ListWithFilters(ctx context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]Account, *pagination.PaginationResult, error) { return nil, nil, nil } func (m *mockAccountRepoForGemini) ListAllWithFilters(ctx context.Context, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, error) { diff --git a/backend/internal/service/openai_quota_auto_reset.go b/backend/internal/service/openai_quota_auto_reset.go index 0b264617b..5e4ea252a 100644 --- a/backend/internal/service/openai_quota_auto_reset.go +++ b/backend/internal/service/openai_quota_auto_reset.go @@ -227,7 +227,7 @@ func (s *OpenAIQuotaAutoResetService) scanEnabledAccounts(ctx context.Context) { for page := 1; ; page++ { accounts, pageInfo, err := s.accountRepo.ListWithFilters(ctx, pagination.PaginationParams{ Page: page, PageSize: openAIAutoResetBatchSize, - }, PlatformOpenAI, AccountTypeOAuth, StatusActive, "", 0, "") + }, PlatformOpenAI, AccountTypeOAuth, StatusActive, "", 0, "", "") if err != nil { slog.Warn("openai_auto_reset_scan_failed", "page", page, "error", err) return diff --git a/backend/internal/service/openai_ws_ratelimit_signal_test.go b/backend/internal/service/openai_ws_ratelimit_signal_test.go index 13346cc46..0315a16b3 100644 --- a/backend/internal/service/openai_ws_ratelimit_signal_test.go +++ b/backend/internal/service/openai_ws_ratelimit_signal_test.go @@ -73,7 +73,7 @@ func (r *openAICodexExtraListRepo) SetRateLimited(_ context.Context, _ int64, re return nil } -func (r *openAICodexExtraListRepo) ListWithFilters(_ context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode string) ([]Account, *pagination.PaginationResult, error) { +func (r *openAICodexExtraListRepo) ListWithFilters(_ context.Context, params pagination.PaginationParams, platform, accountType, status, search string, groupID int64, privacyMode, model string) ([]Account, *pagination.PaginationResult, error) { _ = platform _ = accountType _ = status @@ -536,7 +536,7 @@ func TestAdminService_ListAccounts_ExhaustedCodexExtraDoesNotSetRateLimit(t *tes } svc := &adminServiceImpl{accountRepo: repo} - accounts, total, err := svc.ListAccounts(context.Background(), 1, 20, PlatformOpenAI, AccountTypeOAuth, "", "", 0, "", "", "") + accounts, total, err := svc.ListAccounts(context.Background(), 1, 20, PlatformOpenAI, AccountTypeOAuth, "", "", 0, "", "", "", "") require.NoError(t, err) require.Equal(t, int64(1), total) require.Len(t, accounts, 1) diff --git a/backend/internal/service/ops_concurrency.go b/backend/internal/service/ops_concurrency.go index 883707823..7e8cb56e4 100644 --- a/backend/internal/service/ops_concurrency.go +++ b/backend/internal/service/ops_concurrency.go @@ -35,7 +35,7 @@ func (s *OpsService) listAllAccountsForOps(ctx context.Context, platformFilter s accounts, pageInfo, err := s.accountRepo.ListWithFilters(ctx, pagination.PaginationParams{ Page: page, PageSize: opsAccountsPageSize, - }, platformFilter, "", "", "", groupID, "") + }, platformFilter, "", "", "", groupID, "", "") if err != nil { return nil, err } diff --git a/backend/internal/service/ratelimit_session_window_test.go b/backend/internal/service/ratelimit_session_window_test.go index bf7cc2bf0..efb441b93 100644 --- a/backend/internal/service/ratelimit_session_window_test.go +++ b/backend/internal/service/ratelimit_session_window_test.go @@ -84,7 +84,7 @@ func (m *sessionWindowMockRepo) Delete(context.Context, int64) error { panic( func (m *sessionWindowMockRepo) List(context.Context, pagination.PaginationParams) ([]Account, *pagination.PaginationResult, error) { panic("unexpected") } -func (m *sessionWindowMockRepo) ListWithFilters(context.Context, pagination.PaginationParams, string, string, string, string, int64, string) ([]Account, *pagination.PaginationResult, error) { +func (m *sessionWindowMockRepo) ListWithFilters(context.Context, pagination.PaginationParams, string, string, string, string, int64, string, string) ([]Account, *pagination.PaginationResult, error) { panic("unexpected") } func (m *sessionWindowMockRepo) ListAllWithFilters(context.Context, string, string, string, string, int64, string) ([]Account, error) { diff --git a/backend/internal/service/user_service.go b/backend/internal/service/user_service.go index 1853d3d2c..2fbc0d962 100644 --- a/backend/internal/service/user_service.go +++ b/backend/internal/service/user_service.go @@ -65,11 +65,15 @@ var ( // UserListFilters contains all filter options for listing users type UserListFilters struct { - EnterpriseID int64 // Current non-deleted enterprise membership; 0 means no filter. - Status string // User status filter - Role string // User role filter - Search string // Search in email, username - GroupName string // Filter by allowed group name (fuzzy match) + EnterpriseID int64 // Current non-deleted enterprise membership; 0 means no filter. + // HideEnterpriseEmployees 为 true 时仅保留"有效企业负责人":存在未软删除、 + // role=owner 且 status=active 的企业成员关系,且用户本身 status=active。 + // 与 CountActiveOwners 的定义一致;非企业用户与非负责人均被排除。 + HideEnterpriseEmployees bool + Status string // User status filter + Role string // User role filter + Search string // Search in email, username + GroupName string // Filter by allowed group name (fuzzy match) // APIKeyGroupID filters users who own at least one non-soft-deleted API key // bound to this group (api_keys.group_id). 0 = no filter. Covers all three // group types since it matches the key's group directly, not allowed_groups. diff --git a/frontend/src/api/admin/accounts.ts b/frontend/src/api/admin/accounts.ts index 2f859ab58..bd6fd2f32 100644 --- a/frontend/src/api/admin/accounts.ts +++ b/frontend/src/api/admin/accounts.ts @@ -51,6 +51,7 @@ export async function list( group?: string search?: string privacy_mode?: string + model?: string lite?: string include_scheduler_score?: string sort_by?: string @@ -93,6 +94,7 @@ export async function getUpstreamBillingRatesWithEtag( group?: string search?: string privacy_mode?: string + model?: string sort_by?: string sort_order?: 'asc' | 'desc' }, @@ -126,6 +128,7 @@ export async function listWithEtag( group?: string search?: string privacy_mode?: string + model?: string lite?: string include_scheduler_score?: string sort_by?: string @@ -742,6 +745,7 @@ export async function exportData(options?: { status?: string group?: string privacy_mode?: string + model?: string search?: string sort_by?: string sort_order?: 'asc' | 'desc' @@ -752,12 +756,13 @@ export async function exportData(options?: { if (options?.ids && options.ids.length > 0) { params.ids = options.ids.join(',') } else if (options?.filters) { - const { platform, type, status, group, privacy_mode, search, sort_by, sort_order } = options.filters + const { platform, type, status, group, privacy_mode, model, search, sort_by, sort_order } = options.filters if (platform) params.platform = platform if (type) params.type = type if (status) params.status = status if (group) params.group = group if (privacy_mode) params.privacy_mode = privacy_mode + if (model) params.model = model if (search) params.search = search if (sort_by) params.sort_by = sort_by if (sort_order) params.sort_order = sort_order diff --git a/frontend/src/api/admin/users.ts b/frontend/src/api/admin/users.ts index 10baf5b47..9b9674f45 100644 --- a/frontend/src/api/admin/users.ts +++ b/frontend/src/api/admin/users.ts @@ -73,6 +73,7 @@ export async function list( search?: string group_name?: string // fuzzy filter by allowed group name enterprise_id?: number + hide_enterprise_employees?: boolean // true = only active enterprise owners api_key_group_id?: number // filter users by the group their API keys are bound to attributes?: Record // attributeId -> value include_subscriptions?: boolean @@ -93,6 +94,7 @@ export async function list( group_name: filters?.group_name, api_key_group_id: filters?.api_key_group_id, enterprise_id: filters?.enterprise_id, + hide_enterprise_employees: filters?.hide_enterprise_employees, include_subscriptions: filters?.include_subscriptions, sort_by: filters?.sort_by, sort_order: filters?.sort_order diff --git a/frontend/src/api/keys.ts b/frontend/src/api/keys.ts index 85640eadb..4f7367785 100644 --- a/frontend/src/api/keys.ts +++ b/frontend/src/api/keys.ts @@ -111,6 +111,19 @@ export async function update(id: number, updates: UpdateApiKeyRequest): Promise< return data } +export interface RotateApiKeyResult { + id: number + key_hint: string + key?: string +} + +export async function rotate(id: number, operationId: string): Promise { + const { data } = await apiClient.post(`/keys/${id}/rotate`, undefined, { + headers: { 'Idempotency-Key': operationId } + }) + return data +} + export interface BulkUpdateApiKeysResult { succeededIds: number[] failures: Array<{ id: number; error: unknown }> @@ -162,6 +175,7 @@ export const keysAPI = { getById, create, update, + rotate, bulkUpdate, delete: deleteKey, toggleStatus diff --git a/frontend/src/components/admin/account/AccountTableFilters.vue b/frontend/src/components/admin/account/AccountTableFilters.vue index ce7009c66..b96eb4bbb 100644 --- a/frontend/src/components/admin/account/AccountTableFilters.vue +++ b/frontend/src/components/admin/account/AccountTableFilters.vue @@ -13,20 +13,33 @@ diff --git a/frontend/src/components/admin/account/__tests__/AccountTableFilters.modelFilter.spec.ts b/frontend/src/components/admin/account/__tests__/AccountTableFilters.modelFilter.spec.ts new file mode 100644 index 000000000..61a78b323 --- /dev/null +++ b/frontend/src/components/admin/account/__tests__/AccountTableFilters.modelFilter.spec.ts @@ -0,0 +1,58 @@ +import { describe, expect, it, vi } from 'vitest' +import { mount } from '@vue/test-utils' +import type { VueWrapper } from '@vue/test-utils' + +import AccountTableFilters from '../AccountTableFilters.vue' +import Select from '@/components/common/Select.vue' + +vi.mock('vue-i18n', async (importOriginal) => { + const actual = await importOriginal>() + return { + ...actual, + useI18n: () => ({ + t: (key: string) => key + }) + } +}) + +const mountFilters = () => mount(AccountTableFilters, { + props: { + searchQuery: '', + filters: {}, + groups: [] + } +}) + +const modelSelectOf = (wrapper: VueWrapper) => { + const selects = wrapper.findAllComponents(Select) + return selects[selects.length - 1] +} + +describe('AccountTableFilters model filter', () => { + it('reuses the existing model catalog with a searchable, clearable selector', () => { + const wrapper = mountFilters() + const modelSelect = modelSelectOf(wrapper) + + const options = modelSelect.props('options') as Array<{ value: string; label: string }> + expect(options[0]).toEqual({ value: '', label: 'admin.accounts.allModels' }) + expect(modelSelect.props('placeholder')).toBe('admin.accounts.filterByModel') + expect(modelSelect.props('searchable')).toBe(true) + expect(modelSelect.props('clearable')).toBe(true) + + const values = options.map(option => option.value) + expect(values).toContain('claude-opus-5') + expect(new Set(values).size).toBe(values.length) + expect(values.filter(value => value === 'claude-fable-5-1')).toHaveLength(1) + }) + + it('emits the selected model id and clears it back to an empty filter', async () => { + const wrapper = mountFilters() + const modelSelect = modelSelectOf(wrapper) + + modelSelect.vm.$emit('update:modelValue', 'claude-opus-5') + expect(wrapper.emitted('update:filters')?.at(-1)?.[0]).toEqual({ model: 'claude-opus-5' }) + + modelSelect.vm.$emit('update:modelValue', null) + expect(wrapper.emitted('update:filters')?.at(-1)?.[0]).toEqual({ model: '' }) + }) +}) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 6afd56b32..436b115c3 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -3,6 +3,8 @@ export default { title: 'Account Management', description: 'Manage AI platform accounts and credentials', createAccount: 'Create Account', + filterByModel: 'Filter by model', + allModels: 'All models', autoRefresh: 'Auto Refresh', enableAutoRefresh: 'Enable auto refresh', refreshInterval5s: '5 seconds', diff --git a/frontend/src/i18n/locales/en/admin/overview.ts b/frontend/src/i18n/locales/en/admin/overview.ts index b9db851aa..64f52e979 100644 --- a/frontend/src/i18n/locales/en/admin/overview.ts +++ b/frontend/src/i18n/locales/en/admin/overview.ts @@ -651,6 +651,7 @@ export default { }, enterpriseDeposit: 'Top up', enterpriseDepositTitle: 'Enterprise top-up - {name}', + hideEnterpriseEmployees: 'Hide enterprise employees', roles: { admin: 'Admin', user: 'User' diff --git a/frontend/src/i18n/locales/en/dashboard.ts b/frontend/src/i18n/locales/en/dashboard.ts index 4cb53bd04..2d51326e6 100644 --- a/frontend/src/i18n/locales/en/dashboard.ts +++ b/frontend/src/i18n/locales/en/dashboard.ts @@ -142,7 +142,7 @@ export default { showOnce: { replayed: 'This creation result was replayed. The full key was returned only by the first successful creation and cannot be retrieved again. Create a new key if you did not save it.', title: 'Save your API key now', - warning: 'This key is shown only once. Copy and save it now; if lost, you must create a new one. After closing, neither you nor administrators can view the full key again.', + warning: 'This key is shown only once. Copy and save it now. If you lose it, rotate the key or create a new one. After closing, neither you nor administrators can view the full key again.', copy: 'Copy full key', confirm: 'I saved the full key somewhere safe and understand that I cannot view it again after closing.', done: 'I saved it, close', @@ -154,6 +154,13 @@ export default { }, keyCreatedSuccess: 'API key created successfully', keyUpdatedSuccess: 'API key updated successfully', + rotateKey: 'Rotate', + rotateTitle: 'Rotate API key', + rotateConfirmMessage: 'Rotating “{name}” invalidates the old key. Save the new key shown once and update any clients still using the old one. Settings and usage stay the same.', + keyRotatedSuccess: 'API key rotated successfully', + rotationReplayed: 'Rotation completed, but the full key cannot be shown again. If you did not save it, start a new rotation.', + rotationConflict: 'This key changed and the list was refreshed. Check it before trying again.', + failedToRotate: 'Could not confirm the rotation. Please try again.', keyDeletedSuccess: 'API key deleted successfully', keyEnabledSuccess: 'API key enabled successfully', keyDisabledSuccess: 'API key disabled successfully', diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 41e73d4ec..123288cf4 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -3,6 +3,8 @@ export default { title: '账号管理', description: '管理 AI 平台账号和 Cookie', createAccount: '添加账号', + filterByModel: '按模型筛选', + allModels: '全部模型', autoRefresh: '自动刷新', enableAutoRefresh: '启用自动刷新', refreshInterval5s: '5 秒', diff --git a/frontend/src/i18n/locales/zh/admin/overview.ts b/frontend/src/i18n/locales/zh/admin/overview.ts index c2972e81c..f54ef0204 100644 --- a/frontend/src/i18n/locales/zh/admin/overview.ts +++ b/frontend/src/i18n/locales/zh/admin/overview.ts @@ -537,6 +537,7 @@ export default { }, enterpriseDeposit: '企业充值', enterpriseDepositTitle: '企业充值 - {name}', + hideEnterpriseEmployees: '隐藏企业员工', roles: { admin: '管理员', user: '用户' diff --git a/frontend/src/i18n/locales/zh/dashboard.ts b/frontend/src/i18n/locales/zh/dashboard.ts index 585cec635..230425ab3 100644 --- a/frontend/src/i18n/locales/zh/dashboard.ts +++ b/frontend/src/i18n/locales/zh/dashboard.ts @@ -142,7 +142,7 @@ export default { showOnce: { replayed: '创建结果已重放。完整 Key 只在首次创建时返回,无法再次取回;如果没有保存,请新建 Key。', title: 'API Key 只显示这一次', - warning: '只显示这一次,请立即复制保存;丢失后只能新建。关闭后,您和管理员都无法再查看完整 Key。', + warning: '只显示这一次,请立即复制保存;丢失后可以轮转或新建。关闭后,您和管理员都无法再查看完整 Key。', copy: '复制完整 Key', confirm: '我已将完整 Key 保存在安全的位置,理解关闭后无法再次查看。', done: '我已保存,关闭', @@ -154,6 +154,13 @@ export default { }, keyCreatedSuccess: 'API 密钥创建成功', keyUpdatedSuccess: 'API 密钥更新成功', + rotateKey: '轮转', + rotateTitle: '轮转 API 密钥', + rotateConfirmMessage: '轮转「{name}」后,旧密钥将失效。请保存仅显示一次的新密钥,并更新仍在使用旧密钥的客户端。现有配置和用量不变。', + keyRotatedSuccess: 'API 密钥已轮转', + rotationReplayed: '轮转已完成,完整密钥无法再次显示。如果未保存,请重新发起轮转。', + rotationConflict: '密钥已发生变化,列表已重新加载。请核对后再试。', + failedToRotate: '未能确认轮转结果,请重试。', keyDeletedSuccess: 'API 密钥删除成功', keyEnabledSuccess: 'API 密钥已启用', keyDisabledSuccess: 'API 密钥已禁用', diff --git a/frontend/src/views/admin/AccountsView.vue b/frontend/src/views/admin/AccountsView.vue index cc656383f..d0db6f7c2 100644 --- a/frontend/src/views/admin/AccountsView.vue +++ b/frontend/src/views/admin/AccountsView.vue @@ -589,6 +589,7 @@ type AccountBulkEditTarget = group?: string search?: string privacy_mode?: string + model?: string sort_by?: string sort_order?: AccountSortOrder } @@ -1234,6 +1235,7 @@ const buildUpstreamBillingRateFilters = () => { group: typeof rawParams.group === 'string' ? rawParams.group : '', search: typeof rawParams.search === 'string' ? rawParams.search : '', privacy_mode: typeof rawParams.privacy_mode === 'string' ? rawParams.privacy_mode : '', + model: typeof rawParams.model === 'string' ? rawParams.model : '', sort_by: sortState.sort_by, sort_order: sortState.sort_order } @@ -1518,6 +1520,7 @@ const refreshAccountsIncrementally = async () => { privacy_mode?: string group?: string search?: string + model?: string sort_by?: string sort_order?: AccountSortOrder @@ -2136,6 +2139,7 @@ const buildBulkEditFilterSnapshot = () => { group: typeof rawParams.group === 'string' ? rawParams.group : '', search: typeof rawParams.search === 'string' ? rawParams.search : '', privacy_mode: typeof rawParams.privacy_mode === 'string' ? rawParams.privacy_mode : '', + model: typeof rawParams.model === 'string' ? rawParams.model : '', sort_by: typeof rawParams.sort_by === 'string' ? rawParams.sort_by : '', sort_order: sortOrder } @@ -2216,6 +2220,7 @@ const buildAccountQueryFilters = () => ({ status: params.status || '', group: params.group || '', privacy_mode: params.privacy_mode || '', + model: params.model || '', search: params.search || '', sort_by: sortState.sort_by, sort_order: sortState.sort_order @@ -2261,6 +2266,8 @@ const accountMatchesCurrentFilters = (account: Account) => { } const search = String(filters.search || '').trim().toLowerCase() if (search && !account.name.toLowerCase().includes(search)) return false + // 模型支持依赖账号 model_mapping 的通配符与平台默认目录,服务端才是权威判定; + // 本地补丁无法安全推断,保留行等下一次列表刷新(避免误删仍有模型的账号)。 return true } const mergeRuntimeFields = (oldAccount: Account, updatedAccount: Account): Account => ({ diff --git a/frontend/src/views/admin/UsersView.vue b/frontend/src/views/admin/UsersView.vue index 878c155a2..ec55b7db7 100644 --- a/frontend/src/views/admin/UsersView.vue +++ b/frontend/src/views/admin/UsersView.vue @@ -72,6 +72,19 @@ /> + +
+ + + {{ t('admin.users.hideEnterpriseEmployees') }} + +
+