Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions backend/dev-docs/API_KEY_ROTATION.md
Original file line number Diff line number Diff line change
@@ -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。
2 changes: 1 addition & 1 deletion backend/internal/handler/admin/account_codex_import.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
10 changes: 7 additions & 3 deletions backend/internal/handler/admin/account_data.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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 != "" {
Expand All @@ -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) {
Expand Down
28 changes: 20 additions & 8 deletions backend/internal/handler/admin/account_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -653,13 +654,17 @@ 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 参数
search = strings.TrimSpace(search)
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)
Expand All @@ -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
Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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")
Expand All @@ -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")
Expand All @@ -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 {
Expand All @@ -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"`
}{
Expand All @@ -913,6 +919,7 @@ func buildAccountsListETag[T any](
AccountType: accountType,
Status: status,
Search: search,
Model: model,
Lite: lite,
Items: items,
}
Expand Down Expand Up @@ -2416,13 +2423,18 @@ 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,
Status: filters.Status,
Group: filters.Group,
Search: filters.Search,
PrivacyMode: filters.PrivacyMode,
Model: model,
}
}

Expand Down Expand Up @@ -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
Expand Down
53 changes: 53 additions & 0 deletions backend/internal/handler/admin/account_handler_list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand All @@ -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)
Expand Down
6 changes: 4 additions & 2 deletions backend/internal/handler/admin/admin_service_stub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ type stubAdminService struct {
search string
groupID int64
privacyMode string
model string
sortBy string
sortOrder string
calls int
Expand Down Expand Up @@ -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++
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions backend/internal/handler/admin/user_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}
Loading
Loading