完善管理员密钥权限并新增需确认的全权兼容模式

This commit is contained in:
lyen1688 committed 2026-11-01 23:52:35 +08:00
1 parent d851a38477
commit 194d69e636
61 files changed
+2922 -136

No files matched your search

@@ -1734,7 +1734,7 @@ func (h *AccountHandler) GetStats(c *gin.Context) {
stats, err := h.accountUsageService.GetAccountUsageStats(c.Request.Context(), accountID, startTime, endTime)
if err != nil {
response.ErrorFrom(c, err)
scopedOpenAIError(c, err)
return
}
@@ -24,7 +24,7 @@ func scopedAdminAccountDTO(a *service.Account, p adminaccess.Policy) gin.H {
groups = append(groups, g)
}
}
result := gin.H{"id": a.ID, "name": a.Name, "notes": a.Notes, "platform": a.Platform, "type": a.Type, "status": a.Status, "schedulable": a.Schedulable, "concurrency": a.Concurrency, "priority": a.Priority, "group_ids": groups}
result := gin.H{"id": a.ID, "name": a.Name, "notes": a.Notes, "platform": a.Platform, "type": a.Type, "status": a.Status, "schedulable": a.Schedulable, "concurrency": a.Concurrency, "priority": a.Priority, "group_ids": groups, "expires_at": a.ExpiresAt, "rate_limit_reset_at": a.RateLimitResetAt, "overload_until": a.OverloadUntil, "temp_unschedulable_until": a.TempUnschedulableUntil}
// 兼容原账户读取结构,仅返回模型映射,凭证及扩展字段继续脱敏。
if p.AllowsAccount("accounts.read", resource) {
mapping := map[string]string{}
@@ -42,12 +42,43 @@ func scopedAdminAccountDTO(a *service.Account, p adminaccess.Policy) gin.H {
}
result["credentials"] = gin.H{"model_mapping": mapping}
}
if p.AllowsAccount("accounts.identity.read", resource) {
credentials, _ := result["credentials"].(gin.H)
if credentials == nil {
credentials = gin.H{}
}
for _, key := range []string{"email", "plan_type", "subscription_expires_at"} {
if value, ok := a.Credentials[key].(string); ok {
credentials[key] = value
}
}
result["credentials"] = credentials
// 保留两处邮箱供调用方检查一致性,禁止回传其他扩展字段。
extra := gin.H{}
if value, ok := a.Extra["email"].(string); ok {
extra["email"] = value
}
result["extra"] = extra
result["created_at"] = a.CreatedAt
}
if p.AllowsAccount("accounts.usage.read", resource) {
extra, _ := result["extra"].(gin.H)
if extra == nil {
extra = gin.H{}
}
for _, key := range []string{"codex_usage_updated_at", "codex_7d_used_percent", "codex_7d_reset_at"} {
if value, ok := a.Extra[key]; ok {
extra[key] = value
}
}
result["extra"] = extra
}
return result
}
// ScopedAdminKeyAccounts 在原处理器前完成独立授权和安全输出。
func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) {
principal := adminaccess.FromContext(c.Request.Context())
principal := adminaccess.RestrictedFromContext(c.Request.Context())
if principal == nil {
return
}
@@ -70,6 +101,9 @@ func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) {
h.scopedAdminImportCodexSession(c)
return
}
if h.scopedAdminStatistics(c) {
return
}
api, ok := h.adminService.(service.ScopedAdminAccounts)
if !ok {
response.Error(c, 503, "受限账户服务不可用")
@@ -85,7 +119,17 @@ func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) {
if size < 1 || size > 100 {
size = 20
}
accounts, total, err := api.ScopedAdminList(ctx, pagination.PaginationParams{Page: page, PageSize: size}, c.Query("platform"), c.Query("type"), c.Query("status"), c.Query("search"))
groupID := int64(0)
// 空分组筛选与省略参数均表示不按分组筛选。
if raw := c.Query("group"); raw != "" {
var err error
groupID, err = strconv.ParseInt(raw, 10, 64)
if err != nil || groupID < -1 {
response.BadRequest(c, "分组筛选无效")
return
}
}
accounts, total, err := api.ScopedAdminList(ctx, pagination.PaginationParams{Page: page, PageSize: size}, c.Query("platform"), c.Query("type"), c.Query("status"), c.Query("search"), groupID)
if err != nil {
response.Error(c, 503, "账户查询失败")
return
@@ -96,10 +140,11 @@ func (h *AccountHandler) ScopedAdminKeyAccounts(c *gin.Context) {
items = append(items, scopedAdminAccountDTO(&accounts[i], principal.Policy))
}
}
response.Success(c, gin.H{"items": items, "total": total, "page": page, "page_size": size})
response.Paginated(c, items, total, page, size)
return
}
id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
if (path == base+"/:id" || path == base+"/:id/models") && c.Request.Method == "GET" {
a, err := h.adminService.GetAccount(ctx, id)
if err != nil || a == nil || !principal.Policy.AllowsAccount("accounts.read", adminaccess.Account{ID: id, GroupIDs: accountGroupIDs(a), Type: accountType(a), Platform: accountPlatform(a)}) {
@@ -84,7 +84,7 @@ type scopedBulkAccountService struct {
fields map[string]json.RawMessage
}
func (s *scopedBulkAccountService) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]service.Account, int64, error) {
func (s *scopedBulkAccountService) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]service.Account, int64, error) {
panic("不应读取全站账户")
}
func (s *scopedBulkAccountService) ScopedAdminWrite(_ context.Context, id int64, _ string, fields map[string]json.RawMessage, _ func(context.Context, *service.Account) (*service.Account, error)) (*service.Account, error) {
@@ -40,7 +40,7 @@ type scopedCommitAccounts struct {
fail bool
}
func (*scopedCommitAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]service.Account, int64, error) {
func (*scopedCommitAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]service.Account, int64, error) {
panic("不应查询列表")
}
func (s *scopedCommitAccounts) ScopedAdminWrite(_ context.Context, id int64, _ string, _ map[string]json.RawMessage, _ func(context.Context, *service.Account) (*service.Account, error)) (*service.Account, error) {
@@ -18,12 +18,12 @@ import (
)
func scopedAdminGroupModelsDTO(g *service.Group) gin.H {
return gin.H{"id": g.ID, "name": g.Name, "platform": g.Platform, "model_allowlist": g.ModelAllowlist}
return gin.H{"id": g.ID, "name": g.Name, "platform": g.Platform, "status": g.Status, "model_allowlist": g.ModelAllowlist}
}
// ScopedAdminKeyGroupModels 接管分组模型接口,禁止复用可修改费率等字段的完整处理器。
func (h *GroupHandler) ScopedAdminKeyGroupModels(c *gin.Context) {
p := adminaccess.FromContext(c.Request.Context())
p := adminaccess.RestrictedFromContext(c.Request.Context())
if p == nil {
return
}
@@ -72,7 +72,8 @@ func (h *GroupHandler) ScopedAdminKeyGroupModels(c *gin.Context) {
if c.Request.Method == http.MethodPut {
permission = "groups.models.write"
}
allowed := p.Policy.AllowsGroupConfig(permission, g.ID, g.Platform) || (c.Request.Method == http.MethodGet && fullRead)
basicRead := c.Request.Method == http.MethodGet && path == base && p.Policy.AllowsGroupConfig("groups.list.read", g.ID, g.Platform)
allowed := basicRead || p.Policy.AllowsGroupConfig(permission, g.ID, g.Platform) || (c.Request.Method == http.MethodGet && fullRead)
if !allowed {
response.Error(c, 404, "分组不存在")
return
@@ -89,7 +90,7 @@ func (h *GroupHandler) ScopedAdminKeyGroupModels(c *gin.Context) {
if fullRead {
response.Success(c, dto.GroupFromServiceAdmin(g))
} else {
response.Success(c, scopedAdminGroupModelsDTO(g))
response.Success(c, scopedAdminGroupReadDTO(g, p.Policy))
}
return
}
@@ -157,7 +158,7 @@ func (h *GroupHandler) scopedAdminListGroupModels(c *gin.Context) {
}
out := make([]gin.H, 0, len(groups))
for i := range groups {
out = append(out, scopedAdminGroupModelsDTO(&groups[i]))
out = append(out, scopedAdminGroupReadDTO(&groups[i], adminaccess.FromContext(c.Request.Context()).Policy))
}
if all {
response.Success(c, out)
@@ -165,3 +166,11 @@ func (h *GroupHandler) scopedAdminListGroupModels(c *gin.Context) {
response.Paginated(c, out, total, page, size)
}
}
// 基本分组读取不能隐式获得模型配置。
func scopedAdminGroupReadDTO(g *service.Group, policy adminaccess.Policy) gin.H {
if policy.AllowsGroupConfig("groups.models.read", g.ID, g.Platform) {
return scopedAdminGroupModelsDTO(g)
}
return gin.H{"id": g.ID, "name": g.Name, "platform": g.Platform, "status": g.Status}
}
@@ -0,0 +1,30 @@
//go:build unit
package admin
import (
"context"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"net/http/httptest"
"testing"
)
func TestAdminFullAccessIdempotencyScopeIsolation(t *testing.T) {
scope := func(p *adminaccess.Principal) string {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("POST", "/", nil)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9})
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(context.Background(), p))
return adminActorScope(c)
}
jwt := scope(nil)
full := scope(&adminaccess.Principal{KeyID: "one", Policy: adminaccess.Policy{FullAccess: true}})
restricted := scope(&adminaccess.Principal{KeyID: "one", Policy: adminaccess.Policy{}})
other := scope(&adminaccess.Principal{KeyID: "two", Policy: adminaccess.Policy{FullAccess: true}})
require.NotEqual(t, jwt, full)
require.NotEqual(t, full, restricted)
require.NotEqual(t, full, other)
}
@@ -0,0 +1,109 @@
package admin
import (
"strconv"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
func (h *OpenAIOAuthHandler) scopedOpenAIAllowed(c *gin.Context, id int64, action string, parent bool) bool {
if adminaccess.RestrictedFromContext(c.Request.Context()) == nil {
return true
}
_, ok := scopedAuthorizedAccount(c, h.adminService, id, action, parent)
return ok
}
func (h *OpenAIOAuthHandler) scopedOpenAIHasPermission(c *gin.Context, id int64, action string, parent bool) bool {
p := adminaccess.RestrictedFromContext(c.Request.Context())
if p == nil {
return true
}
if h.adminService == nil {
return false
}
a, err := h.adminService.GetAccount(c.Request.Context(), id)
if err != nil || a == nil || !p.Policy.AllowsAccount(action, scopedAccountResource(a)) {
return false
}
if parent && a.IsShadow() {
if a.ParentAccountID == nil {
return false
}
source, err := h.adminService.GetAccount(c.Request.Context(), *a.ParentAccountID)
return err == nil && source != nil && !source.IsShadow() && p.Policy.AllowsAccount(action, scopedAccountResource(source))
}
return true
}
func scopedOpenAIError(c *gin.Context, err error) {
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
scopedAdminAccountError(c, err)
return
}
response.ErrorFrom(c, err)
}
func (h *OpenAIOAuthHandler) scopedQuotaDTO(c *gin.Context, id int64, u *service.OpenAIQuotaUsage) *service.OpenAIQuotaUsage {
if u == nil {
return nil
}
safe := *u
p := adminaccess.RestrictedFromContext(c.Request.Context())
if p == nil {
return &safe
}
identity := h.scopedOpenAIHasPermission(c, id, "accounts.identity.read", true)
if !identity {
safe.UserID = ""
safe.AccountID = ""
safe.Email = ""
safe.PlanType = ""
}
return &safe
}
func (h *OpenAIOAuthHandler) scopedOpenAIQuota(c *gin.Context, refresh bool) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil || id <= 0 {
response.BadRequest(c, "账户 ID 无效")
return
}
if !h.scopedOpenAIAllowed(c, id, "openai.quota.read", true) {
return
}
if h.quotaService == nil {
response.Error(c, 503, "账户额度服务不可用")
return
}
u, err := h.quotaService.QueryUsage(c.Request.Context(), id)
if err != nil {
scopedOpenAIError(c, err)
return
}
if u == nil {
response.Error(c, 502, "账户额度查询失败")
return
}
safe := h.scopedQuotaDTO(c, id, u)
// 读取只更新展示快照,绝不通知可能消耗重置次数的自动任务。
if !refresh {
response.Success(c, safe)
return
}
result := openAIQuotaRefreshResponse{OpenAIQuotaUsage: *safe}
result.CreditsCachePersisted = h.quotaService.CacheCreditsSnapshot(c.Request.Context(), id, safe) == nil
result.CachePersisted = h.quotaService.CacheResetCreditsSnapshot(c.Request.Context(), id, safe.RateLimitResetCredits) == nil
response.Success(c, result)
}
func (h *OpenAIOAuthHandler) scopedReferralDTO(c *gin.Context, e *service.OpenAIReferralEligibility) *service.OpenAIReferralEligibility {
if e == nil || adminaccess.RestrictedFromContext(c.Request.Context()) == nil {
return e
}
// 邀请资格只展示容量和流程字段,不回传上游自由文本及收件人资料。
return &service.OpenAIReferralEligibility{ShouldShow: e.ShouldShow, RemainingSendCapacity: e.RemainingSendCapacity, RemainingRewardCapacity: e.RemainingRewardCapacity, RequiresExplicitConfirmation: e.RequiresExplicitConfirmation, OfferID: e.OfferID, ProgramID: e.ProgramID, AvailableInvites: e.AvailableInvites, FetchedAt: e.FetchedAt}
}
@@ -0,0 +1,175 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type permissionsProxyService struct {
service.AdminService
proxy *service.Proxy
}
func (s *permissionsProxyService) GetProxy(context.Context, int64) (*service.Proxy, error) {
return s.proxy, nil
}
func TestScopedAdminPermissionsRefreshRejectsUnavailableProxyBeforeNetwork(t *testing.T) {
gin.SetMode(gin.TestMode)
expired := time.Now().Add(-time.Hour)
for _, proxy := range []*service.Proxy{nil, {Status: "inactive"}, {Status: "active", ExpiresAt: &expired}} {
h := &OpenAIOAuthHandler{adminService: &permissionsProxyService{proxy: proxy}}
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{GlobalPermissions: []string{"openai.tokens.refresh"}}}))
})
r.POST("/api/v1/admin/openai/refresh-token", h.RefreshToken)
req := httptest.NewRequest("POST", "/api/v1/admin/openai/refresh-token", strings.NewReader(`{"refresh_token":"TEST_SECRET","proxy_id":14}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, 400, w.Code)
require.NotContains(t, w.Body.String(), "SECRET")
}
}
type scopedPermissionAccountService struct {
scopedBulkAccountService
listGroupID int64
}
func (s *scopedPermissionAccountService) ScopedAdminList(_ context.Context, _ pagination.PaginationParams, _, _, _, _ string, groupID int64) ([]service.Account, int64, error) {
s.listGroupID = groupID
return []service.Account{{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}}, 1, nil
}
func TestScopedAdminPermissionPaginationContract(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name, query string
groupID int64
invalid bool
}{
{"无筛选", "page=1&page_size=100", 0, false},
{"空分组", "group=", 0, false},
{"补号前全局查重", "platform=openai&type=oauth&status=&group=&lite=1&include_scheduler_score=0&sort_by=id&sort_order=asc&page=1&page_size=100&timezone=Asia%2FShanghai", 0, false},
{"监控分组", "platform=openai&type=oauth&status=&group=2&lite=1&include_scheduler_score=0&sort_by=id&sort_order=asc&page=1&page_size=100&timezone=Asia%2FShanghai", 2, false},
{"查询限流账户", "platform=openai&type=oauth&status=rate_limited&group=2&lite=1&include_scheduler_score=0&sort_by=id&sort_order=asc&page=1&page_size=100&timezone=Asia%2FShanghai", 2, false},
{"未分组", "group=-1", -1, false},
{"非法负数", "group=-2", 0, true},
{"非法文本", "group=invalid", 0, true},
{"空白字符", "group=%20", 0, true},
{"溢出数值", "group=9999999999999999999999", 0, true},
} {
t.Run(tc.name, func(t *testing.T) {
r := gin.New()
svc := &scopedPermissionAccountService{listGroupID: -99}
h := &AccountHandler{adminService: svc}
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}}}))
})
r.Use(h.ScopedAdminKeyAccounts)
r.GET("/api/v1/admin/accounts", func(c *gin.Context) { t.Fatal("不应调用全权处理器") })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts?"+tc.query, nil))
if tc.invalid {
require.Equal(t, 400, w.Code, w.Body.String())
require.Equal(t, int64(-99), svc.listGroupID, "无效筛选不能触达账户查询")
return
}
require.Equal(t, 200, w.Code, "账户查询失败(HTTP %d):%s", w.Code, w.Body.String())
require.Equal(t, tc.groupID, svc.listGroupID)
var body struct {
Data map[string]any `json:"data"`
}
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
require.Equal(t, float64(1), body.Data["pages"], "标准分页必须包含 pages")
require.Equal(t, float64(1), body.Data["page"])
})
}
}
func (s *scopedPermissionAccountService) GetAccount(context.Context, int64) (*service.Account, error) {
return &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{2, 3}, Credentials: map[string]any{"email": "test@example.com", "plan_type": "plus", "access_token": "SECRET"}, Extra: map[string]any{"email": "test@example.com", "codex_usage_updated_at": "2026-10-24T00:00:00Z", "codex_7d_used_percent": 100, "codex_7d_reset_at": "2026-10-30T00:00:00Z", "private": "SECRET"}}, nil
}
func TestScopedAdminPermissionIdentityAndUsageAreIndependent(t *testing.T) {
for _, permissions := range [][]string{{"accounts.read"}, {"accounts.read", "accounts.identity.read"}, {"accounts.read", "accounts.usage.read"}, {"accounts.read", "accounts.identity.read", "accounts.usage.read"}} {
r := gin.New()
policy := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: permissions, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}
h := &AccountHandler{adminService: &scopedPermissionAccountService{}}
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: policy}))
})
r.Use(h.ScopedAdminKeyAccounts)
r.GET("/api/v1/admin/accounts/:id", func(c *gin.Context) { t.Fatal("不能调用全权读取") })
r.GET("/api/v1/admin/accounts/:id/usage", func(c *gin.Context) { t.Fatal("不能绕过额度授权") })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts/1", nil))
require.Equal(t, 200, w.Code)
require.NotContains(t, w.Body.String(), "SECRET")
require.Contains(t, w.Body.String(), `"group_ids":[2]`)
a := adminaccess.Account{ID: 1, GroupIDs: []int64{2}, Type: "oauth", Platform: "openai"}
require.Equal(t, policy.AllowsAccount("accounts.identity.read", a), strings.Contains(w.Body.String(), "test@example.com"))
require.Equal(t, policy.AllowsAccount("accounts.usage.read", a), strings.Contains(w.Body.String(), "codex_7d_used_percent"))
w = httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts/1/usage?source=active&force=true", nil))
want := 404
if policy.AllowsAccount("accounts.usage.read", a) {
want = 503
} // 已授权才会触达尚未接线的额度服务。
require.Equal(t, want, w.Code)
policy.Rules[0].GroupIDs = []int64{99}
w = httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/accounts/1/usage", nil))
require.Equal(t, 404, w.Code)
}
}
type scopedBasicGroupService struct{ service.AdminService }
func (*scopedBasicGroupService) GetGroup(context.Context, int64) (*service.Group, error) {
return &service.Group{ID: 1, Name: "基本组", Platform: "openai", Status: "active"}, nil
}
func TestScopedAdminBasicGroupReadDoesNotReturnModels(t *testing.T) {
policy := adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.list.read"}, GroupIDs: []int64{1}, Platforms: []string{"openai"}}}}
h := &GroupHandler{adminService: &scopedBasicGroupService{}}
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: policy}))
})
r.Use(h.ScopedAdminKeyGroupModels)
r.GET("/api/v1/admin/groups/:id", func(c *gin.Context) { t.Fatal("不能调用完整处理器") })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/admin/groups/1", nil))
require.Equal(t, 200, w.Code, w.Body.String())
require.JSONEq(t, `{"code":0,"message":"success","data":{"id":1,"name":"基本组","platform":"openai","status":"active"}}`, w.Body.String())
}
func TestScopedAdminPermissionRefreshRejectsMissingGlobalGrant(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, policy := range []adminaccess.Policy{{}, {Rules: []adminaccess.Rule{{Permissions: []string{"accounts.refresh"}, AllGroups: true, AccountTypes: []string{"oauth"}}}}} {
h := &OpenAIOAuthHandler{}
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: policy}))
})
r.POST("/api/v1/admin/openai/refresh-token", h.RefreshToken)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/api/v1/admin/openai/refresh-token", strings.NewReader(`{"refresh_token":"SECRET"}`)))
require.Equal(t, 403, w.Code)
require.NotContains(t, w.Body.String(), "SECRET")
}
}
@@ -31,7 +31,7 @@ func scopedProxyDTO(p service.Proxy) scopedProxyOption {
// scopedAdminProxyRead 对代理读取限定数量;无分页的 /all 从全池抽样。
func (h *ProxyHandler) scopedAdminProxyRead(c *gin.Context) bool {
principal := adminaccess.FromContext(c.Request.Context())
principal := adminaccess.RestrictedFromContext(c.Request.Context())
if principal == nil {
return false
}
@@ -0,0 +1,233 @@
package admin
import (
"context"
"slices"
"strconv"
"strings"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
type scopedAccountReader interface {
GetAccount(context.Context, int64) (*service.Account, error)
}
func scopedAccountResource(a *service.Account) adminaccess.Account {
return adminaccess.Account{ID: a.ID, GroupIDs: a.GroupIDs, Platform: a.Platform, Type: a.Type}
}
// 仅校验实际读取对象;上游凭证来自母账户时,母账户必须同时获授权。
func scopedAuthorizedAccount(c *gin.Context, reader scopedAccountReader, id int64, action string, parent bool) (*service.Account, bool) {
p := adminaccess.RestrictedFromContext(c.Request.Context())
if p == nil {
return nil, true
}
if reader == nil || id <= 0 {
response.Error(c, 404, "账户不存在")
return nil, false
}
a, err := reader.GetAccount(c.Request.Context(), id)
if err != nil || a == nil || !p.Policy.AllowsAccount(action, scopedAccountResource(a)) {
response.Error(c, 404, "账户不存在")
return nil, false
}
if parent && a.IsShadow() {
if a.ParentAccountID == nil || *a.ParentAccountID == id {
response.Error(c, 404, "账户不存在")
return nil, false
}
source, err := reader.GetAccount(c.Request.Context(), *a.ParentAccountID)
if err != nil || source == nil || source.IsShadow() || !p.Policy.AllowsAccount(action, scopedAccountResource(source)) {
response.Error(c, 404, "账户不存在")
return nil, false
}
}
return a, true
}
func (h *AccountHandler) scopedAdminStatistics(c *gin.Context) bool {
path := strings.TrimPrefix(c.FullPath(), "/api/v1/admin/accounts")
action := ""
switch {
case c.Request.Method == "GET" && (path == "/:id/today-stats" || path == "/:id/stats"):
action = "accounts.stats.read"
case c.Request.Method == "GET" && path == "/:id/usage":
action = "accounts.usage.read"
case c.Request.Method == "POST" && path == "/today-stats/batch":
action = "accounts.stats.read"
case c.Request.Method == "POST" && path == "/usage/batch":
action = "accounts.usage.read"
default:
return false
}
if strings.HasSuffix(path, "/batch") {
var req BatchUsageRequest
if c.ShouldBindJSON(&req) != nil || len(req.AccountIDs) == 0 || len(req.AccountIDs) > 100 {
response.BadRequest(c, "请明确指定 1 至 100 个账户 ID")
return true
}
ids := make([]int64, 0, len(req.AccountIDs))
accounts := map[int64]*service.Account{}
for _, id := range req.AccountIDs {
if id <= 0 {
response.BadRequest(c, "账户 ID 无效")
return true
}
if slices.Contains(ids, id) {
continue
}
a, ok := scopedAuthorizedAccount(c, h.adminService, id, action, action == "accounts.usage.read")
if !ok {
return true
}
ids = append(ids, id)
accounts[id] = a
}
if h.accountUsageService == nil {
response.Error(c, 503, "账户额度服务不可用")
return true
}
// 不读取全权批量缓存,避免不同权限共享 ETag 或未裁剪结果。
if action == "accounts.stats.read" {
stats, err := h.accountUsageService.GetTodayStatsBatch(c.Request.Context(), ids)
if err != nil {
response.Error(c, 502, "账户统计查询失败")
return true
}
response.Success(c, gin.H{"stats": stats})
return true
}
usage, errs, err := h.accountUsageService.GetUsageBatch(c.Request.Context(), ids, req.Force)
if err != nil {
response.Error(c, 502, "账户额度查询失败")
return true
}
safe := map[int64]any{}
for id, u := range usage {
if a := accounts[id]; a != nil && u != nil {
safe[id] = scopedUsageDTO(u, adminaccess.RestrictedFromContext(c.Request.Context()).Policy, a)
}
}
safeErrors := map[int64]string{}
for id := range errs {
if accounts[id] != nil {
safeErrors[id] = "账户额度查询失败"
}
}
response.Success(c, gin.H{"usage": safe, "errors": safeErrors})
return true
}
id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
a, ok := scopedAuthorizedAccount(c, h.adminService, id, action, action == "accounts.usage.read")
if !ok {
return true
}
if h.accountUsageService == nil {
response.Error(c, 503, "账户额度服务不可用")
return true
}
switch path {
case "/:id/today-stats":
stats, err := h.accountUsageService.GetTodayStats(c.Request.Context(), id)
if err != nil {
response.Error(c, 502, "账户统计查询失败")
} else {
response.Success(c, stats)
}
case "/:id/stats":
h.GetStats(c)
case "/:id/usage":
var u *service.UsageInfo
var err error
if c.Query("source") == "passive" {
u, err = h.accountUsageService.GetPassiveUsage(c.Request.Context(), id)
} else {
u, err = h.accountUsageService.GetUsage(c.Request.Context(), id, c.Query("force") == "true")
}
if err != nil || u == nil {
response.Error(c, 502, "账户额度查询失败")
} else {
response.Success(c, scopedUsageDTO(u, adminaccess.RestrictedFromContext(c.Request.Context()).Policy, a))
}
}
return true
}
func scopedUsageDTO(u *service.UsageInfo, p adminaccess.Policy, a *service.Account) gin.H {
stats := p.AllowsAccount("accounts.stats.read", scopedAccountResource(a))
window := func(w *service.UsageProgress) *service.UsageProgress {
if w == nil {
return nil
}
safe := *w
if !stats {
safe.WindowStats = nil
}
return &safe
}
out := gin.H{
"source": u.Source,
"updated_at": u.UpdatedAt,
"five_hour": window(u.FiveHour),
"seven_day": window(u.SevenDay),
"seven_day_sonnet": window(u.SevenDaySonnet),
"seven_day_fable": window(u.SevenDayFable),
"gemini_shared_daily": window(u.GeminiSharedDaily),
"gemini_pro_daily": window(u.GeminiProDaily),
"gemini_flash_daily": window(u.GeminiFlashDaily),
"gemini_shared_minute": window(u.GeminiSharedMinute),
"gemini_pro_minute": window(u.GeminiProMinute),
"gemini_flash_minute": window(u.GeminiFlashMinute),
"thirty_day": window(u.ThirtyDay),
"antigravity_quota": u.AntigravityQuota,
"antigravity_quota_details": u.AntigravityQuotaDetails,
"ai_credits": u.AICredits,
"grok_request_quota": u.GrokRequestQuota,
"grok_token_quota": u.GrokTokenQuota,
"grok_retry_after_seconds": u.GrokRetryAfterSeconds,
"grok_quota_snapshot_state": u.GrokQuotaSnapshotState,
"grok_free_token_limit": u.GrokFreeTokenLimit,
"needs_reauth": u.NeedsReauth,
"needs_verify": u.NeedsVerify,
"is_banned": u.IsBanned,
"is_forbidden": u.IsForbidden,
}
if p.AllowsAccount("accounts.identity.read", scopedAccountResource(a)) {
out["subscription_tier"] = u.SubscriptionTier
out["subscription_tier_raw"] = u.SubscriptionTierRaw
}
if u.GrokBilling != nil {
billing := *u.GrokBilling
if !p.AllowsAccount("accounts.identity.read", scopedAccountResource(a)) {
billing.Plan = ""
billing.TopUpMethod = ""
billing.IsUnifiedBillingUser = false
}
if !stats {
billing.UsedCents = nil
billing.IncludedUsedCents = nil
billing.MonthlyUsed = nil
billing.OnDemandUsed = nil
}
out["grok_billing"] = &billing
}
if stats {
out["grok_local_usage"] = u.GrokLocalUsage
out["grok_local_usage_24h"] = u.GrokLocalUsage24h
out["grok_local_usage_7d"] = u.GrokLocalUsage7d
out["grok_local_usage_monthly"] = u.GrokLocalUsageMonthly
}
if u.Error != "" {
out["error"] = "上游额度查询失败"
}
switch u.ErrorCode {
case "forbidden", "unauthenticated", "rate_limited", "network_error":
out["error_code"] = u.ErrorCode
}
return out
}
@@ -0,0 +1,239 @@
//go:build unit
package admin
import (
"context"
"encoding/json"
"fmt"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/xai"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type scopedStatisticsAccounts struct {
service.AdminService
accounts map[int64]*service.Account
}
func (s *scopedStatisticsAccounts) GetAccount(_ context.Context, id int64) (*service.Account, error) {
return s.accounts[id], nil
}
func statisticsPolicy(permission string) adminaccess.Policy {
return adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{permission}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}
}
func statisticsContext(c *gin.Context, permission string) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{Policy: statisticsPolicy(permission)}))
}
func TestScopedAdminStatisticsRejectBeforeCacheOrService(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, 2: {ID: 2, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}}}
h := &AccountHandler{adminService: svc}
for _, path := range []string{"/api/v1/admin/accounts/1/today-stats", "/api/v1/admin/accounts/1/stats", "/api/v1/admin/accounts/today-stats/batch", "/api/v1/admin/accounts/usage/batch"} {
t.Run(path, func(t *testing.T) {
r := gin.New()
r.Use(func(c *gin.Context) { statisticsContext(c, "accounts.read") })
r.Use(h.ScopedAdminKeyAccounts)
method := "GET"
if strings.Contains(path, "batch") {
method = "POST"
}
r.Handle(method, strings.Replace(path, "/1/", "/:id/", 1), func(c *gin.Context) { t.Fatal("不得调用原处理器") })
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(`{"account_ids":[1,2]}`)))
require.Equal(t, 404, w.Code, w.Body.String())
})
}
}
func TestScopedAdminOpenAIRejectsBeforeUpstream(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}}}
stub := &referralHandlerStub{}
h := &OpenAIOAuthHandler{adminService: svc, referralService: stub}
r := gin.New()
r.Use(func(c *gin.Context) { statisticsContext(c, "accounts.read") })
r.POST("/:id/referrals/invite", h.SendReferralInvite)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", "/1/referrals/invite", strings.NewReader(`{"email":"friend@example.com","program_id":"codex_referral_consumer","confirmed":true}`)))
require.Equal(t, 404, w.Code, w.Body.String())
require.Zero(t, stub.sends)
}
func TestScopedAdminUsageProjectionKeepsPlatformQuotaAndHidesCosts(t *testing.T) {
a := &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}
u := &service.UsageInfo{FiveHour: &service.UsageProgress{Utilization: 25, WindowStats: &service.WindowStats{Cost: 123}}, SevenDaySonnet: &service.UsageProgress{Utilization: 30}, GeminiProDaily: &service.UsageProgress{Utilization: 40}, AntigravityQuota: map[string]*service.AntigravityModelQuota{"model": {Utilization: 50}}, Error: "TOKEN_SECRET", ValidationURL: "URL_SECRET", ForbiddenReason: "IDENTITY_SECRET"}
out := scopedUsageDTO(u, statisticsPolicy("accounts.usage.read"), a)
require.Nil(t, out["five_hour"].(*service.UsageProgress).WindowStats)
require.NotNil(t, out["seven_day_sonnet"])
require.NotNil(t, out["gemini_pro_daily"])
require.NotNil(t, out["antigravity_quota"])
raw, err := json.Marshal(out)
require.NoError(t, err)
require.NotContains(t, string(raw), "SECRET")
require.NotContains(t, string(raw), "123")
require.NotNil(t, u.FiveHour.WindowStats, "裁剪不能更改共享缓存")
}
func TestScopedAdminOpenAIQuotaActionsAndIdentity(t *testing.T) {
for _, tc := range []struct {
action, path, method string
allow bool
}{
{"openai.quota.read", "/1/quota", "GET", true}, {"openai.quota.read", "/1/quota/refresh", "POST", true},
{"accounts.usage.read", "/1/quota", "GET", false}, {"openai.quota.reset", "/1/quota", "GET", false},
} {
t.Run(tc.action+tc.path, func(t *testing.T) {
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}}}
stub := &openAIQuotaWorkflowStub{queryResult: &service.OpenAIQuotaUsage{UserID: "IDENTITY_SECRET", Email: "IDENTITY_SECRET", AccountID: "IDENTITY_SECRET", PlanType: "IDENTITY_SECRET", RateLimit: &service.OpenAIRateLimit{PrimaryWindow: &service.OpenAIRateLimitWindow{UsedPercent: 23}}, RateLimitResetCredits: &service.OpenAIRateLimitResetCredits{AvailableCount: 3}}}
h := &OpenAIOAuthHandler{adminService: svc, quotaService: stub}
r := gin.New()
r.Use(func(c *gin.Context) { statisticsContext(c, tc.action) })
r.GET("/:id/quota", h.QueryQuota)
r.POST("/:id/quota/refresh", h.RefreshQuota)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, nil))
if tc.allow {
require.Equal(t, 200, w.Code, w.Body.String())
require.Equal(t, 1, stub.queryCalls)
require.Contains(t, w.Body.String(), `"available_count":3`)
require.Contains(t, w.Body.String(), `"used_percent":23`)
} else {
require.Equal(t, 404, w.Code)
require.Zero(t, stub.queryCalls)
require.Zero(t, stub.cacheCalls)
}
require.NotContains(t, w.Body.String(), "SECRET")
})
}
}
func TestScopedAdminAccountScopeAndShadowSource(t *testing.T) {
parent := int64(2)
for _, tc := range []struct {
name string
a, source *service.Account
rules []adminaccess.Rule
allowed bool
}{
{"同规则", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, nil, nil, true},
{"其他组", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}, nil, nil, false},
{"其他平台", &service.Account{ID: 1, Platform: "anthropic", Type: "oauth", GroupIDs: []int64{1}}, nil, nil, false},
{"其他类型", &service.Account{ID: 1, Platform: "openai", Type: "apikey", GroupIDs: []int64{1}}, nil, nil, false},
{"母账户越权", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}, ParentAccountID: &parent}, &service.Account{ID: 2, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}, nil, false},
{"不能拼接规则", &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, nil, []adminaccess.Rule{{Permissions: []string{"openai.quota.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"apikey"}}, {Permissions: []string{"openai.quota.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}}}, false},
} {
t.Run(tc.name, func(t *testing.T) {
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: tc.a, 2: tc.source}}
r := gin.New()
r.Use(func(c *gin.Context) {
statisticsContext(c, "openai.quota.read")
if tc.rules != nil {
p := adminaccess.FromContext(c.Request.Context())
p.Policy.Rules = tc.rules
}
})
r.GET("/:id/quota", func(c *gin.Context) {
_, ok := scopedAuthorizedAccount(c, svc, 1, "openai.quota.read", true)
if ok {
c.Status(204)
}
})
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/1/quota", nil))
want := 404
if tc.allowed {
want = 204
}
require.Equal(t, want, w.Code, w.Body.String())
})
}
}
func TestScopedAdminMutationResponseRequiresReadPermission(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, read := range []bool{false, true} {
for _, kind := range []string{"reset", "invite"} {
t.Run(fmt.Sprintf("%s/read=%v", kind, read), func(t *testing.T) {
count := 2
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}}}
quota := &openAIQuotaWorkflowStub{resetResult: &service.OpenAIQuotaResetResult{Code: "success"}, queryResult: &service.OpenAIQuotaUsage{RateLimitResetCredits: &service.OpenAIRateLimitResetCredits{AvailableCount: 3}, Email: "IDENTITY_SECRET"}}
referral := &referralHandlerStub{eligibility: &service.OpenAIReferralEligibility{ShouldShow: true, AvailableInvites: &count}}
h := &OpenAIOAuthHandler{adminService: svc, quotaService: quota, referralService: referral, rateLimitService: &openAIAccountStateRecovererStub{}}
action, readAction, path := "openai.quota.reset", "openai.quota.read", "/1/reset"
if kind == "invite" {
action, readAction, path = "openai.referrals.invite", "openai.referrals.read", "/1/invite"
}
r := gin.New()
r.Use(func(c *gin.Context) {
statisticsContext(c, action)
if read {
p := adminaccess.FromContext(c.Request.Context())
p.Policy.Rules[0].Permissions = append(p.Policy.Rules[0].Permissions, readAction)
}
})
r.POST("/:id/reset", h.ResetQuota)
r.POST("/:id/invite", h.SendReferralInvite)
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("POST", path, strings.NewReader(`{"email":"friend@example.com","program_id":"codex_referral_consumer","confirmed":true}`)))
require.Equal(t, 200, w.Code, w.Body.String())
require.NotContains(t, w.Body.String(), "IDENTITY_SECRET")
if kind == "reset" {
require.Equal(t, 1, quota.resetCalls)
if read {
require.Contains(t, w.Body.String(), "available_count")
} else {
require.NotContains(t, w.Body.String(), "available_count")
}
} else {
require.Equal(t, 1, referral.sends)
if read {
require.Contains(t, w.Body.String(), "available_invites")
} else {
require.NotContains(t, w.Body.String(), "available_invites")
}
}
})
}
}
}
func TestScopedAdminUsageBillingPreservesQuotaWithoutCost(t *testing.T) {
limit, used, percent := 100.0, 123.0, 25.0
u := &service.UsageInfo{GrokBilling: &xai.BillingSummary{MonthlyLimit: &limit, MonthlyUsed: &used, UsedCents: &used, UsedPercent: &percent, Plan: "IDENTITY_SECRET"}}
a := &service.Account{ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}
out := scopedUsageDTO(u, statisticsPolicy("accounts.usage.read"), a)
billing, ok := out["grok_billing"].(*xai.BillingSummary)
require.True(t, ok, "须保留真实上游额度窗口")
require.Equal(t, &limit, billing.MonthlyLimit)
require.Equal(t, &percent, billing.UsedPercent)
require.Nil(t, billing.MonthlyUsed)
require.Nil(t, billing.UsedCents)
require.Empty(t, billing.Plan)
require.NotNil(t, u.GrokBilling.MonthlyUsed, "不能裁剪共享缓存")
}
func TestScopedAdminBatchAuthorizationPrecedesETag(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := &scopedStatisticsAccounts{accounts: map[int64]*service.Account{1: {ID: 1, Platform: "openai", Type: "oauth", GroupIDs: []int64{1}}, 2: {ID: 2, Platform: "openai", Type: "oauth", GroupIDs: []int64{2}}}}
h := &AccountHandler{adminService: svc}
cached := accountTodayStatsBatchCache.Set(buildAccountTodayStatsBatchCacheKey([]int64{1, 2}), gin.H{"stats": "CACHE_SECRET"})
r := gin.New()
r.Use(func(c *gin.Context) { statisticsContext(c, "accounts.stats.read") })
r.Use(h.ScopedAdminKeyAccounts)
r.POST("/api/v1/admin/accounts/today-stats/batch", h.GetBatchTodayStats)
request := httptest.NewRequest("POST", "/api/v1/admin/accounts/today-stats/batch", strings.NewReader(`{"account_ids":[1,2]}`))
request.Header.Set("If-None-Match", cached.ETag)
w := httptest.NewRecorder()
r.ServeHTTP(w, request)
require.Equal(t, 404, w.Code, w.Body.String())
require.Empty(t, w.Header().Get("ETag"))
require.NotContains(t, w.Body.String(), "CACHE_SECRET")
}
@@ -12,7 +12,7 @@ import (
// adminUserResponse 对受限密钥使用字段白名单,避免完整管理员 DTO 新增字段时隐式扩大授权。
// 订阅及用量由各自的独立接口提供,用户资料接口不嵌入这些关联数据。
func adminUserResponse(c *gin.Context, user *service.User) any {
principal := adminaccess.FromContext(c.Request.Context())
principal := adminaccess.RestrictedFromContext(c.Request.Context())
if principal == nil {
return dto.UserFromServiceAdmin(user)
}
@@ -43,6 +43,9 @@ func TestScopedAdminUserResponsePreservesFullAdminResponses(t *testing.T) {
svc := &scopedUserResponseService{}
h := NewUserHandler(svc, nil, nil, nil, nil, nil, nil)
r := gin.New()
r.Use(func(c *gin.Context) {
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{KeyID: "full", Policy: adminaccess.Policy{FullAccess: true}}))
})
r.GET("/users", h.List)
r.GET("/users/:id", h.GetByID)
for _, path := range []string{"/users", "/users?include_subscriptions=true", "/users/7"} {
@@ -62,7 +65,7 @@ func TestScopedAdminUserResponsePreservesFullAdminResponses(t *testing.T) {
}
}
func TestScopedAdminUserBalanceResponseRedactsCachedFullAdminResult(t *testing.T) {
func TestScopedAdminUserBalanceReplayRejectsDifferentCredential(t *testing.T) {
gin.SetMode(gin.TestMode)
previous := service.DefaultIdempotencyCoordinator()
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) })
@@ -91,6 +94,12 @@ func TestScopedAdminUserBalanceResponseRedactsCachedFullAdminResult(t *testing.T
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if scoped != scopedFirst {
require.Equal(t, 409, w.Code, w.Body.String())
require.NotContains(t, w.Body.String(), "内部备注")
require.NotContains(t, w.Body.String(), "内部密钥")
continue
}
require.Equal(t, 200, w.Code, w.Body.String())
if i > 0 {
require.Equal(t, "true", w.Header().Get("X-Idempotency-Replayed"))
@@ -50,6 +50,7 @@ func (h *SettingHandler) CreateScopedAdminKey(c *gin.Context) {
response.ErrorFrom(c, e)
return
}
middleware.SetAuditExtra(c, map[string]any{"admin_key_id": item.ID, "full_access": item.Policy.FullAccess})
response.Success(c, gin.H{"key": key, "item": item})
}
func (h *SettingHandler) UpdateScopedAdminKey(c *gin.Context) {
@@ -66,6 +67,7 @@ func (h *SettingHandler) UpdateScopedAdminKey(c *gin.Context) {
response.ErrorFrom(c, e)
return
}
middleware.SetAuditExtra(c, map[string]any{"admin_key_id": item.ID, "full_access_before": item.PreviousFullAccess, "full_access": item.Policy.FullAccess})
response.Success(c, item)
}
func (h *SettingHandler) RotateScopedAdminKey(c *gin.Context) {
@@ -77,6 +79,7 @@ func (h *SettingHandler) RotateScopedAdminKey(c *gin.Context) {
response.ErrorFrom(c, e)
return
}
middleware.SetAuditExtra(c, map[string]any{"admin_key_id": item.ID, "full_access": item.Policy.FullAccess})
response.Success(c, gin.H{"key": key, "item": item})
}
func (h *SettingHandler) RevokeScopedAdminKey(c *gin.Context) {
@@ -2,6 +2,10 @@ package admin
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"strconv"
"time"
@@ -68,6 +72,11 @@ func executeAdminIdempotentWithTimeout(
}
func adminActorScope(c *gin.Context) string {
if principal := adminaccess.FromContext(c.Request.Context()); principal != nil {
policy, _ := json.Marshal(principal.Policy)
digest := sha256.Sum256(policy)
return "admin-key:" + principal.KeyID + ":" + hex.EncodeToString(digest[:])
}
actorScope := "admin:0"
if subject, ok := middleware2.GetAuthSubjectFromContext(c); ok {
actorScope = "admin:" + strconv.FormatInt(subject.UserID, 10)
@@ -9,6 +9,7 @@ import (
"time"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/openai"
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
"github.com/Wei-Shaw/sub2api/internal/service"
@@ -194,6 +195,11 @@ type OpenAICodexPATCreateRequest struct {
// RefreshToken refreshes an OpenAI OAuth token
// POST /api/v1/admin/openai/refresh-token
func (h *OpenAIOAuthHandler) RefreshToken(c *gin.Context) {
scoped := adminaccess.RestrictedFromContext(c.Request.Context()) != nil
if scoped && !adminaccess.RouteAllowed(adminaccess.RestrictedFromContext(c.Request.Context()).Policy, c.Request.Method, c.FullPath()) {
response.Error(c, 403, "调用方令牌刷新未授权")
return
}
var req OpenAIRefreshTokenRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.BadRequest(c, "Invalid request: "+err.Error())
@@ -211,6 +217,10 @@ func (h *OpenAIOAuthHandler) RefreshToken(c *gin.Context) {
var proxyURL string
if req.ProxyID != nil {
proxy, err := h.adminService.GetProxy(c.Request.Context(), *req.ProxyID)
if scoped && (err != nil || proxy == nil || !proxy.IsActive() || proxy.IsExpired(time.Now())) {
response.BadRequest(c, "代理不可用")
return
}
if err == nil && proxy != nil {
proxyURL = proxy.URL()
}
@@ -225,6 +235,10 @@ func (h *OpenAIOAuthHandler) RefreshToken(c *gin.Context) {
tokenInfo, err := h.openaiOAuthService.RefreshTokenWithClientID(c.Request.Context(), refreshToken, proxyURL, clientID)
if err != nil {
if scoped {
response.Error(c, 502, "调用方令牌刷新失败")
return
}
response.ErrorFrom(c, err)
return
}
@@ -477,6 +491,10 @@ func buildOpenAICodexPATAccountName(name string, tokenInfo *service.OpenAITokenI
// QueryQuota queries the rate-limit / quota usage for an OpenAI account.
// GET /api/v1/admin/openai/accounts/:id/quota
func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) {
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
h.scopedOpenAIQuota(c, false)
return
}
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
@@ -504,6 +522,10 @@ func (h *OpenAIOAuthHandler) QueryQuota(c *gin.Context) {
// state: the audit middleware only records mutating verbs, so a persisting GET
// would mutate the database without an audit trail.
func (h *OpenAIOAuthHandler) RefreshQuota(c *gin.Context) {
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
h.scopedOpenAIQuota(c, true)
return
}
accountID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.BadRequest(c, "Invalid account ID")
@@ -588,13 +610,19 @@ func (h *OpenAIOAuthHandler) ResetQuota(c *gin.Context) {
response.BadRequest(c, "Invalid account ID")
return
}
if !h.scopedOpenAIAllowed(c, accountID, "openai.quota.reset", false) {
return
}
if h.quotaService == nil {
response.BadRequest(c, "openai quota service is not enabled")
return
}
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
c.Request = c.Request.WithContext(service.WithScopedAdminAccountOperation(c.Request.Context(), "openai.quota.reset"))
}
result, err := h.quotaService.ResetCredit(c.Request.Context(), accountID)
if err != nil {
response.ErrorFrom(c, err)
scopedOpenAIError(c, err)
return
}
if result == nil {
@@ -620,5 +648,13 @@ func (h *OpenAIOAuthHandler) ResetQuota(c *gin.Context) {
if postResult.Account != nil {
resetResponse.Account = dto.AccountFromService(postResult.Account)
}
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
if h.scopedOpenAIHasPermission(c, accountID, "openai.quota.read", true) {
resetResponse.Quota = h.scopedQuotaDTO(c, accountID, resetResponse.Quota)
} else {
resetResponse.Quota = nil
}
resetResponse.Account = nil
}
response.Success(c, resetResponse)
}
@@ -47,15 +47,19 @@ func (h *OpenAIOAuthHandler) RefreshReferrals(c *gin.Context) {
if !ok {
return
}
if !h.scopedOpenAIAllowed(c, id, "openai.referrals.read", true) {
return
}
eligibility, err := h.referralService.QueryReferralEligibility(c.Request.Context(), id)
if err != nil {
response.ErrorFrom(c, err)
scopedOpenAIError(c, err)
return
}
if eligibility == nil {
response.Error(c, http.StatusBadGateway, "Empty invitation eligibility response")
return
}
eligibility = h.scopedReferralDTO(c, eligibility)
cacheErr := h.referralService.CacheReferralSnapshot(c.Request.Context(), id, eligibility)
response.Success(c, openAIReferralRefreshResponse{Eligibility: eligibility, CachePersisted: cacheErr == nil})
}
@@ -65,6 +69,9 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) {
if !ok {
return
}
if !h.scopedOpenAIAllowed(c, id, "openai.referrals.invite", false) {
return
}
var input service.OpenAIReferralSendRequest
if err := c.ShouldBindJSON(&input); err != nil {
response.BadRequest(c, "Invalid invitation request")
@@ -72,7 +79,7 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) {
}
result, err := h.referralService.SendReferralInvite(c.Request.Context(), id, input)
if err != nil {
response.ErrorFrom(c, err)
scopedOpenAIError(c, err)
return
}
if result == nil || !result.Sent {
@@ -81,7 +88,7 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) {
}
// The email is already sent. Refresh failure must not turn it into a failed
// submission and encourage a duplicate send, even if the browser disconnects.
baseCtx := context.WithoutCancel(c.Request.Context())
baseCtx := service.WithScopedAdminAccountOperation(context.WithoutCancel(c.Request.Context()), "openai.referrals.invite")
refreshCtx, cancelRefresh := context.WithTimeout(baseCtx, 8*time.Second)
eligibility, refreshErr := h.referralService.QueryReferralEligibility(refreshCtx, id)
cancelRefresh()
@@ -92,10 +99,15 @@ func (h *OpenAIOAuthHandler) SendReferralInvite(c *gin.Context) {
// invalidating a stale snapshot) a fresh, independent deadline.
cacheCtx, cancelCache := context.WithTimeout(baseCtx, 3*time.Second)
defer cancelCache()
eligibility = h.scopedReferralDTO(c, eligibility)
cacheErr := h.referralService.CacheReferralSnapshot(cacheCtx, id, eligibility)
responseEligibility := eligibility
if !h.scopedOpenAIHasPermission(c, id, "openai.referrals.read", true) {
responseEligibility = nil
}
response.Success(c, openAIReferralSendResponse{
OpenAIReferralSendResult: *result,
openAIReferralRefreshResponse: openAIReferralRefreshResponse{Eligibility: eligibility, CachePersisted: cacheErr == nil},
openAIReferralRefreshResponse: openAIReferralRefreshResponse{Eligibility: responseEligibility, CachePersisted: cacheErr == nil},
RefreshFailed: eligibility == nil,
})
}
@@ -19,7 +19,7 @@ type scopedPromoUsageResponse struct {
}
func adminPromoUsagesResponse(c *gin.Context, items []dto.PromoCodeUsage) any {
if adminaccess.FromContext(c.Request.Context()) == nil {
if adminaccess.RestrictedFromContext(c.Request.Context()) == nil {
return items
}
out := make([]scopedPromoUsageResponse, 0, len(items))
@@ -36,7 +36,7 @@ type scopedAnnouncementReadResponse struct {
}
func adminAnnouncementReadResponse(c *gin.Context, items []service.AnnouncementUserReadStatus) any {
if adminaccess.FromContext(c.Request.Context()) == nil {
if adminaccess.RestrictedFromContext(c.Request.Context()) == nil {
return items
}
out := make([]scopedAnnouncementReadResponse, 0, len(items))
@@ -9,14 +9,14 @@ import (
)
func scopedAdminWriteOnly(c *gin.Context, readPermission string) bool {
p := adminaccess.FromContext(c.Request.Context())
p := adminaccess.RestrictedFromContext(c.Request.Context())
return p != nil && !slices.Contains(p.Policy.GlobalPermissions, readPermission)
}
// adminSubscriptionResponse 在缓存重放后也应用字段白名单,不嵌入用户、分配人或分组配置。
// 写权限只确认订阅 ID;订阅用量等字段必须另有读取权限。
func adminSubscriptionResponse(c *gin.Context, data any) any {
if adminaccess.FromContext(c.Request.Context()) == nil {
if adminaccess.RestrictedFromContext(c.Request.Context()) == nil {
return data
}
raw, err := json.Marshal(data)
@@ -73,7 +73,7 @@ func (r *scopedSubscriptionRepo) ExtendExpiry(context.Context, int64, time.Time)
return nil
}
func TestScopedAdminSubscriptionExtendReplayRespectsReadPermission(t *testing.T) {
func TestScopedAdminSubscriptionExtendReplayRejectsChangedAuthorization(t *testing.T) {
gin.SetMode(gin.TestMode)
previous := service.DefaultIdempotencyCoordinator()
t.Cleanup(func() { service.SetDefaultIdempotencyCoordinator(previous) })
@@ -100,10 +100,12 @@ func TestScopedAdminSubscriptionExtendReplayRespectsReadPermission(t *testing.T)
req.Header.Set("X-Test-Mode", mode)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, 200, w.Code, w.Body.String())
if i > 0 {
require.Equal(t, "true", w.Header().Get("X-Idempotency-Replayed"))
require.Equal(t, 409, w.Code, w.Body.String())
require.NotContains(t, w.Body.String(), "private-user")
continue
}
require.Equal(t, 200, w.Code, w.Body.String())
var result struct {
Data map[string]json.RawMessage `json:"data"`
}
@@ -82,7 +82,7 @@ func scopedAdminUsageLogResponse(record *service.UsageLog) gin.H {
}
func adminUsageLogResponses(c *gin.Context, records []service.UsageLog) any {
if adminaccess.FromContext(c.Request.Context()) != nil {
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
out := make([]gin.H, 0, len(records))
for i := range records {
out = append(out, scopedAdminUsageLogResponse(&records[i]))
@@ -151,7 +151,7 @@ func (h *UserHandler) List(c *gin.Context) {
includeSubscriptions := parseBoolQueryWithDefault(raw, true)
filters.IncludeSubscriptions = &includeSubscriptions
}
principal := adminaccess.FromContext(c.Request.Context())
principal := adminaccess.RestrictedFromContext(c.Request.Context())
if principal != nil {
includeSubscriptions := false
filters.IncludeSubscriptions = &includeSubscriptions
@@ -430,7 +430,7 @@ func (h *UserHandler) UpdateBalance(c *gin.Context) {
return dto.UserFromServiceAdmin(user), nil
}, func(data any) any {
// 成功确认不隐式授予用户资料或余额读取权限;缓存重放也必须经过此边界。
if adminaccess.FromContext(c.Request.Context()) != nil {
if adminaccess.RestrictedFromContext(c.Request.Context()) != nil {
return gin.H{"id": userID}
}
return data
+19 -1
View File
@@ -1,6 +1,9 @@
package adminaccess
import "slices"
import (
"slices"
"strings"
)
type Permission struct {
ID string `json:"id"`
@@ -17,6 +20,18 @@ type permissionDefinition struct {
// 接口按方法和 Gin 完整路径精确登记;新增接口不会继承同目录权限。
// 全站权限与账户规则独立,选中分组绝不会隐式授予全站操作。
var definitions = []permissionDefinition{
{Permission{"accounts.identity.read", "读取账户邮箱、套餐及创建时间(不含令牌)", "账户", "account"}, []string{"GET /accounts/:id"}},
{Permission{"accounts.usage.read", "读取及主动刷新授权账户额度与快照", "账户", "account"}, []string{"GET /accounts/:id/usage", "POST /accounts/usage/batch"}},
{Permission{"accounts.stats.read", "读取账户用量与费用统计", "账户", "account"}, []string{"GET /accounts/:id/today-stats", "POST /accounts/today-stats/batch", "GET /accounts/:id/stats"}},
{Permission{"openai.quota.read", "查询 OpenAI 上游额度与重置次数", "OpenAI", "account"}, []string{"GET /openai/accounts/:id/quota", "POST /openai/accounts/:id/quota/refresh"}},
{Permission{"openai.quota.reset", "消耗 OpenAI 重置次数恢复额度", "OpenAI", "account"}, []string{"POST /openai/accounts/:id/reset-quota"}},
{Permission{"openai.referrals.read", "查询 OpenAI 邀请资格与次数", "OpenAI", "account"}, []string{"POST /openai/accounts/:id/referrals/refresh"}},
{Permission{"openai.referrals.invite", "发送 OpenAI 邀请邮件", "OpenAI", "account"}, []string{"POST /openai/accounts/:id/referrals/invite"}},
{Permission{"accounts.options.write", "写入 OpenAI OAuth 身份与连接选项", "账户", "account"}, []string{"POST /accounts"}},
{Permission{"accounts.rate.write", "设置账户计费倍率", "账户", "account"}, []string{"POST /accounts", "PUT /accounts/:id"}},
{Permission{"groups.list.read", "读取所选分组基本信息(名称、平台、状态)", "分组", "group"}, []string{"GET /groups", "GET /groups/all", "GET /groups/:id"}},
{Permission{"groups.capacity.read", "读取所选分组容量(整个分组,不按账户类型过滤)", "分组", "group"}, []string{"GET /groups/capacity-summary"}},
{Permission{"openai.tokens.refresh", "刷新调用方提供的 OpenAI 令牌(返回令牌,可使用所选代理)", "OAuth", "global"}, []string{"POST /openai/refresh-token"}},
{Permission{"accounts.read", "查看账户(脱敏)", "账户", "account"}, []string{"GET /accounts", "GET /accounts/:id", "GET /accounts/:id/models"}},
{Permission{"accounts.create", "创建账户", "账户", "account"}, []string{"POST /accounts", "POST /accounts/import/codex-session"}},
{Permission{"accounts.update", "编辑名称与备注", "账户", "account"}, []string{"PUT /accounts/:id"}},
@@ -77,6 +92,9 @@ func PermissionCatalog() []Permission {
// RouteAllowed 只检查动作准入;账户资源及字段必须再由专用处理器检查。
func RouteAllowed(policy Policy, method, path string) bool {
if policy.FullAccess {
return strings.HasPrefix(path, "/api/v1/admin/") && !strings.HasPrefix(path, "/api/v1/admin/settings/admin-api-key")
}
target := method + " " + path
for _, definition := range definitions {
matched := false
@@ -0,0 +1,20 @@
package adminaccess
import "testing"
func TestScopedPermissionCatalogRequiresExplicitGrant(t *testing.T) {
for _, id := range []string{"accounts.identity.read", "accounts.usage.read", "accounts.options.write", "accounts.rate.write", "groups.list.read", "groups.capacity.read", "openai.tokens.refresh"} {
found := false
for _, entry := range PermissionCatalog() {
if entry.ID == id {
found = true
}
}
if !found {
t.Errorf("权限未登记: %s", id)
}
}
if RouteAllowed(Policy{}, "POST", "/api/v1/admin/openai/refresh-token") {
t.Fatal("旧策略不得继承新增权限")
}
}
@@ -0,0 +1,31 @@
package adminaccess
import "testing"
func TestStatisticsAndOpenAIPermissions(t *testing.T) {
for action, routes := range map[string][]string{
"accounts.stats.read": {"GET /accounts/:id/today-stats", "POST /accounts/today-stats/batch", "GET /accounts/:id/stats"},
"accounts.usage.read": {"POST /accounts/usage/batch"},
"openai.quota.read": {"GET /openai/accounts/:id/quota", "POST /openai/accounts/:id/quota/refresh"},
"openai.quota.reset": {"POST /openai/accounts/:id/reset-quota"},
"openai.referrals.read": {"POST /openai/accounts/:id/referrals/refresh"},
"openai.referrals.invite": {"POST /openai/accounts/:id/referrals/invite"},
} {
p := Policy{Rules: []Rule{{Permissions: []string{action}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}}}}
if err := ValidatePolicy(p); err != nil {
t.Errorf("%s: %v", action, err)
}
for _, route := range routes {
var method, path string
for i, c := range route {
if c == ' ' {
method, path = route[:i], route[i+1:]
break
}
}
if !RouteAllowed(p, method, "/api/v1/admin"+path) {
t.Errorf("%s 无法进入 %s", action, route)
}
}
}
}
@@ -0,0 +1,32 @@
//go:build unit
package adminaccess
import (
"encoding/json"
"testing"
)
func TestAdminFullAccessRouteBoundary(t *testing.T) {
var policy Policy
if err := json.Unmarshal([]byte(`{"full_access":true}`), &policy); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
path string
allowed bool
}{
{"/api/v1/admin/future-operation", true},
{"/api/v1/admin/accounts/:id", true},
{"/api/v1/admin/settings/admin-api-keys", false},
{"/api/v1/admin/settings/admin-api-keys/:id/rotate", false},
{"/api/v1/admin/settings/admin-api-key/regenerate", false},
{"/api/v1/user/profile", false},
{"/v1/messages", false},
{"", false},
} {
if got := RouteAllowed(policy, "POST", tc.path); got != tc.allowed {
t.Errorf("%s: got %v want %v", tc.path, got, tc.allowed)
}
}
}
@@ -18,6 +18,7 @@ type Rule struct {
}
type Policy struct {
FullAccess bool `json:"full_access,omitempty"`
Rules []Rule `json:"rules"`
GlobalPermissions []string `json:"global_permissions"`
}
@@ -47,6 +48,16 @@ func FromContext(ctx context.Context) *Principal {
return principal
}
// RestrictedFromContext 只返回需要资源限制和响应裁剪的密钥。
// 全权密钥仍保留原 Principal,供审计、限流和幂等隔离使用。
func RestrictedFromContext(ctx context.Context) *Principal {
principal := FromContext(ctx)
if principal != nil && !principal.Policy.FullAccess {
return principal
}
return nil
}
// Matches 保持分组、类型和平台在同一规则中匹配,不拆开合并授权条件。
func (r Rule) Matches(a Account) bool {
if !slices.Contains(r.AccountTypes, a.Type) || (len(r.Platforms) > 0 && !slices.Contains(r.Platforms, a.Platform)) {
+1 -1
View File
@@ -1969,7 +1969,7 @@ func (r *accountRepository) BindGroups(ctx context.Context, accountID int64, gro
if scoped := r.accountTransactionScope(ctx); scoped != r {
return scoped.BindGroups(ctx, accountID, groupIDs)
}
if adminaccess.FromContext(ctx) != nil {
if adminaccess.RestrictedFromContext(ctx) != nil {
return r.scopedAdminBindGroups(ctx, accountID, groupIDs)
}
existingGroupIDs, err := r.loadAccountGroupIDs(ctx, accountID)
@@ -0,0 +1,37 @@
package repository
import (
"context"
"github.com/Wei-Shaw/sub2api/ent/group"
"github.com/Wei-Shaw/sub2api/ent/predicate"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/Wei-Shaw/sub2api/internal/service"
)
// ListScopedAdminCapacityGroupIDs 先在数据库内限定分组,再查询账户与实时容量。
func (r *groupRepository) ListScopedAdminCapacityGroupIDs(ctx context.Context) ([]int64, error) {
p := adminaccess.FromContext(ctx)
if p == nil {
return nil, infraerrors.Forbidden("SCOPED_GROUP_CAPACITY_FORBIDDEN", "缺少受限身份")
}
alternatives := []predicate.Group{}
for _, rule := range p.Policy.RulesFor("groups.capacity.read") {
terms := []predicate.Group{group.IDGT(0)}
if !rule.AllGroups {
if len(rule.GroupIDs) == 0 {
continue
}
terms = append(terms, group.IDIn(rule.GroupIDs...))
}
if len(rule.Platforms) > 0 {
terms = append(terms, group.PlatformIn(rule.Platforms...))
}
alternatives = append(alternatives, group.And(terms...))
}
if len(alternatives) == 0 {
return []int64{}, nil
}
return r.client.Group.Query().Where(group.DeletedAtIsNil(), group.StatusEQ(service.StatusActive), group.Or(alternatives...)).Order(group.ByID()).IDs(ctx)
}
@@ -25,7 +25,7 @@ func (r *groupRepository) ScopedAdminUpdateGroupModels(ctx context.Context, id i
defer func() { _ = tx.Rollback() }()
txctx := dbent.NewTxContext(ctx, tx)
row, err := tx.Client().Group.Query().Where(group.IDEQ(id), group.DeletedAtIsNil()).
Select(group.FieldID, group.FieldName, group.FieldPlatform, group.FieldModelAllowlist).ForUpdate().Only(txctx)
Select(group.FieldID, group.FieldName, group.FieldPlatform, group.FieldStatus, group.FieldModelAllowlist).ForUpdate().Only(txctx)
if err != nil {
return nil, translatePersistenceError(err, service.ErrGroupNotFound, nil)
}
@@ -42,7 +42,7 @@ func (r *groupRepository) ScopedAdminUpdateGroupModels(ctx context.Context, id i
if err = tx.Commit(); err != nil {
return nil, err
}
return &service.Group{ID: row.ID, Name: row.Name, Platform: row.Platform, ModelAllowlist: cfg}, nil
return &service.Group{ID: row.ID, Name: row.Name, Platform: row.Platform, Status: row.Status, ModelAllowlist: cfg}, nil
}
// ScopedAdminListGroupModels 在数据库内过滤范围,分页和总数均只包含已授权分组。
@@ -52,7 +52,8 @@ func (r *groupRepository) ScopedAdminListGroupModels(ctx context.Context, params
return nil, 0, infraerrors.Forbidden("SCOPED_GROUP_MODELS_FORBIDDEN", "缺少受限身份")
}
alternatives := []predicate.Group{}
for _, rule := range p.Policy.RulesFor("groups.models.read") {
rules := append(p.Policy.RulesFor("groups.models.read"), p.Policy.RulesFor("groups.list.read")...)
for _, rule := range rules {
terms := []predicate.Group{group.IDGT(0)}
if !rule.AllGroups {
if len(rule.GroupIDs) == 0 {
@@ -82,7 +83,7 @@ func (r *groupRepository) ScopedAdminListGroupModels(ctx context.Context, params
if err != nil {
return nil, 0, err
}
q.Select(group.FieldID, group.FieldName, group.FieldPlatform, group.FieldModelAllowlist).Order(group.ByID())
q.Select(group.FieldID, group.FieldName, group.FieldPlatform, group.FieldStatus).Order(group.ByID())
if !all {
q.Offset(params.Offset()).Limit(params.Limit())
}
@@ -91,8 +92,24 @@ func (r *groupRepository) ScopedAdminListGroupModels(ctx context.Context, params
return nil, 0, err
}
result := make([]service.Group, 0, len(rows))
modelIDs := make([]int64, 0, len(rows))
modelIndexes := make(map[int64]int)
for _, row := range rows {
result = append(result, service.Group{ID: row.ID, Name: row.Name, Platform: row.Platform, ModelAllowlist: service.GroupModelAllowlistFromDomain(row.ModelAllowlist)})
result = append(result, service.Group{ID: row.ID, Name: row.Name, Platform: row.Platform, Status: row.Status})
if p.Policy.AllowsGroupConfig("groups.models.read", row.ID, row.Platform) {
modelIDs = append(modelIDs, row.ID)
modelIndexes[row.ID] = len(result) - 1
}
}
// 仅为独立模型读取权限允许的行加载配置,基本列表不读取模型或费率。
if len(modelIDs) > 0 {
models, err := r.client.Group.Query().Where(group.IDIn(modelIDs...), group.DeletedAtIsNil()).Select(group.FieldID, group.FieldModelAllowlist).All(ctx)
if err != nil {
return nil, 0, err
}
for _, model := range models {
result[modelIndexes[model.ID]].ModelAllowlist = service.GroupModelAllowlistFromDomain(model.ModelAllowlist)
}
}
return result, int64(total), nil
}
@@ -0,0 +1,230 @@
//go:build unit
package repository
import (
"context"
"database/sql"
"fmt"
"github.com/Wei-Shaw/sub2api/internal/service"
"os"
"strings"
"testing"
"time"
"entgo.io/ent/dialect"
entsql "entgo.io/ent/dialect/sql"
dbent "github.com/Wei-Shaw/sub2api/ent"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/stretchr/testify/require"
)
func scopedPermissionsTestDB(t *testing.T, options ...dbent.Option) (*dbent.Client, *sql.DB) {
t.Helper()
dsn := os.Getenv("SCOPED_ADMIN_TEST_DSN")
if dsn == "" {
t.Skip("需要独立 SCOPED_ADMIN_TEST_DSN")
}
base, err := sql.Open("postgres", dsn)
require.NoError(t, err)
schema := fmt.Sprintf("permissions_test_%d", time.Now().UnixNano())
_, err = base.Exec(`CREATE SCHEMA ` + schema)
require.NoError(t, err)
db, err := sql.Open("postgres", dsn+" search_path="+schema)
require.NoError(t, err)
client := dbent.NewClient(append([]dbent.Option{dbent.Driver(entsql.OpenDB(dialect.Postgres, db))}, options...)...)
t.Cleanup(func() { _ = client.Close(); _, _ = base.Exec(`DROP SCHEMA ` + schema + ` CASCADE`); _ = base.Close() })
_, err = db.Exec(`CREATE TABLE groups(id BIGINT PRIMARY KEY, name TEXT DEFAULT '分组', platform TEXT DEFAULT 'openai', status TEXT DEFAULT 'active', model_allowlist JSONB DEFAULT '{}', deleted_at TIMESTAMPTZ);
CREATE TABLE accounts(id BIGINT PRIMARY KEY, name TEXT DEFAULT '账户', notes TEXT, platform TEXT DEFAULT 'openai', type TEXT DEFAULT 'oauth', status TEXT DEFAULT 'active', schedulable BOOLEAN DEFAULT true, concurrency INT DEFAULT 1, priority INT DEFAULT 1, credentials JSONB DEFAULT '{}', extra JSONB DEFAULT '{}', expires_at TIMESTAMPTZ, rate_limit_reset_at TIMESTAMPTZ, overload_until TIMESTAMPTZ, temp_unschedulable_until TIMESTAMPTZ, created_at TIMESTAMPTZ DEFAULT NOW(), deleted_at TIMESTAMPTZ);
CREATE TABLE account_groups(account_id BIGINT, group_id BIGINT, priority INT DEFAULT 50, created_at TIMESTAMPTZ DEFAULT NOW());
INSERT INTO groups(id,platform,status) VALUES (1,'openai','active'),(2,'openai','active'),(3,'anthropic','active'),(4,'openai','inactive');
INSERT INTO accounts(id,credentials,extra) VALUES (1,'{"email":"test@example.com","access_token":"SECRET"}','{}'),(2,'{}','{"email":"test@example.com"}'),(3,'{"email":"test@example.com"}','{}');
INSERT INTO account_groups(account_id,group_id) VALUES (1,1),(1,9),(2,2),(3,3);`)
require.NoError(t, err)
return client, db
}
func TestScopedAdminPermissionsPostgresFilters(t *testing.T) {
client, db := scopedPermissionsTestDB(t)
policy := adminaccess.Policy{Rules: []adminaccess.Rule{
{Permissions: []string{"accounts.read", "groups.list.read", "groups.capacity.read"}, GroupIDs: []int64{1, 2, 3, 4}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}},
{Permissions: []string{"accounts.identity.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}},
{Permissions: []string{"groups.capacity.read"}, GroupIDs: []int64{2}, Platforms: []string{"anthropic"}},
}}
ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: policy})
groups := newGroupRepositoryWithSQL(client, db)
ids, err := groups.ListScopedAdminCapacityGroupIDs(ctx)
require.NoError(t, err)
require.Equal(t, []int64{1, 2}, ids, "平台和分组不能跨规则拼接,停用组不能参与容量统计")
rows, total, err := groups.ScopedAdminListGroupModels(ctx, pagination.PaginationParams{Page: 1, PageSize: 1}, false, "openai", "active", "")
require.NoError(t, err)
require.EqualValues(t, 2, total)
require.Len(t, rows, 1)
require.Equal(t, "active", rows[0].Status)
accounts := newAccountRepositoryWithSQL(client, db, nil)
for _, tc := range []struct {
group int64
search string
ids []int64
}{
{2, "", []int64{2}}, {1, "TEST@example.com", []int64{1}}, {2, "test@example.com", []int64{}}, {0, "test@example.com", []int64{1}}, {9, "", []int64{}},
} {
rows, total, err := accounts.ScopedAdminList(ctx, pagination.PaginationParams{Page: 1, PageSize: 100}, "openai", "oauth", "", tc.search, tc.group)
require.NoError(t, err)
require.EqualValues(t, len(tc.ids), total)
ids := []int64{}
for _, row := range rows {
ids = append(ids, row.ID)
require.NotContains(t, row.Credentials, "access_token")
if row.ID == 1 {
require.Equal(t, "test@example.com", row.Credentials["email"])
require.False(t, row.CreatedAt.IsZero())
} else {
require.NotContains(t, row.Credentials, "email")
}
}
require.Equal(t, tc.ids, ids)
}
_, err = groups.ListScopedAdminCapacityGroupIDs(context.Background())
require.Error(t, err)
}
func TestScopedAdminPermissionsWeeklySnapshotPostgres(t *testing.T) {
client, db := scopedPermissionsTestDB(t)
_, err := db.Exec(`UPDATE accounts SET credentials = '{"email":"test@example.com","access_token":"SECRET"}', extra = '{"email":"test@example.com","codex_usage_updated_at":"2026-10-25T00:00:00Z","codex_7d_used_percent":90,"codex_7d_reset_at":"2026-10-30T00:00:00Z","private":"SECRET"}'`)
require.NoError(t, err)
repo := newAccountRepositoryWithSQL(client, db, nil)
for _, tc := range []struct {
name string
usage adminaccess.Rule
identity bool
want bool
}{
{name: "无额度权限"},
{name: "仅身份权限", identity: true},
{name: "仅额度权限", usage: adminaccess.Rule{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, want: true},
{name: "身份和额度权限", identity: true, usage: adminaccess.Rule{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}, want: true},
{name: "额度分组不匹配", usage: adminaccess.Rule{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{99}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}},
{name: "额度类型不匹配", usage: adminaccess.Rule{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"apikey"}, Platforms: []string{"openai"}}},
{name: "额度平台不匹配", usage: adminaccess.Rule{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"anthropic"}}},
} {
t.Run(tc.name, func(t *testing.T) {
read := adminaccess.Rule{Permissions: []string{"accounts.read"}, GroupIDs: []int64{1, 2}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}
if tc.identity {
read.Permissions = append(read.Permissions, "accounts.identity.read")
}
policy := adminaccess.Policy{Rules: []adminaccess.Rule{read}}
if len(tc.usage.Permissions) > 0 {
policy.Rules = append(policy.Rules, tc.usage)
}
ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: policy})
rows, total, err := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: 1, PageSize: 100}, "openai", "oauth", "", "", 0)
require.NoError(t, err)
require.EqualValues(t, 2, total)
require.Len(t, rows, 2)
for _, row := range rows {
want := map[string]any{}
if tc.identity {
want["email"] = "test@example.com"
require.Equal(t, "test@example.com", row.Credentials["email"])
}
if tc.want && row.ID == 1 {
want["codex_usage_updated_at"] = "2026-10-25T00:00:00Z"
want["codex_7d_used_percent"] = float64(90)
want["codex_7d_reset_at"] = "2026-10-30T00:00:00Z"
}
if len(want) == 0 {
require.Empty(t, row.Extra)
} else {
require.Equal(t, want, row.Extra, "列表必须保留已授权的周额度快照,必须按行应用额度权限")
}
require.NotContains(t, row.Credentials, "access_token")
}
})
}
}
func TestScopedAdminPermissionBasicGroupRepositoryRedactsModels(t *testing.T) {
client, db := scopedPermissionsTestDB(t)
_, err := db.Exec(`UPDATE groups SET model_allowlist='{"enabled":true,"models":["private-model"]}'`)
require.NoError(t, err)
repo := newGroupRepositoryWithSQL(client, db)
p := &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{
{Permissions: []string{"groups.list.read"}, GroupIDs: []int64{1, 2}, Platforms: []string{"openai"}},
{Permissions: []string{"groups.models.read"}, GroupIDs: []int64{2}, Platforms: []string{"openai"}},
}}}
rows, total, err := repo.ScopedAdminListGroupModels(adminaccess.WithPrincipal(context.Background(), p), pagination.DefaultPagination(), false, "", "", "")
require.NoError(t, err)
require.EqualValues(t, 2, total)
require.Len(t, rows, 2)
require.Empty(t, rows[0].ModelAllowlist.Models, "基本分组权限不能加载模型配置")
require.Equal(t, []string{"private-model"}, rows[1].ModelAllowlist.Models)
}
func TestScopedAdminGroupModelsUpdatePreservesStatusPostgres(t *testing.T) {
client, db := scopedPermissionsTestDB(t)
_, err := db.Exec(`ALTER TABLE groups ADD COLUMN updated_at TIMESTAMPTZ;
CREATE TABLE scheduler_outbox(id BIGSERIAL PRIMARY KEY,event_type TEXT,account_id BIGINT,group_id BIGINT,payload JSONB,dedup_key TEXT);
CREATE UNIQUE INDEX outbox_dedup ON scheduler_outbox(dedup_key) WHERE dedup_key IS NOT NULL;`)
require.NoError(t, err)
repo := newGroupRepositoryWithSQL(client, db)
ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.models.write"}, GroupIDs: []int64{1}, Platforms: []string{"openai"}}}}})
cfg := service.GroupModelAllowlist{Enabled: true, Models: []string{"model"}}
for _, status := range []string{"active", "inactive"} {
t.Run(status, func(t *testing.T) {
_, err := db.Exec(`UPDATE groups SET status=$1 WHERE id=1`, status)
require.NoError(t, err)
updated, err := repo.ScopedAdminUpdateGroupModels(ctx, 1, cfg)
require.NoError(t, err)
require.Equal(t, status, updated.Status)
var stored string
require.NoError(t, db.QueryRow(`SELECT status FROM groups WHERE id=1`).Scan(&stored))
require.Equal(t, status, stored)
})
}
}
func TestScopedAdminIdentityProjectionBatchesAuthorizedPagePostgres(t *testing.T) {
identityQueries := []string{}
client, db := scopedPermissionsTestDB(t, dbent.Debug(), dbent.Log(func(args ...any) {
query := fmt.Sprint(args...)
if strings.Contains(query, "subscription_expires_at") {
identityQueries = append(identityQueries, query)
}
}))
_, err := db.Exec(`INSERT INTO accounts(id,credentials,extra) SELECT i,'{"email":"batch@example.com","access_token":"SECRET","model_mapping":{"alias":"target"}}'::jsonb,'{"email":"batch@example.com","codex_7d_used_percent":90,"private":"SECRET"}'::jsonb FROM generate_series(100,199) i;
INSERT INTO account_groups(account_id,group_id) SELECT i,CASE WHEN i%2=0 THEN 1 ELSE 2 END FROM generate_series(100,199) i;`)
require.NoError(t, err)
policy := adminaccess.Policy{Rules: []adminaccess.Rule{
{Permissions: []string{"accounts.read"}, GroupIDs: []int64{1, 2}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}},
{Permissions: []string{"accounts.identity.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}},
{Permissions: []string{"accounts.usage.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}},
}}
ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: policy})
repo := newAccountRepositoryWithSQL(client, db, nil)
rows, total, err := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: 1, PageSize: 100}, "openai", "oauth", "", "", 0)
require.NoError(t, err)
require.EqualValues(t, 102, total)
require.Len(t, rows, 100)
for _, row := range rows {
resource := adminaccess.Account{ID: row.ID, Type: row.Type, Platform: row.Platform, GroupIDs: row.GroupIDs}
if policy.AllowsAccount("accounts.identity.read", resource) {
require.Contains(t, row.Credentials, "email")
require.False(t, row.CreatedAt.IsZero())
} else {
require.NotContains(t, row.Credentials, "email")
require.NotContains(t, row.Extra, "email")
require.True(t, row.CreatedAt.IsZero())
}
if row.ID >= 100 {
require.Equal(t, map[string]string{"alias": "target"}, row.Credentials["model_mapping"])
require.Equal(t, policy.AllowsAccount("accounts.usage.read", resource), row.Extra["codex_7d_used_percent"] != nil)
}
require.NotContains(t, row.Credentials, "access_token")
require.NotContains(t, row.Extra, "private")
}
require.Equal(t, 1, len(identityQueries), "同一分页的身份信息必须单次批量读取")
require.Contains(t, identityQueries[0], `"accounts"."id" IN (`)
}
@@ -6,6 +6,7 @@ import (
"fmt"
"slices"
"strings"
"time"
entsql "entgo.io/ent/dialect/sql"
dbent "github.com/Wei-Shaw/sub2api/ent"
@@ -17,35 +18,62 @@ import (
"github.com/Wei-Shaw/sub2api/internal/service"
)
func (r *accountRepository) ScopedAdminList(ctx context.Context, p pagination.PaginationParams, platform, kind, status, search string) ([]service.Account, int64, error) {
func (r *accountRepository) ScopedAdminList(ctx context.Context, p pagination.PaginationParams, platform, kind, status, search string, groupID int64) ([]service.Account, int64, error) {
principal := adminaccess.FromContext(ctx)
if principal == nil {
return nil, 0, fmt.Errorf("缺少受限身份")
}
alternatives := scopedAdminAccountPredicates(principal.Policy, "accounts.read")
readPolicy := principal.Policy
if groupID > 0 {
readPolicy.Rules = nil
for _, rule := range principal.Policy.RulesFor("accounts.read") {
if rule.AllGroups || slices.Contains(rule.GroupIDs, groupID) {
readPolicy.Rules = append(readPolicy.Rules, rule)
}
}
}
alternatives := scopedAdminAccountPredicates(readPolicy, "accounts.read")
if len(alternatives) == 0 {
return []service.Account{}, 0, nil
}
q := r.accountListFilteredQuery(platform, kind, status, search, 0, "").Where(dbaccount.Or(alternatives...))
q := r.accountListFilteredQuery(platform, kind, status, "", groupID, "").Where(dbaccount.Or(alternatives...))
if search != "" {
matches := []dbpredicate.Account{dbaccount.NameContainsFold(search)}
identityScope := scopedAdminAccountPredicates(principal.Policy, "accounts.identity.read")
if len(identityScope) > 0 {
email := dbpredicate.Account(func(s *entsql.Selector) {
s.Where(entsql.P(func(b *entsql.Builder) {
b.WriteString("(lower(" + s.C(dbaccount.FieldCredentials) + "->>'email') = ").Arg(strings.ToLower(search))
b.WriteString(" OR lower(" + s.C(dbaccount.FieldExtra) + "->>'email') = ").Arg(strings.ToLower(search)).WriteString(")")
}))
})
matches = append(matches, dbaccount.And(dbaccount.Or(identityScope...), email))
}
q.Where(dbaccount.Or(matches...))
}
total, err := q.Clone().Count(ctx)
if err != nil {
return nil, 0, err
}
// SQL 只投影模型映射子字段,不加载 Token、API Key、接入地址或其他凭证。
var rows []struct {
ID int64
Name string
Notes *string
Platform string
Type string
Status string
Schedulable bool
Concurrency int
Priority int
ModelMapping json.RawMessage `json:"model_mapping"`
ID int64
Name string
Notes *string
Platform string
Type string
Status string
Schedulable bool
Concurrency int
Priority int
ExpiresAt *time.Time `json:"expires_at"`
RateLimitResetAt *time.Time `json:"rate_limit_reset_at"`
OverloadUntil *time.Time `json:"overload_until"`
TempUnschedulableUntil *time.Time `json:"temp_unschedulable_until"`
ModelMapping json.RawMessage `json:"model_mapping"`
}
err = q.Offset(p.Offset()).Limit(p.Limit()).Order(dbaccount.ByID()).
Select(dbaccount.FieldID, dbaccount.FieldName, dbaccount.FieldNotes, dbaccount.FieldPlatform, dbaccount.FieldType, dbaccount.FieldStatus, dbaccount.FieldSchedulable, dbaccount.FieldConcurrency, dbaccount.FieldPriority).
Select(dbaccount.FieldID, dbaccount.FieldName, dbaccount.FieldNotes, dbaccount.FieldPlatform, dbaccount.FieldType, dbaccount.FieldStatus, dbaccount.FieldSchedulable, dbaccount.FieldConcurrency, dbaccount.FieldPriority, dbaccount.FieldExpiresAt, dbaccount.FieldRateLimitResetAt, dbaccount.FieldOverloadUntil, dbaccount.FieldTempUnschedulableUntil).
Aggregate(func(s *entsql.Selector) string {
return s.C(dbaccount.FieldCredentials) + "->'model_mapping' AS model_mapping"
}).Scan(ctx, &rows)
@@ -71,7 +99,75 @@ func (r *accountRepository) ScopedAdminList(ctx context.Context, p pagination.Pa
if len(mapping) > 0 {
credentials = map[string]any{"model_mapping": mapping}
}
accounts = append(accounts, service.Account{ID: row.ID, Name: row.Name, Notes: row.Notes, Platform: row.Platform, Type: row.Type, Status: row.Status, Schedulable: row.Schedulable, Concurrency: row.Concurrency, Priority: row.Priority, GroupIDs: groups, Credentials: credentials})
a := service.Account{ID: row.ID, Name: row.Name, Notes: row.Notes, Platform: row.Platform, Type: row.Type, Status: row.Status, Schedulable: row.Schedulable, Concurrency: row.Concurrency, Priority: row.Priority, GroupIDs: groups, Credentials: credentials, ExpiresAt: row.ExpiresAt, RateLimitResetAt: row.RateLimitResetAt, OverloadUntil: row.OverloadUntil, TempUnschedulableUntil: row.TempUnschedulableUntil}
accounts = append(accounts, a)
}
// 身份字段只为本页逐行鉴权通过的账户批量投影,不加载完整凭证或 extra。
identityIDs := make([]int64, 0, len(accounts))
identityAccounts := make(map[int64]*service.Account)
for i := range accounts {
a := &accounts[i]
if principal.Policy.AllowsAccount("accounts.identity.read", adminaccess.Account{ID: a.ID, GroupIDs: a.GroupIDs, Type: a.Type, Platform: a.Platform}) {
identityIDs = append(identityIDs, a.ID)
identityAccounts[a.ID] = a
}
}
if len(identityIDs) > 0 {
var identities []struct {
ID int64 `json:"id"`
CreatedAt time.Time `json:"created_at"`
Credentials json.RawMessage `json:"credentials"`
Extra json.RawMessage `json:"extra"`
}
err := r.client.Account.Query().Where(dbaccount.IDIn(identityIDs...)).Select(dbaccount.FieldID, dbaccount.FieldCreatedAt).
Aggregate(func(s *entsql.Selector) string {
return "jsonb_build_object('email', " + s.C(dbaccount.FieldCredentials) + "->'email', 'plan_type', " + s.C(dbaccount.FieldCredentials) + "->'plan_type', 'subscription_expires_at', " + s.C(dbaccount.FieldCredentials) + "->'subscription_expires_at') AS credentials"
}, func(s *entsql.Selector) string {
return "jsonb_build_object('email', " + s.C(dbaccount.FieldExtra) + "->'email') AS extra"
}).Scan(ctx, &identities)
if err != nil {
return nil, 0, err
}
for _, identity := range identities {
a := identityAccounts[identity.ID]
if err := json.Unmarshal(identity.Credentials, &a.Credentials); err != nil {
return nil, 0, err
}
if err := json.Unmarshal(identity.Extra, &a.Extra); err != nil {
return nil, 0, err
}
a.CreatedAt = identity.CreatedAt
}
}
// 仅为本页已获额度权限的账户批量加载三个周额度快照字段。
usageIDs := make([]int64, 0, len(accounts))
usageAccounts := make(map[int64]*service.Account)
for i := range accounts {
a := &accounts[i]
if principal.Policy.AllowsAccount("accounts.usage.read", adminaccess.Account{ID: a.ID, GroupIDs: a.GroupIDs, Type: a.Type, Platform: a.Platform}) {
usageIDs = append(usageIDs, a.ID)
usageAccounts[a.ID] = a
}
}
if len(usageIDs) > 0 {
var snapshots []struct {
ID int64 `json:"id"`
Extra json.RawMessage `json:"extra"`
}
err := r.client.Account.Query().Where(dbaccount.IDIn(usageIDs...)).Select(dbaccount.FieldID).
Aggregate(func(s *entsql.Selector) string {
extra := s.C(dbaccount.FieldExtra)
return "jsonb_strip_nulls(jsonb_build_object('codex_usage_updated_at', " + extra + "->'codex_usage_updated_at', 'codex_7d_used_percent', " + extra + "->'codex_7d_used_percent', 'codex_7d_reset_at', " + extra + "->'codex_7d_reset_at')) AS extra"
}).Scan(ctx, &snapshots)
if err != nil {
return nil, 0, err
}
for _, snapshot := range snapshots {
// 合并到已有 extra,保留独立身份权限允许读取的邮箱。
if err := json.Unmarshal(snapshot.Extra, &usageAccounts[snapshot.ID].Extra); err != nil {
return nil, 0, err
}
}
}
return accounts, int64(total), nil
}
@@ -63,7 +63,7 @@ func TestScopedAdminAccountListScopesCountAndPageInSQL(t *testing.T) {
{Permissions: []string{"accounts.read"}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}},
{Permissions: []string{"accounts.read"}, GroupIDs: []int64{2}, AccountTypes: []string{"apikey"}},
}}}
_, total, err := repo.ScopedAdminList(adminaccess.WithPrincipal(context.Background(), principal), pagination.PaginationParams{Page: 1, PageSize: 20}, "", "", "", "")
_, total, err := repo.ScopedAdminList(adminaccess.WithPrincipal(context.Background(), principal), pagination.PaginationParams{Page: 1, PageSize: 20}, "", "", "", "", 0)
if err != nil {
t.Fatal(err)
}
@@ -97,7 +97,7 @@ func TestScopedAdminAccountListPostgresRulesAndPagination(t *testing.T) {
_, err = db.Exec(`CREATE TABLE accounts (
id BIGINT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', notes TEXT, platform TEXT NOT NULL,
type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'active', schedulable BOOLEAN NOT NULL DEFAULT true,
concurrency INT NOT NULL DEFAULT 1, priority INT NOT NULL DEFAULT 1, credentials JSONB DEFAULT '{}', deleted_at TIMESTAMPTZ
concurrency INT NOT NULL DEFAULT 1, priority INT NOT NULL DEFAULT 1, credentials JSONB DEFAULT '{}', expires_at TIMESTAMPTZ, rate_limit_reset_at TIMESTAMPTZ, overload_until TIMESTAMPTZ, temp_unschedulable_until TIMESTAMPTZ, deleted_at TIMESTAMPTZ
);
CREATE TABLE account_groups(account_id BIGINT, group_id BIGINT, priority INT DEFAULT 50, created_at TIMESTAMPTZ DEFAULT NOW());
INSERT INTO accounts(id,platform,type) VALUES
@@ -114,7 +114,7 @@ func TestScopedAdminAccountListPostgresRulesAndPagination(t *testing.T) {
}}}
ctx := adminaccess.WithPrincipal(context.Background(), principal)
for page, wantID := range []int64{1, 4} {
rows, total, listErr := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: page + 1, PageSize: 1}, "", "", "", "")
rows, total, listErr := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: page + 1, PageSize: 1}, "", "", "", "", 0)
require.NoError(t, listErr)
require.EqualValues(t, 2, total)
require.Len(t, rows, 1)
@@ -129,7 +129,7 @@ func TestScopedAdminAccountListPostgresRulesAndPagination(t *testing.T) {
for _, credentials := range []string{`{}`, `{"model_mapping":null}`, `{"model_mapping":{}}`, `{"model_mapping":[]}`, `{"model_mapping":"invalid"}`, `{"model_mapping":{"bad":{"token":"SECRET"},"number":1},"access_token":"SECRET"}`} {
_, err = db.Exec(`UPDATE accounts SET credentials=$1::jsonb WHERE id=4`, credentials)
require.NoError(t, err)
rows, total, listErr := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: 2, PageSize: 1}, "", "", "", "")
rows, total, listErr := repo.ScopedAdminList(ctx, pagination.PaginationParams{Page: 2, PageSize: 1}, "", "", "", "", 0)
require.NoError(t, listErr)
require.EqualValues(t, 2, total)
require.Len(t, rows, 1)
@@ -137,12 +137,12 @@ func TestScopedAdminAccountListPostgresRulesAndPagination(t *testing.T) {
require.Empty(t, rows[0].Credentials)
}
principal.Policy.Rules = []adminaccess.Rule{{Permissions: []string{"accounts.read"}, AllGroups: true, AccountTypes: []string{"oauth"}}}
rows, total, err := repo.ScopedAdminList(ctx, pagination.DefaultPagination(), "", "", "", "")
rows, total, err := repo.ScopedAdminList(ctx, pagination.DefaultPagination(), "", "", "", "", 0)
require.NoError(t, err)
require.EqualValues(t, 3, total, "全部分组不包含无分组账户")
require.Len(t, rows, 3)
principal.Policy.Rules[0].IncludeUngrouped = true
_, total, err = repo.ScopedAdminList(ctx, pagination.DefaultPagination(), "", "", "", "")
_, total, err = repo.ScopedAdminList(ctx, pagination.DefaultPagination(), "", "", "", "", 0)
require.NoError(t, err)
require.EqualValues(t, 4, total)
}
@@ -88,7 +88,19 @@ func (r *scopedAdminKeyRepository) UpdateScopedAdminKey(ctx context.Context, k *
if e != nil {
return e
}
return scopedAdminKeyResult(r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET name=$2,description=$3,enabled=$4,expires_at=$5,allowed_ips=$6,policy=$7,updated_at=$8 WHERE id=$1 AND revoked_at IS NULL`, k.ID, k.Name, k.Description, k.Enabled, k.ExpiresAt, string(ips), string(policy), k.UpdatedAt))
// 只允许更新刚读取的版本,避免并发收权后旧请求恢复全权模式。
result, err := r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET name=$2,description=$3,enabled=$4,expires_at=$5,allowed_ips=$6,policy=$7,updated_at=$8 WHERE id=$1 AND revoked_at IS NULL AND updated_at=$9`, k.ID, k.Name, k.Description, k.Enabled, k.ExpiresAt, string(ips), string(policy), k.UpdatedAt, k.ExpectedUpdatedAt)
if err != nil {
return err
}
affected, err := result.RowsAffected()
if err != nil {
return err
}
if affected == 0 {
return service.ErrScopedAdminKeyConflict
}
return nil
}
func (r *scopedAdminKeyRepository) TouchScopedAdminKey(ctx context.Context, id, expectedHash string, expectedUpdatedAt time.Time, ip string, now time.Time) error {
return scopedAdminKeyResult(r.db.ExecContext(ctx, `UPDATE scoped_admin_api_keys SET last_used_at=$5,last_used_ip=$4 WHERE id=$1 AND key_hash=$2 AND updated_at=$3 AND revoked_at IS NULL AND enabled=true AND (expires_at IS NULL OR expires_at>$5)`, id, expectedHash, expectedUpdatedAt, ip, now))
@@ -144,3 +144,23 @@ func TestScopedAdminKeyPostgresMigrationAndLifecycle(t *testing.T) {
_, _, err = settings.RotateScopedAdminKey(ctx, item.ID)
require.ErrorIs(t, err, service.ErrScopedAdminKeyNotFound)
}
func TestAdminFullAccessPostgresStaleEditCannotRestorePrivileges(t *testing.T) {
db := scopedAdminKeyTestDB(t)
repo := NewScopedAdminKeyRepository(db)
settings := service.NewSettingService(nil, nil)
settings.SetScopedAdminKeyRepository(repo)
ctx := context.Background()
key, item, err := settings.CreateScopedAdminKey(ctx, service.ScopedAdminKeyInput{Name: "兼容", Enabled: true, ConfirmFullAccess: true, Policy: adminaccess.Policy{FullAccess: true}}, 9)
require.NoError(t, err)
stale, err := repo.GetScopedAdminKey(ctx, item.ID)
require.NoError(t, err)
stale.ExpectedUpdatedAt = stale.UpdatedAt
_, err = settings.UpdateScopedAdminKey(ctx, item.ID, service.ScopedAdminKeyInput{Name: "收权", Enabled: true})
require.NoError(t, err)
stale.UpdatedAt = time.Now().UTC()
require.ErrorIs(t, repo.UpdateScopedAdminKey(ctx, stale), service.ErrScopedAdminKeyConflict)
current, err := settings.AuthenticateScopedAdminKey(ctx, key, "192.0.2.1")
require.NoError(t, err)
require.False(t, current.Policy.FullAccess)
}
@@ -44,7 +44,7 @@ func TestScopedAdminKeyRepositoryEditDoesNotRestoreOldHash(t *testing.T) {
defer db.Close()
repo := NewScopedAdminKeyRepository(db)
k := &service.ScopedAdminKey{ID: "id", Hash: "旧摘要", ScopedAdminKeyInput: service.ScopedAdminKeyInput{Name: "更新", AllowedIPs: []string{}}, UpdatedAt: time.Now().UTC()}
mock.ExpectExec(`UPDATE scoped_admin_api_keys SET name=\$2,description=\$3,enabled=\$4,expires_at=\$5,allowed_ips=\$6,policy=\$7,updated_at=\$8 WHERE id=\$1 AND revoked_at IS NULL`).WithArgs(k.ID, k.Name, k.Description, k.Enabled, k.ExpiresAt, "[]", sqlmock.AnyArg(), k.UpdatedAt).WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectExec(`UPDATE scoped_admin_api_keys SET name=\$2,description=\$3,enabled=\$4,expires_at=\$5,allowed_ips=\$6,policy=\$7,updated_at=\$8 WHERE id=\$1 AND revoked_at IS NULL`).WithArgs(k.ID, k.Name, k.Description, k.Enabled, k.ExpiresAt, "[]", sqlmock.AnyArg(), k.UpdatedAt, k.ExpectedUpdatedAt).WillReturnResult(sqlmock.NewResult(0, 1))
require.NoError(t, repo.UpdateScopedAdminKey(context.Background(), k))
require.NoError(t, mock.ExpectationsWereMet())
}
@@ -268,7 +268,7 @@ func recordAdminKeyRequest(c *gin.Context, audit *service.AuditLogService, item
}
entry := &service.AuditLog{CreatedAt: time.Now().UTC(), AuthMethod: service.AuditAuthMethodAdminAPIKey, Action: "admin.api_key.request", Method: c.Request.Method, Path: c.Request.URL.Path, StatusCode: c.Writer.Status(), ClientIP: SecurityClientIP(c), UserAgent: c.Request.UserAgent()}
if item != nil {
entry.Extra = map[string]any{"admin_key_id": item.ID, "admin_key_name": item.Name}
entry.Extra = map[string]any{"admin_key_id": item.ID, "admin_key_name": item.Name, "full_access": item.Policy.FullAccess}
uid := item.CreatedBy
entry.ActorUserID = &uid
}
@@ -52,6 +52,7 @@ func SkipAudit(c *gin.Context) {
// scalar, non-secret operation summaries. Request bodies and arbitrary maps
// are never accepted through this channel.
var auditExtraAllowedKeys = map[string]struct{}{
"admin_key_id": {}, "full_access": {}, "full_access_before": {},
"mcp_grant_id": {}, "mcp_tool": {},
"result": {}, "error_code": {}, "enabled": {}, "blocking_enabled": {},
"config_version": {}, "endpoint_count": {}, "scanner_count": {},
@@ -168,3 +168,21 @@ func TestScopedAdminKeyPanelRateLimitPreservesUnrestrictedAdminWrites(t *testing
})
}
}
func TestAdminFullAccessRetainsPerKeyRateLimit(t *testing.T) {
allower := &fakePanelAllower{}
limiter := &PanelRateLimiter{limiter: allower, settingService: newPanelRateLimitTestService(t, `{"enabled":true,"user_rpm":1,"heavy_rpm":1,"exempt_admin":true}`)}
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set(string(ContextKeyUser), AuthSubject{UserID: 9})
c.Set(string(ContextKeyUserRole), service.RoleAdmin)
c.Request = c.Request.WithContext(adminaccess.WithPrincipal(c.Request.Context(), &adminaccess.Principal{KeyID: "full", Policy: adminaccess.Policy{FullAccess: true}}))
}, limiter.Global())
r.GET("/full", func(c *gin.Context) { c.Status(204) })
for _, want := range []int{204, 429} {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest("GET", "/full", nil))
require.Equal(t, want, w.Code)
}
require.Equal(t, int64(2), allower.counts["panel:global:admin-key:full"])
}
@@ -115,3 +115,36 @@ func TestScopedAdminKeyMissingDependenciesFailClosed(t *testing.T) {
require.NotPanics(t, func() { r.ServeHTTP(w, req) })
require.Equal(t, 401, w.Code)
}
func TestAdminFullAccessKeepsIdentityAndJWTBoundary(t *testing.T) {
repo := &adminAuthKeyRepo{}
settings := service.NewSettingService(nil, nil)
settings.SetScopedAdminKeyRepository(repo)
key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "兼容", Enabled: true, ConfirmFullAccess: true, Policy: adminaccess.Policy{FullAccess: true}}, 9)
require.NoError(t, err)
users := service.NewUserService(&stubUserRepo{getByID: func(context.Context, int64) (*service.User, error) {
return &service.User{ID: 9, Role: service.RoleAdmin, Status: service.StatusActive}, nil
}}, nil, nil, nil)
r := gin.New()
r.Use(gin.HandlerFunc(NewAdminAuthMiddleware(nil, users, settings, nil)))
r.GET("/api/v1/admin/future", func(c *gin.Context) {
require.NotNil(t, adminaccess.FromContext(c.Request.Context()))
require.Nil(t, adminaccess.RestrictedFromContext(c.Request.Context()))
require.Equal(t, service.AuditAuthMethodAdminAPIKey, c.GetString("auth_method"))
c.Status(204)
})
r.POST("/api/v1/admin/settings/admin-api-keys", func(c *gin.Context) { t.Fatal("全权key不能管理密钥") })
r.GET("/api/v1/admin/interactive", func(c *gin.Context) {
require.False(t, enforceStepUp(c, nil, nil, nil))
})
for _, tc := range []struct {
method, path string
status int
}{{"GET", "/api/v1/admin/future", 204}, {"POST", "/api/v1/admin/settings/admin-api-keys", 403}, {"GET", "/api/v1/admin/interactive", 403}} {
w := httptest.NewRecorder()
req := httptest.NewRequest(tc.method, tc.path, nil)
req.Header.Set("x-api-key", key)
r.ServeHTTP(w, req)
require.Equal(t, tc.status, w.Code, w.Body.String())
}
}
@@ -76,7 +76,7 @@ func (*scopedRouteAccounts) GetAccount(_ context.Context, id int64) (*service.Ac
}
return a, nil
}
func (s *scopedRouteAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]service.Account, int64, error) {
func (s *scopedRouteAccounts) ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]service.Account, int64, error) {
s.t.Fatal("本测试中列表必须在权限准入阶段被拒绝")
return nil, 0, nil
}
@@ -0,0 +1,96 @@
//go:build unit
package routes
import (
"context"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/handler"
adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
type fullAccessRouteService struct{ scopedRouteAccounts }
func (*fullAccessRouteService) GetProxy(context.Context, int64) (*service.Proxy, error) {
return &service.Proxy{ID: 9, Username: "proxy-user", Password: "proxy-secret", Status: "active"}, nil
}
func (*fullAccessRouteService) GetGroup(context.Context, int64) (*service.Group, error) {
return &service.Group{ID: 9, Name: "完整分组", Platform: "openai", RateMultiplier: 12.5}, nil
}
func TestAdminFullAccessRegisteredRoutesPreserveFullHandlers(t *testing.T) {
gin.SetMode(gin.TestMode)
keys := &scopedRouteKeys{}
settings := service.NewSettingService(nil, nil)
settings.SetScopedAdminKeyRepository(keys)
key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "完整管理", Enabled: true, ConfirmFullAccess: true, Policy: adminaccess.Policy{FullAccess: true}}, 9)
require.NoError(t, err)
svc := &fullAccessRouteService{scopedRouteAccounts{t: t}}
account := adminhandler.NewAccountHandler(svc, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
auth := middleware.NewAdminAuthMiddleware(nil, service.NewUserService(&scopedRouteUsers{}, nil, nil, nil), settings, nil)
r := gin.New()
RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Account: account, Group: adminhandler.NewGroupHandler(svc, nil, nil), Proxy: adminhandler.NewProxyHandler(svc)}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.AbortWithStatus(403) }), nil, nil)
for _, tc := range []struct{ path, contains string }{
{"/accounts/3", `"group_ids":[2]`},
{"/groups/9", `"rate_multiplier":12.5`},
{"/proxies/9", `"password":"proxy-secret"`},
} {
req := httptest.NewRequest("GET", "/api/v1/admin"+tc.path, nil)
req.Header.Set("x-api-key", key)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, 200, w.Code, tc.path+": "+w.Body.String())
require.Contains(t, w.Body.String(), tc.contains)
}
// 密钥全权模式仍不跨越真人会话边界。
for _, path := range []string{"/api/v1/admin/settings/admin-api-keys", "/api/v1/admin/accounts/data"} {
req := httptest.NewRequest("GET", path, nil)
req.Header.Set("x-api-key", key)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, 403, w.Code)
}
}
func TestAdminFullAccessCreationRequiresHTTPConfirmation(t *testing.T) {
for _, tc := range []struct {
body string
status int
}{
{`{"name":"兼容","enabled":true,"policy":{"full_access":true}}`, 400},
{`{"name":"兼容","enabled":true,"policy":{"full_access":true},"confirm_full_access":"true"}`, 400},
{`{"name":"兼容","enabled":true,"policy":{"full_access":true},"confirm_full_access":true}`, 200},
} {
keys := &scopedRouteKeys{}
settings := service.NewSettingService(nil, nil)
settings.SetScopedAdminKeyRepository(keys)
r := gin.New()
auth := middleware.AdminAuthMiddleware(func(c *gin.Context) {
c.Set("auth_method", service.AuditAuthMethodJWT)
c.Set(string(middleware.ContextKeyUserRole), service.RoleAdmin)
c.Set(string(middleware.ContextKeyUser), middleware.AuthSubject{UserID: 9})
c.Next()
})
RegisterAdminRoutes(r.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Setting: adminhandler.NewSettingHandler(settings, nil, nil, nil, nil, nil, nil)}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil)
req := httptest.NewRequest("POST", "/api/v1/admin/settings/admin-api-keys", strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, tc.status, w.Code, w.Body.String())
if tc.status == 400 {
require.Nil(t, keys.item)
} else {
require.True(t, keys.item.Policy.FullAccess)
require.False(t, keys.item.ConfirmFullAccess)
require.NotContains(t, w.Body.String(), "confirm_full_access")
}
}
}
@@ -0,0 +1,200 @@
//go:build unit
package routes
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/handler"
adminhandler "github.com/Wei-Shaw/sub2api/internal/handler/admin"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
"github.com/Wei-Shaw/sub2api/internal/pkg/usagestats"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/imroc/req/v3"
"github.com/stretchr/testify/require"
)
type scopedRouteStatisticsAccounts struct{ scopedRouteAccounts }
func (s *scopedRouteStatisticsAccounts) GetAccount(ctx context.Context, id int64) (*service.Account, error) {
a, err := s.scopedRouteAccounts.GetAccount(ctx, id)
a.Credentials["access_token"] = "PRIVATE_TOKEN"
a.Credentials["chatgpt_account_id"] = "PRIVATE_ACCOUNT"
a.Credentials["plan_type"] = "plus"
return a, err
}
func (*scopedRouteStatisticsAccounts) GetGroup(_ context.Context, id int64) (*service.Group, error) {
return &service.Group{ID: id, Name: "组", Platform: "openai", Status: service.StatusActive}, nil
}
func (*scopedRouteStatisticsAccounts) ScopedAdminListGroupModels(context.Context, pagination.PaginationParams, bool, string, string, string) ([]service.Group, int64, error) {
return []service.Group{{ID: 1, Name: "组", Platform: "openai", Status: service.StatusActive}}, 1, nil
}
type scopedRouteStatisticsRepo struct {
service.AccountRepository
admin *scopedRouteStatisticsAccounts
}
func (s *scopedRouteStatisticsRepo) GetByID(ctx context.Context, id int64) (*service.Account, error) {
return s.admin.GetAccount(ctx, id)
}
func (s *scopedRouteStatisticsRepo) GetByIDs(ctx context.Context, ids []int64) ([]*service.Account, error) {
out := []*service.Account{}
for _, id := range ids {
a, err := s.GetByID(ctx, id)
if err != nil {
return nil, err
}
out = append(out, a)
}
return out, nil
}
func (*scopedRouteStatisticsRepo) UpdateExtra(context.Context, int64, map[string]any) error {
return nil
}
func (*scopedRouteStatisticsRepo) ListSchedulableCapacityByGroupIDs(context.Context, []int64) ([]service.GroupAccountCapacityRow, error) {
return nil, nil
}
type scopedRouteStatisticsLogs struct {
service.UsageLogRepository
reads atomic.Int64
}
func (s *scopedRouteStatisticsLogs) GetAccountTodayStats(context.Context, int64) (*usagestats.AccountStats, error) {
s.reads.Add(1)
return &usagestats.AccountStats{Requests: 7, Cost: 12}, nil
}
func (s *scopedRouteStatisticsLogs) GetAccountWindowStats(context.Context, int64, time.Time) (*usagestats.AccountStats, error) {
s.reads.Add(1)
return &usagestats.AccountStats{Requests: 7, Cost: 12}, nil
}
func (s *scopedRouteStatisticsLogs) GetAccountUsageStats(context.Context, int64, time.Time, time.Time) (*usagestats.AccountUsageStatsResponse, error) {
s.reads.Add(1)
return &usagestats.AccountUsageStatsResponse{}, nil
}
type scopedRouteCapacityGroups struct{ service.GroupRepository }
func (*scopedRouteCapacityGroups) ListScopedAdminCapacityGroupIDs(context.Context) ([]int64, error) {
return []int64{1}, nil
}
type scopedRouteReferrals struct{ queries, sends atomic.Int64 }
func (s *scopedRouteReferrals) QueryEligibility(context.Context, service.OpenAIReferralCall) (*service.OpenAIReferralEligibility, error) {
s.queries.Add(1)
count := 2
confirm := true
return &service.OpenAIReferralEligibility{ShouldShow: true, RemainingSendCapacity: &count, RequiresExplicitConfirmation: &confirm}, nil
}
func (s *scopedRouteReferrals) SendInvite(context.Context, service.OpenAIReferralCall, string) error {
s.sends.Add(1)
return nil
}
func TestScopedAdminRegisteredStatisticsAndOpenAIRoutes(t *testing.T) {
gin.SetMode(gin.TestMode)
cases := []struct {
permission, method, path, body string
want int
}{
{"accounts.stats.read", "GET", "/accounts/1/today-stats", "", 200},
{"accounts.stats.read", "GET", "/accounts/1/stats", "", 200},
{"accounts.stats.read", "POST", "/accounts/today-stats/batch", `{"account_ids":[1,1]}`, 200},
{"accounts.usage.read", "GET", "/accounts/1/usage", "", 200},
{"accounts.usage.read", "POST", "/accounts/usage/batch", `{"account_ids":[1,1]}`, 200},
{"openai.quota.read", "GET", "/openai/accounts/1/quota", "", 200},
{"openai.quota.read", "POST", "/openai/accounts/1/quota/refresh", "", 200},
{"openai.quota.reset", "POST", "/openai/accounts/1/reset-quota", "", 200},
{"openai.referrals.read", "POST", "/openai/accounts/1/referrals/refresh", "", 200},
{"openai.referrals.invite", "POST", "/openai/accounts/1/referrals/invite", `{"email":"friend@example.com","program_id":"codex_referral_consumer","confirmed":true}`, 200},
{"groups.list.read", "GET", "/groups", "", 200},
{"groups.capacity.read", "GET", "/groups/capacity-summary", "", 200},
{"openai.tokens.refresh", "POST", "/openai/refresh-token", `{}`, 400},
}
for _, tc := range cases {
for _, allowed := range []bool{false, true} {
t.Run(tc.permission+tc.path+map[bool]string{false: "/默认拒绝", true: "/显式授权"}[allowed], func(t *testing.T) {
policy := adminaccess.Policy{Rules: []adminaccess.Rule{{GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}
if allowed {
if tc.permission == "openai.tokens.refresh" {
policy.GlobalPermissions = []string{tc.permission}
} else {
policy.Rules[0].Permissions = []string{tc.permission}
}
}
settings := service.NewSettingService(nil, nil)
settings.SetScopedAdminKeyRepository(&scopedRouteKeys{})
key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "统计路由", Enabled: true, Policy: policy}, 9)
require.NoError(t, err)
users := service.NewUserService(&scopedRouteUsers{}, nil, nil, nil)
auth := middleware.NewAdminAuthMiddleware(nil, users, settings, nil)
admin := &scopedRouteStatisticsAccounts{scopedRouteAccounts: scopedRouteAccounts{t: t}}
repo := &scopedRouteStatisticsRepo{admin: admin}
logs := &scopedRouteStatisticsLogs{}
referrals := &scopedRouteReferrals{}
var calls atomic.Int64
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.Header().Set("Content-Type", "application/json")
if strings.HasSuffix(r.URL.Path, "/consume") {
_, _ = w.Write([]byte(`{"code":"success","windows_reset":1}`))
} else if strings.HasSuffix(r.URL.Path, "/credits") {
_, _ = w.Write([]byte(`{"available_count":0,"credits":[]}`))
} else {
_, _ = w.Write([]byte(`{"email":"PRIVATE_EMAIL","account_id":"PRIVATE_ACCOUNT","rate_limit":{"allowed":true,"primary_window":{"used_percent":25}},"rate_limit_reset_credits":{"available_count":0},"credits":{"has_credits":true,"balance":"50"}}`))
}
}))
defer srv.Close()
target, _ := url.Parse(srv.URL)
factory := func(string) (*req.Client, error) {
return req.C().WrapRoundTripFunc(func(rt req.RoundTripper) req.RoundTripFunc {
return func(r *req.Request) (*req.Response, error) {
r.URL.Scheme = target.Scheme
r.URL.Host = target.Host
return rt.RoundTrip(r)
}
}), nil
}
quota := service.NewOpenAIQuotaService(repo, nil, service.NewOpenAITokenProvider(repo, nil, nil), factory, referrals)
usage := service.NewAccountUsageService(repo, logs, nil, nil, nil, nil, nil, quota, service.NewUsageCache(), nil, nil)
accounts := adminhandler.NewAccountHandler(admin, nil, nil, nil, nil, nil, nil, usage, nil, nil, nil, nil, nil, nil)
openai := adminhandler.NewOpenAIOAuthHandler(nil, admin, quota, nil)
groups := adminhandler.NewGroupHandler(admin, nil, service.NewGroupCapacityService(repo, &scopedRouteCapacityGroups{}, nil, nil, nil))
router := gin.New()
RegisterAdminRoutes(router.Group("/api/v1"), &handler.Handlers{Admin: &handler.AdminHandlers{Account: accounts, OpenAIOAuth: openai, Group: groups}}, auth, middleware.AuditLogMiddleware(func(c *gin.Context) { c.Next() }), middleware.StepUpAuthMiddleware(func(c *gin.Context) { c.Next() }), nil, nil)
request := httptest.NewRequest(tc.method, "/api/v1/admin"+tc.path, strings.NewReader(tc.body))
request.Header.Set("x-api-key", key)
request.Header.Set("Content-Type", "application/json")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
want := 403
if allowed {
want = tc.want
}
require.Equal(t, want, recorder.Code, recorder.Body.String())
require.NotContains(t, recorder.Body.String(), "PRIVATE_")
if !allowed {
require.Zero(t, calls.Load())
require.Zero(t, logs.reads.Load())
require.Zero(t, referrals.queries.Load())
require.Zero(t, referrals.sends.Load())
}
if tc.permission != "openai.referrals.invite" {
require.Zero(t, referrals.sends.Load())
}
})
}
}
}
@@ -13,6 +13,7 @@ import (
"sync"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
httppool "github.com/Wei-Shaw/sub2api/internal/pkg/httpclient"
openaipkg "github.com/Wei-Shaw/sub2api/internal/pkg/openai"
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
@@ -346,6 +347,9 @@ func batchUsageErrorMessage(err error) string {
}
func (s *AccountUsageService) getUsageForAccount(ctx context.Context, account *Account, forceProbe bool) (*UsageInfo, error) {
if err := scopedAccountAccess(ctx, s.accountRepo, account, "accounts.usage.read", true); err != nil {
return nil, err
}
if account == nil {
return nil, fmt.Errorf("account is required")
}
@@ -512,6 +516,16 @@ func (s *AccountUsageService) GetUsageForAccount(ctx context.Context, account *A
// Anthropic OAuth/SetupToken 统一走 passive 链路,其他账号复用现有主动查询逻辑。
// 单个账号失败不会中断整批请求,错误会按账号返回。
func (s *AccountUsageService) GetUsageBatch(ctx context.Context, accountIDs []int64, force bool) (map[int64]*UsageInfo, map[int64]string, error) {
if adminaccess.RestrictedFromContext(ctx) != nil {
if len(accountIDs) > 100 {
return nil, nil, fmt.Errorf("账户数量超过限制")
}
for _, id := range accountIDs {
if id <= 0 {
return nil, nil, fmt.Errorf("账户 ID 无效")
}
}
}
uniqueIDs := make([]int64, 0, len(accountIDs))
seen := make(map[int64]struct{}, len(accountIDs))
for _, accountID := range accountIDs {
@@ -544,6 +558,13 @@ func (s *AccountUsageService) GetUsageBatch(ctx context.Context, accountIDs []in
accountsByID[account.ID] = account
}
if adminaccess.RestrictedFromContext(ctx) != nil {
for _, id := range uniqueIDs {
if err := scopedAccountAccess(ctx, s.accountRepo, accountsByID[id], "accounts.usage.read", true); err != nil {
return nil, nil, err
}
}
}
var mu sync.Mutex
g, gctx := errgroup.WithContext(ctx)
g.SetLimit(6)
@@ -595,6 +616,9 @@ func (s *AccountUsageService) GetPassiveUsage(ctx context.Context, accountID int
}
func (s *AccountUsageService) getPassiveUsageForAccount(ctx context.Context, account *Account) (*UsageInfo, error) {
if err := scopedAccountAccess(ctx, s.accountRepo, account, "accounts.usage.read", false); err != nil {
return nil, err
}
if !supportsAnthropicPassiveUsage(account) {
return nil, fmt.Errorf("passive usage only supported for Anthropic OAuth/SetupToken accounts")
}
@@ -717,17 +741,32 @@ func (s *AccountUsageService) getOpenAIUsage(ctx context.Context, account *Accou
applyExtraToUsage(usage, account.Extra, now)
if (force || shouldRefreshOpenAICodexSnapshot(account, usage, now)) && s.shouldProbeOpenAICodexSnapshot(account.ID, now, force) {
if account.IsShadow() {
if adminaccess.RestrictedFromContext(ctx) != nil {
// 受限额度读取只调用额度 API,不生成 /responses 合成请求或消费重置次数。
if s.openAIQuotaService != nil {
if quotaUsage, err := s.openAIQuotaService.QueryUsage(WithScopedAdminAccountOperation(ctx, "accounts.usage.read"), account.ID); err == nil {
updates := buildOpenAIAutoResetUsageUpdates(quotaUsage, now)
if account.IsShadow() {
updates = buildCodexSparkWindowExtraUpdates(quotaUsage, now)
}
if len(updates) > 0 {
mergeAccountExtra(account, updates)
s.persistOpenAICodexProbeSnapshotContext(ctx, account.ID, updates)
applyExtraToUsage(usage, account.Extra, now)
}
}
}
} else if account.IsShadow() {
// Spark shadow accounts fetch usage from /wham/usage (bengalfox channel)
// via the shared OpenAIQuotaService, which resolves credentials from the
// parent account. The result is written to the shadow row's own codex_*
// Extra keys and immediately reflected in the returned UsageInfo.
if s.openAIQuotaService != nil {
if quotaUsage, err := s.openAIQuotaService.QueryUsage(ctx, account.ID); err == nil {
if quotaUsage, err := s.openAIQuotaService.QueryUsage(WithScopedAdminAccountOperation(ctx, "accounts.usage.read"), account.ID); err == nil {
if updates := buildCodexSparkWindowExtraUpdates(quotaUsage, now); len(updates) > 0 {
mergeAccountExtra(account, updates)
s.persistOpenAICodexProbeSnapshot(account.ID, updates)
if account.ParentAccountID != nil {
s.persistOpenAICodexProbeSnapshotContext(ctx, account.ID, updates)
if account.ParentAccountID != nil && adminaccess.RestrictedFromContext(ctx) == nil {
notifyOpenAIAutoReset(*account.ParentAccountID)
}
if usage.UpdatedAt == nil {
@@ -905,13 +944,17 @@ func (s *AccountUsageService) probeOpenAICodexSnapshot(ctx context.Context, acco
return nil, err
}
if len(updates) > 0 {
s.persistOpenAICodexProbeSnapshot(account.ID, updates)
s.persistOpenAICodexProbeSnapshotContext(ctx, account.ID, updates)
return updates, nil
}
return nil, nil
}
func (s *AccountUsageService) persistOpenAICodexProbeSnapshot(accountID int64, updates map[string]any) {
s.persistOpenAICodexProbeSnapshotContext(context.Background(), accountID, updates)
}
func (s *AccountUsageService) persistOpenAICodexProbeSnapshotContext(ctx context.Context, accountID int64, updates map[string]any) {
if s == nil || s.accountRepo == nil || accountID <= 0 {
return
}
@@ -920,9 +963,12 @@ func (s *AccountUsageService) persistOpenAICodexProbeSnapshot(accountID int64, u
}
go func() {
updateCtx, updateCancel := context.WithTimeout(context.Background(), 5*time.Second)
updateCtx, updateCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer updateCancel()
if err := s.accountRepo.UpdateExtra(updateCtx, accountID, updates); err == nil {
if err := scopedAccountIDAccess(updateCtx, s.accountRepo, accountID, "accounts.usage.read", true); err != nil {
return
}
if err := s.accountRepo.UpdateExtra(updateCtx, accountID, updates); err == nil && adminaccess.RestrictedFromContext(ctx) == nil {
notifyOpenAIAutoReset(accountID)
}
}()
@@ -1063,7 +1109,7 @@ func (s *AccountUsageService) getAntigravityUsage(ctx context.Context, account *
}
// 使用独立 context,避免调用方 cancel 导致所有共享 flight 的请求失败
fetchCtx, fetchCancel := context.WithTimeout(context.Background(), 30*time.Second)
fetchCtx, fetchCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer fetchCancel()
proxyURL := s.antigravityQuotaFetcher.GetProxyURL(fetchCtx, account)
@@ -1392,6 +1438,9 @@ func (s *AccountUsageService) addWindowStats(ctx context.Context, account *Accou
// GetTodayStats 获取账号今日统计
func (s *AccountUsageService) GetTodayStats(ctx context.Context, accountID int64) (*WindowStats, error) {
if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, "accounts.stats.read", false); err != nil {
return nil, err
}
stats, err := s.usageLogRepo.GetAccountTodayStats(ctx, accountID)
if err != nil {
return nil, fmt.Errorf("get today stats failed: %w", err)
@@ -1408,6 +1457,16 @@ func (s *AccountUsageService) GetTodayStats(ctx context.Context, accountID int64
// GetTodayStatsBatch 批量获取账号今日统计,优先走批量 SQL,失败时回退单账号查询。
func (s *AccountUsageService) GetTodayStatsBatch(ctx context.Context, accountIDs []int64) (map[int64]*WindowStats, error) {
if adminaccess.RestrictedFromContext(ctx) != nil {
if len(accountIDs) > 100 {
return nil, fmt.Errorf("账户数量超过限制")
}
for _, id := range accountIDs {
if err := scopedAccountIDAccess(ctx, s.accountRepo, id, "accounts.stats.read", false); err != nil {
return nil, err
}
}
}
uniqueIDs := make([]int64, 0, len(accountIDs))
seen := make(map[int64]struct{}, len(accountIDs))
for _, accountID := range accountIDs {
@@ -1550,6 +1609,9 @@ func codexWindowStatsStart(progress *UsageProgress, fallbackWindow time.Duration
}
func (s *AccountUsageService) GetAccountUsageStats(ctx context.Context, accountID int64, startTime, endTime time.Time) (*usagestats.AccountUsageStatsResponse, error) {
if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, "accounts.stats.read", false); err != nil {
return nil, err
}
stats, err := s.usageLogRepo.GetAccountUsageStats(ctx, accountID, startTime, endTime)
if err != nil {
return nil, fmt.Errorf("get account usage stats failed: %w", err)
@@ -1606,6 +1668,10 @@ func parseTime(s string) (time.Time, error) {
}
func (s *AccountUsageService) tryClearRecoverableAccountError(ctx context.Context, account *Account) {
// 额度读取不能隐式恢复账户状态或调度。
if adminaccess.RestrictedFromContext(ctx) != nil {
return
}
if account == nil || account.Status != StatusError {
return
}
@@ -18,7 +18,7 @@ import (
// ScopedAdminAccounts 只提供受限管理密钥需要的窄接口。
type ScopedAdminAccounts interface {
ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]Account, int64, error)
ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]Account, int64, error)
ScopedAdminWrite(context.Context, int64, string, map[string]json.RawMessage, func(context.Context, *Account) (*Account, error)) (*Account, error)
}
@@ -45,6 +45,21 @@ func scopedAccountFieldPermissions(fields map[string]json.RawMessage, create boo
permission = "accounts.schedule"
case "proxy_id", "proxy_mode", "random_proxy":
permission = "accounts.network"
case "rate_multiplier":
var rate float64
if string(raw) == "null" || json.Unmarshal(raw, &rate) != nil || rate < 0 {
return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_RATE", "账户倍率无效")
}
permission = "accounts.rate.write"
case "extra":
if !create {
return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_FIELD", "仅创建支持身份与连接选项")
}
if err := validateScopedOpenAIOptions(raw); err != nil {
return nil, err
}
permissions = append(permissions, "accounts.options.write")
continue
case "group_ids":
permission = "accounts.groups"
case "platform", "type":
@@ -58,6 +73,23 @@ func scopedAccountFieldPermissions(fields map[string]json.RawMessage, create boo
return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_CREDENTIALS", "凭证格式无效")
}
for name, value := range credentials {
if name == "expires_at" {
var expires int64
if string(value) == "null" || json.Unmarshal(value, &expires) != nil || expires < 0 {
return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_CREDENTIALS", "凭证到期时间无效")
}
permissions = append(permissions, "accounts.credentials")
continue
}
if slices.Contains([]string{"email", "chatgpt_account_id", "chatgpt_user_id", "organization_id", "plan_type", "subscription_expires_at", "client_id"}, name) {
var text string
if json.Unmarshal(value, &text) != nil || len(text) > 4096 {
return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_CREDENTIALS", "身份字段格式无效")
}
permissions = append(permissions, "accounts.credentials")
continue
}
// 白名单与映射共用 model_mapping,只授予模型配置写入权限。
if name == "model_mapping" {
var mapping map[string]json.RawMessage
@@ -90,7 +122,7 @@ func scopedAccountFieldPermissions(fields map[string]json.RawMessage, create boo
default:
return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_FIELD", "请求包含不开放的账户字段")
}
if !create || permission == "accounts.schedule" || permission == "accounts.network" {
if !create || permission == "accounts.schedule" || permission == "accounts.network" || permission == "accounts.rate.write" {
permissions = append(permissions, permission)
} else if key == "status" || key == "schedulable" {
return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "创建不支持状态字段")
@@ -99,14 +131,14 @@ func scopedAccountFieldPermissions(fields map[string]json.RawMessage, create boo
return permissions, nil
}
func (s *adminServiceImpl) ScopedAdminList(ctx context.Context, p pagination.PaginationParams, platform, kind, status, search string) ([]Account, int64, error) {
func (s *adminServiceImpl) ScopedAdminList(ctx context.Context, p pagination.PaginationParams, platform, kind, status, search string, groupID int64) ([]Account, int64, error) {
repo, ok := s.accountRepo.(interface {
ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string) ([]Account, int64, error)
ScopedAdminList(context.Context, pagination.PaginationParams, string, string, string, string, int64) ([]Account, int64, error)
})
if !ok {
return nil, 0, fmt.Errorf("受限账户查询不可用")
}
return repo.ScopedAdminList(ctx, p, platform, kind, status, search)
return repo.ScopedAdminList(ctx, p, platform, kind, status, search, groupID)
}
func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, action string, fields map[string]json.RawMessage, run func(context.Context, *Account) (*Account, error)) (*Account, error) {
@@ -123,20 +155,22 @@ func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, actio
}
if id == 0 {
var input struct {
ProxyID *int64 `json:"proxy_id"`
ProxyMode string `json:"proxy_mode"`
RandomProxy bool `json:"random_proxy"`
Name string `json:"name"`
Notes *string `json:"notes"`
Platform string `json:"platform"`
Type string `json:"type"`
Credentials map[string]any `json:"credentials"`
GroupIDs []int64 `json:"group_ids"`
Concurrency int `json:"concurrency"`
Priority int `json:"priority"`
LoadFactor *int `json:"load_factor"`
ExpiresAt *int64 `json:"expires_at"`
AutoPause *bool `json:"auto_pause_on_expired"`
ProxyID *int64 `json:"proxy_id"`
ProxyMode string `json:"proxy_mode"`
RandomProxy bool `json:"random_proxy"`
Name string `json:"name"`
Notes *string `json:"notes"`
Extra map[string]any `json:"extra"`
Platform string `json:"platform"`
Type string `json:"type"`
Credentials map[string]any `json:"credentials"`
RateMultiplier *float64 `json:"rate_multiplier"`
GroupIDs []int64 `json:"group_ids"`
Concurrency int `json:"concurrency"`
Priority int `json:"priority"`
LoadFactor *int `json:"load_factor"`
ExpiresAt *int64 `json:"expires_at"`
AutoPause *bool `json:"auto_pause_on_expired"`
}
body, _ := json.Marshal(fields)
if err = json.Unmarshal(body, &input); err != nil {
@@ -151,6 +185,11 @@ func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, actio
if !slices.Contains(domain.ConcretePlatformIDs(), input.Platform) || input.Concurrency < 0 || input.Priority < 0 {
return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_INPUT", "创建参数无效")
}
if input.Extra != nil && (input.Platform != PlatformOpenAI || input.Type != AccountTypeOAuth) {
return nil, infraerrors.BadRequest("SCOPED_ACCOUNT_OPTIONS", "这些选项仅适用于 OpenAI OAuth")
}
// 隐私结果只能由服务端确认;空字符串同样会让 Ensure 跳过,必须删除键。
delete(input.Extra, "privacy_mode")
resource := adminaccess.Account{Type: input.Type, Platform: input.Platform, GroupIDs: input.GroupIDs}
if input.Type == "" || input.Platform == "" || !principal.Policy.AllowsAccount("accounts.create", resource) {
return nil, infraerrors.Forbidden("SCOPED_ACCOUNT_FORBIDDEN", "创建范围未授权")
@@ -170,7 +209,7 @@ func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, actio
if e != nil {
return nil, e
}
return s.scopedAdminCreateTransaction(ctx, &CreateAccountInput{ProxyID: input.ProxyID, ProxyMode: proxyMode, Name: input.Name, Notes: input.Notes, Platform: input.Platform, Type: input.Type, Credentials: input.Credentials, GroupIDs: input.GroupIDs, Concurrency: input.Concurrency, Priority: input.Priority, LoadFactor: input.LoadFactor, ExpiresAt: input.ExpiresAt, AutoPauseOnExpired: input.AutoPause, SkipDefaultGroupBind: true})
return s.scopedAdminCreateTransaction(ctx, &CreateAccountInput{ProxyID: input.ProxyID, ProxyMode: proxyMode, Name: input.Name, Notes: input.Notes, Platform: input.Platform, Type: input.Type, Credentials: input.Credentials, Extra: input.Extra, RateMultiplier: input.RateMultiplier, GroupIDs: input.GroupIDs, Concurrency: input.Concurrency, Priority: input.Priority, LoadFactor: input.LoadFactor, ExpiresAt: input.ExpiresAt, AutoPauseOnExpired: input.AutoPause, SkipDefaultGroupBind: true})
}
result, err := s.scopedAdminTransaction(ctx, id, action == "accounts.delete", func(txctx context.Context) (*Account, error) {
a, e := s.accountRepo.GetByID(txctx, id)
@@ -221,20 +260,21 @@ func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, actio
return s.ClearAccountError(txctx, id)
}
var input struct {
ProxyID *int64 `json:"proxy_id"`
ProxyMode string `json:"proxy_mode"`
RandomProxy bool `json:"random_proxy"`
Name string `json:"name"`
Notes *string `json:"notes"`
Credentials map[string]any `json:"credentials"`
Concurrency *int `json:"concurrency"`
Priority *int `json:"priority"`
LoadFactor *int `json:"load_factor"`
Status string `json:"status"`
GroupIDs *[]int64 `json:"group_ids"`
ExpiresAt *int64 `json:"expires_at"`
AutoPause *bool `json:"auto_pause_on_expired"`
Schedulable *bool `json:"schedulable"`
ProxyID *int64 `json:"proxy_id"`
ProxyMode string `json:"proxy_mode"`
RandomProxy bool `json:"random_proxy"`
Name string `json:"name"`
Notes *string `json:"notes"`
Credentials map[string]any `json:"credentials"`
RateMultiplier *float64 `json:"rate_multiplier"`
Concurrency *int `json:"concurrency"`
Priority *int `json:"priority"`
LoadFactor *int `json:"load_factor"`
Status string `json:"status"`
GroupIDs *[]int64 `json:"group_ids"`
ExpiresAt *int64 `json:"expires_at"`
AutoPause *bool `json:"auto_pause_on_expired"`
Schedulable *bool `json:"schedulable"`
}
body, _ := json.Marshal(fields)
if e = json.Unmarshal(body, &input); e != nil {
@@ -264,7 +304,7 @@ func (s *adminServiceImpl) ScopedAdminWrite(ctx context.Context, id int64, actio
maps.Copy(merged, input.Credentials)
input.Credentials = merged
}
updated, e := s.UpdateAccount(txctx, id, &UpdateAccountInput{ProxyID: input.ProxyID, Name: input.Name, Notes: input.Notes, Credentials: input.Credentials, Concurrency: input.Concurrency, Priority: input.Priority, LoadFactor: input.LoadFactor, Status: input.Status, GroupIDs: input.GroupIDs, ExpiresAt: input.ExpiresAt, AutoPauseOnExpired: input.AutoPause})
updated, e := s.UpdateAccount(txctx, id, &UpdateAccountInput{ProxyID: input.ProxyID, Name: input.Name, Notes: input.Notes, Credentials: input.Credentials, RateMultiplier: input.RateMultiplier, Concurrency: input.Concurrency, Priority: input.Priority, LoadFactor: input.LoadFactor, Status: input.Status, GroupIDs: input.GroupIDs, ExpiresAt: input.ExpiresAt, AutoPauseOnExpired: input.AutoPause})
if e != nil {
return nil, e
}
@@ -0,0 +1,88 @@
//go:build unit
package service
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func fullAccessInput(t *testing.T, confirm bool) ScopedAdminKeyInput {
t.Helper()
var input ScopedAdminKeyInput
data := `{"name":"兼容工具","enabled":true,"policy":{"full_access":true},"confirm_full_access":false}`
if confirm {
data = `{"name":"兼容工具","enabled":true,"policy":{"full_access":true},"confirm_full_access":true}`
}
require.NoError(t, json.Unmarshal([]byte(data), &input))
return input
}
func TestAdminFullAccessRequiresExplicitConfirmation(t *testing.T) {
s := &SettingService{scopedAdminKeyRepo: &scopedKeyMemoryRepo{}}
ctx := context.Background()
_, _, err := s.CreateScopedAdminKey(ctx, fullAccessInput(t, false), 9)
require.Error(t, err, "新建全权密钥必须显式确认")
_, item, err := s.CreateScopedAdminKey(ctx, ScopedAdminKeyInput{Name: "受限", Enabled: true}, 9)
require.NoError(t, err)
_, err = s.UpdateScopedAdminKey(ctx, item.ID, fullAccessInput(t, false))
require.Error(t, err, "受限密钥升级必须显式确认")
}
func TestAdminFullAccessConfirmationIsNotPersisted(t *testing.T) {
repo := &scopedKeyMemoryRepo{}
s := &SettingService{scopedAdminKeyRepo: repo}
ctx := context.Background()
key, item, err := s.CreateScopedAdminKey(ctx, fullAccessInput(t, true), 9)
require.NoError(t, err)
raw, err := json.Marshal(item)
require.NoError(t, err)
require.Contains(t, string(raw), `"full_access":true`)
require.NotContains(t, string(raw), `"confirm_full_access":true`)
_, err = s.UpdateScopedAdminKey(ctx, item.ID, fullAccessInput(t, false))
require.NoError(t, err, "不扩权的编辑不需要再次确认")
restricted := ScopedAdminKeyInput{Name: "关闭兼容", Enabled: true}
_, err = s.UpdateScopedAdminKey(ctx, item.ID, restricted)
require.NoError(t, err)
_, err = s.UpdateScopedAdminKey(ctx, item.ID, fullAccessInput(t, false))
require.Error(t, err, "再次开启仍需确认")
authenticated, err := s.AuthenticateScopedAdminKey(ctx, key, "192.0.2.1")
require.NoError(t, err)
raw, err = json.Marshal(authenticated.Policy)
require.NoError(t, err)
require.NotContains(t, string(raw), `"full_access":true`)
}
func TestAdminFullAccessLifecycleRestrictions(t *testing.T) {
repo := &scopedKeyMemoryRepo{}
s := &SettingService{scopedAdminKeyRepo: repo}
ctx := context.Background()
in := fullAccessInput(t, true)
in.AllowedIPs = []string{"192.0.2.0/24"}
key, item, err := s.CreateScopedAdminKey(ctx, in, 9)
require.NoError(t, err)
_, err = s.AuthenticateScopedAdminKey(ctx, key, "198.51.100.1")
require.Error(t, err)
next, _, err := s.RotateScopedAdminKey(ctx, item.ID)
require.NoError(t, err)
_, err = s.AuthenticateScopedAdminKey(ctx, key, "192.0.2.1")
require.Error(t, err)
_, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1")
require.NoError(t, err)
repo.item.Enabled = false
_, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1")
require.Error(t, err)
repo.item.Enabled = true
past := time.Now().Add(-time.Hour)
repo.item.ExpiresAt = &past
_, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1")
require.Error(t, err)
repo.item.ExpiresAt = nil
require.NoError(t, s.RevokeScopedAdminKey(ctx, item.ID))
_, err = s.AuthenticateScopedAdminKey(ctx, next, "192.0.2.1")
require.Error(t, err)
}
@@ -0,0 +1,40 @@
package service
import (
"encoding/json"
"slices"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
)
// 只接受对接客户端实际需要的字段,不能写入额度快照、任意 extra 或影子关系。
func validateScopedOpenAIOptions(raw json.RawMessage) error {
var fields map[string]json.RawMessage
invalid := infraerrors.BadRequest("SCOPED_ACCOUNT_OPTIONS", "身份与连接选项格式无效或包含不支持的字段")
if json.Unmarshal(raw, &fields) != nil || len(fields) == 0 {
return invalid
}
for key, value := range fields {
var text string
var flag bool
switch key {
case "email", "privacy_mode":
// privacy_mode 仅兼容旧客户端入参,创建前会移除,服务端仍独立核验。
if string(value) == "null" || json.Unmarshal(value, &text) != nil || len(text) > 512 {
return invalid
}
case "openai_oauth_responses_websockets_v2_mode":
if json.Unmarshal(value, &text) != nil || !slices.Contains([]string{"off", "shared", "dedicated", "ctx_pool", "passthrough", "http_bridge"}, text) {
return invalid
}
case "openai_oauth_responses_websockets_v2_enabled", "openai_long_context_billing_enabled":
if string(value) == "null" || json.Unmarshal(value, &flag) != nil {
return invalid
}
default:
return invalid
}
}
return nil
}
@@ -0,0 +1,158 @@
//go:build unit
package service
import (
"context"
"encoding/json"
"strings"
"testing"
"entgo.io/ent/dialect"
entsql "entgo.io/ent/dialect/sql"
"github.com/DATA-DOG/go-sqlmock"
dbent "github.com/Wei-Shaw/sub2api/ent"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/stretchr/testify/require"
)
func TestScopedAdminPermissionFieldClassification(t *testing.T) {
for _, tc := range []struct {
body string
want []string
}{
{`{"extra":{"email":"test@example.com","openai_oauth_responses_websockets_v2_enabled":false,"openai_oauth_responses_websockets_v2_mode":"off","openai_long_context_billing_enabled":false}}`, []string{"accounts.options.write"}},
{`{"rate_multiplier":0.5}`, []string{"accounts.rate.write"}},
{`{"credentials":{"expires_at":2000000000,"email":"test@example.com","plan_type":"plus"}}`, []string{"accounts.credentials", "accounts.credentials", "accounts.credentials"}},
} {
var fields map[string]json.RawMessage
require.NoError(t, json.Unmarshal([]byte(tc.body), &fields))
got, err := scopedAccountFieldPermissions(fields, true)
require.NoError(t, err)
require.ElementsMatch(t, tc.want, got)
}
}
func TestScopedAdminPermissionRejectsUnlistedOptions(t *testing.T) {
for _, body := range []string{`{"extra":{"codex_7d_used_percent":100}}`, `{"extra":{"openai_timezone_mode":"fixed"}}`, `{"extra":{"secret":"x"}}`, `{"extra":{"openai_long_context_billing_enabled":null}}`, `{"extra":{"openai_oauth_responses_websockets_v2_mode":null}}`, `{"rate_multiplier":-1}`, `{"rate_multiplier":null}`} {
var fields map[string]json.RawMessage
require.NoError(t, json.Unmarshal([]byte(body), &fields))
_, err := scopedAccountFieldPermissions(fields, true)
require.Error(t, err, body)
}
}
type scopedPermissionsCapacityGroups struct{ groupCapacityGroupRepoStub }
func (*scopedPermissionsCapacityGroups) ListScopedAdminCapacityGroupIDs(context.Context) ([]int64, error) {
return []int64{2}, nil
}
func TestScopedAdminPermissionCapacityScopesBeforeAggregation(t *testing.T) {
groups := &scopedPermissionsCapacityGroups{groupCapacityGroupRepoStub{groupIDs: []int64{1, 2, 3}}}
accounts := &groupCapacityAccountRepoStub{}
svc := NewGroupCapacityService(accounts, groups, nil, nil, nil)
ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{})
result, err := svc.GetAllGroupCapacity(ctx)
require.NoError(t, err)
require.Equal(t, []int64{2}, accounts.requested)
require.Equal(t, []GroupCapacitySummary{{GroupID: 2}}, result)
require.Zero(t, groups.listCalls)
svc.groupRepo = &groupCapacityGroupRepoStub{}
_, err = svc.GetAllGroupCapacity(ctx)
require.Error(t, err)
}
type scopedPermissionCreationRepo struct{ AccountRepository }
func (*scopedPermissionCreationRepo) Create(_ context.Context, a *Account) error {
a.ID = 1
return nil
}
func TestScopedAdminPermissionCreateAuthorizesEveryField(t *testing.T) {
permissions := []string{"accounts.create", "accounts.credentials", "accounts.options.write", "accounts.rate.write", "accounts.schedule"}
for _, missing := range append([]string{""}, permissions...) {
t.Run(missing, func(t *testing.T) {
db, mock, err := sqlmock.New()
require.NoError(t, err)
defer db.Close()
if missing == "" {
mock.ExpectBegin()
mock.ExpectCommit()
}
svc := &adminServiceImpl{accountRepo: &scopedPermissionCreationRepo{}, entClient: dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))}
granted := []string{}
for _, permission := range permissions {
if permission != missing {
granted = append(granted, permission)
}
}
ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: granted, IncludeUngrouped: true, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}})
var fields map[string]json.RawMessage
require.NoError(t, json.Unmarshal([]byte(`{"name":"授权创建","platform":"openai","type":"oauth","group_ids":[],"credentials":{"access_token":"test","refresh_token":"test","expires_at":2000000000,"email":"test@example.com","plan_type":"plus"},"extra":{"email":"test@example.com","openai_oauth_responses_websockets_v2_enabled":false,"openai_oauth_responses_websockets_v2_mode":"off","openai_long_context_billing_enabled":false},"rate_multiplier":0.5,"concurrency":20,"priority":1,"expires_at":null,"auto_pause_on_expired":true}`), &fields))
a, err := svc.ScopedAdminWrite(ctx, 0, "", fields, nil)
if missing != "" {
require.Equal(t, 403, infraerrors.Code(err))
} else {
require.NoError(t, err)
require.Equal(t, 0.5, *a.RateMultiplier)
require.Equal(t, "test@example.com", a.Credentials["email"])
require.Equal(t, "test@example.com", a.Extra["email"])
require.NotContains(t, a.Extra, "privacy_mode")
}
require.NoError(t, mock.ExpectationsWereMet())
})
}
}
type scopedPrivacyCreationRepo struct {
scopedPermissionCreationRepo
capturedExtra map[string]any
capturedSkip bool
capturedPrivacySet bool
}
func (r *scopedPrivacyCreationRepo) Create(ctx context.Context, a *Account) error {
r.capturedExtra = map[string]any{}
for key, value := range a.Extra {
r.capturedExtra[key] = value
}
r.capturedSkip = shouldSkipOpenAIPrivacyEnsure(a.Extra)
r.capturedPrivacySet = a.IsPrivacySet()
return r.scopedPermissionCreationRepo.Create(ctx, a)
}
func TestScopedAdminPrivacyCompatibilityIgnoresCallerStateBeforeCreate(t *testing.T) {
for _, mode := range []string{"training_off", "training_disabled", "training_set_failed", "unknown", ""} {
t.Run(mode, func(t *testing.T) {
db, mock, err := sqlmock.New()
require.NoError(t, err)
defer db.Close()
mock.ExpectBegin()
mock.ExpectCommit()
repo := &scopedPrivacyCreationRepo{}
svc := &adminServiceImpl{accountRepo: repo, entClient: dbent.NewClient(dbent.Driver(entsql.OpenDB(dialect.Postgres, db)))}
ctx := adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"accounts.create", "accounts.credentials", "accounts.options.write"}, IncludeUngrouped: true, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}})
var fields map[string]json.RawMessage
require.NoError(t, json.Unmarshal([]byte(`{"name":"兼容隐私入参","platform":"openai","type":"oauth","group_ids":[],"credentials":{"access_token":"test"}}`), &fields))
fields["extra"], err = json.Marshal(map[string]any{"privacy_mode": mode, "email": "test@example.com"})
require.NoError(t, err)
account, err := svc.ScopedAdminWrite(ctx, 0, "", fields, nil)
require.NoError(t, err)
require.Equal(t, "test@example.com", repo.capturedExtra["email"])
require.NotContains(t, repo.capturedExtra, "privacy_mode", "持久化前必须删除隐私状态键,空字符串同样不能残留")
require.False(t, repo.capturedSkip, "调用方隐私值不能阻止服务端 Ensure")
require.False(t, repo.capturedPrivacySet)
require.NotContains(t, account.Extra, "privacy_mode")
require.False(t, account.IsPrivacySet())
require.NoError(t, mock.ExpectationsWereMet())
})
}
}
func TestScopedAdminPrivacyCompatibilityRejectsInvalidTypes(t *testing.T) {
for _, value := range []string{`null`, `true`, `1`, `[]`, `{}`, `"` + strings.Repeat("x", 513) + `"`} {
var fields map[string]json.RawMessage
require.NoError(t, json.Unmarshal([]byte(`{"extra":{"privacy_mode":`+value+`}}`), &fields))
_, err := scopedAccountFieldPermissions(fields, true)
require.Equal(t, 400, infraerrors.Code(err), value)
}
}
@@ -0,0 +1,56 @@
package service
import (
"context"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
)
type scopedAccountOperationKey struct{}
// WithScopedAdminAccountOperation 仅供已完成动作验权的处理器传递同一操作的后续查询。
// 例如重置后的额度刷新仍属于重置操作,不要求额外授予读取权限。
func WithScopedAdminAccountOperation(ctx context.Context, action string) context.Context {
return context.WithValue(ctx, scopedAccountOperationKey{}, action)
}
func scopedAccountOperation(ctx context.Context, fallback string) string {
if action, ok := ctx.Value(scopedAccountOperationKey{}).(string); ok && action != "" {
return action
}
return fallback
}
func scopedAccountAccess(ctx context.Context, repo AccountRepository, a *Account, action string, parent bool) error {
p := adminaccess.RestrictedFromContext(ctx)
if p == nil {
return nil
}
denied := func() error { return infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在") }
if a == nil || !p.Policy.AllowsAccount(action, scopedAccountResource(a)) {
return denied()
}
if parent && a.IsShadow() {
if repo == nil || a.ParentAccountID == nil || *a.ParentAccountID == a.ID {
return denied()
}
source, err := repo.GetByID(ctx, *a.ParentAccountID)
if err != nil || source == nil || source.IsShadow() || !p.Policy.AllowsAccount(action, scopedAccountResource(source)) {
return denied()
}
}
return nil
}
func scopedAccountIDAccess(ctx context.Context, repo AccountRepository, id int64, action string, parent bool) error {
if adminaccess.RestrictedFromContext(ctx) == nil {
return nil
}
if repo == nil {
return infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在")
}
a, err := repo.GetByID(ctx, id)
if err != nil {
return infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在")
}
return scopedAccountAccess(ctx, repo, a, action, parent)
}
@@ -0,0 +1,295 @@
//go:build unit
package service
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/synctest"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
httppool "github.com/Wei-Shaw/sub2api/internal/pkg/httpclient"
"github.com/Wei-Shaw/sub2api/internal/pkg/usagestats"
"github.com/stretchr/testify/require"
)
func scopedStatisticsServiceContext(action string) context.Context {
return adminaccess.WithPrincipal(context.Background(), &adminaccess.Principal{Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{action}, GroupIDs: []int64{1}, AccountTypes: []string{"oauth"}, Platforms: []string{"openai"}}}}})
}
func TestScopedAdminUsageServiceRechecksScopeBeforeSnapshot(t *testing.T) {
a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{2}, Extra: map[string]any{"codex_5h_used_percent": 25.0}}
repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}
svc := &AccountUsageService{accountRepo: repo}
u, err := svc.getUsageForAccount(scopedStatisticsServiceContext("accounts.usage.read"), a, false)
require.Nil(t, u)
require.Equal(t, 404, infraerrors.Code(err))
}
func TestScopedAdminReferralServiceChecksScopeBeforeResolvingParent(t *testing.T) {
parentID := int64(2)
shadow := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}, ParentAccountID: &parentID}
parent := &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{2}}
svc := &OpenAIQuotaService{accountRepo: &stubQuotaAccountRepo{accounts: map[int64]*Account{1: shadow, 2: parent}}}
a, err := svc.referralAccount(scopedStatisticsServiceContext("openai.referrals.read"), 1, false)
require.Nil(t, a)
require.Equal(t, 404, infraerrors.Code(err))
}
func TestScopedAdminQuotaCacheWriteRechecksScope(t *testing.T) {
a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{2}}
repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}
svc := &OpenAIQuotaService{accountRepo: repo}
err := svc.CacheCreditsSnapshot(scopedStatisticsServiceContext("openai.quota.read"), 1, &OpenAIQuotaUsage{})
require.Equal(t, 404, infraerrors.Code(err))
require.Zero(t, repo.extraUpdateCalls)
}
type scopedUsageRecoveryRepo struct {
stubQuotaAccountRepo
clears int
}
func (r *scopedUsageRecoveryRepo) ClearError(context.Context, int64) error { r.clears++; return nil }
func TestScopedAdminUsageReadDoesNotRecoverAccount(t *testing.T) {
for _, platform := range []string{PlatformGemini, PlatformAnthropic} {
t.Run(platform, func(t *testing.T) {
a := &Account{ID: 1, Platform: platform, Type: AccountTypeOAuth, GroupIDs: []int64{1}, Status: StatusError, ErrorMessage: "unauthenticated", Credentials: map[string]any{"access_token": "token", "scope": "user:profile"}}
repo := &scopedUsageRecoveryRepo{stubQuotaAccountRepo: stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}}
cache := NewUsageCache()
cache.apiCache.Store(int64(1), &apiUsageCache{response: &ClaudeUsageResponse{}, timestamp: time.Now()})
svc := &AccountUsageService{accountRepo: repo, usageLogRepo: &usageBatchLogRepoStub{}, cache: cache}
ctx := scopedStatisticsServiceContext("accounts.usage.read")
adminaccess.FromContext(ctx).Policy.Rules[0].Platforms = []string{platform}
_, err := svc.getUsageForAccount(ctx, a, false)
require.NoError(t, err)
require.Zero(t, repo.clears)
require.Equal(t, StatusError, a.Status)
})
}
}
type scopedStatisticsBatchRepo struct{ stubQuotaAccountRepo }
func (r *scopedStatisticsBatchRepo) GetByIDs(ctx context.Context, ids []int64) ([]*Account, error) {
out := []*Account{}
for _, id := range ids {
a, err := r.GetByID(ctx, id)
if err != nil {
continue
}
out = append(out, a)
}
return out, nil
}
type scopedStatisticsLogRepo struct {
usageBatchLogRepoStub
reads int
}
func (r *scopedStatisticsLogRepo) GetAccountTodayStats(context.Context, int64) (*usagestats.AccountStats, error) {
r.reads++
return &usagestats.AccountStats{Cost: 23}, nil
}
func (r *scopedStatisticsLogRepo) GetAccountWindowStats(context.Context, int64, time.Time) (*usagestats.AccountStats, error) {
r.reads++
return &usagestats.AccountStats{Cost: 23}, nil
}
func TestScopedAdminBatchRejectsWholeRequestBeforeData(t *testing.T) {
for _, action := range []string{"accounts.usage.read", "accounts.stats.read"} {
for _, id := range []int64{2, 3} {
t.Run(fmt.Sprintf("%s/id=%d", action, id), func(t *testing.T) {
repo := &scopedStatisticsBatchRepo{stubQuotaAccountRepo: stubQuotaAccountRepo{accounts: map[int64]*Account{1: {ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}}, 2: {ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{2}}}}}
logs := &scopedStatisticsLogRepo{}
svc := &AccountUsageService{accountRepo: repo, usageLogRepo: logs, cache: NewUsageCache()}
ctx := scopedStatisticsServiceContext(action)
var err error
if action == "accounts.usage.read" {
_, _, err = svc.GetUsageBatch(ctx, []int64{1, id}, true)
} else {
_, err = svc.GetTodayStatsBatch(ctx, []int64{1, id})
}
require.Equal(t, 404, infraerrors.Code(err))
require.Zero(t, logs.reads)
require.Zero(t, repo.extraUpdateCalls)
})
}
}
}
func TestScopedAdminSnapshotWriteDoesNotNotifyAutomaticReset(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}}
repo := &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}
svc := &AccountUsageService{accountRepo: repo}
notifier := NewOpenAIQuotaAutoResetService(nil, nil, nil, nil, nil, nil, nil)
openAIAutoResetNotifierRegistry.Lock()
previous := openAIAutoResetNotifierRegistry.service
openAIAutoResetNotifierRegistry.service = notifier
openAIAutoResetNotifierRegistry.Unlock()
defer func() {
openAIAutoResetNotifierRegistry.Lock()
openAIAutoResetNotifierRegistry.service = previous
openAIAutoResetNotifierRegistry.Unlock()
notifier.cancel()
}()
svc.persistOpenAICodexProbeSnapshotContext(scopedStatisticsServiceContext("accounts.usage.read"), 1, map[string]any{"codex_5h_used_percent": 25.0})
synctest.Wait()
require.Equal(t, 1, repo.extraUpdateCalls)
require.Empty(t, notifier.queue)
})
}
func TestScopedAdminQuotaHeaderReloadRechecksScope(t *testing.T) {
a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{2}}
svc := &OpenAIQuotaService{accountRepo: &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}}
headers, _, err := svc.buildCodexQuotaHeaders(scopedStatisticsServiceContext("openai.quota.read"), 1, "token", "upstream-id", false)
require.Nil(t, headers)
require.Equal(t, 404, infraerrors.Code(err))
}
func TestScopedAdminGrokQuotaReloadRechecksScope(t *testing.T) {
a := &Account{ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth, GroupIDs: []int64{2}}
svc := &GrokQuotaService{accountRepo: &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}}
ctx := scopedStatisticsServiceContext("accounts.usage.read")
adminaccess.FromContext(ctx).Policy.Rules[0].Platforms = []string{PlatformGrok}
account, err := svc.loadGrokOAuthAccount(ctx, 1)
require.Nil(t, account)
require.Equal(t, 404, infraerrors.Code(err))
}
func TestScopedAdminGrokBillingChecksScopeBeforeJoiningFlight(t *testing.T) {
a := &Account{ID: 1, Platform: PlatformGrok, Type: AccountTypeOAuth, GroupIDs: []int64{2}}
svc := &GrokQuotaService{accountRepo: &stubQuotaAccountRepo{accounts: map[int64]*Account{1: a}}}
ctx := scopedStatisticsServiceContext("accounts.usage.read")
adminaccess.FromContext(ctx).Policy.Rules[0].Platforms = []string{PlatformGrok}
result, err := svc.ProbeBilling(ctx, 1)
require.Nil(t, result)
require.Equal(t, 404, infraerrors.Code(err))
}
func TestScopedAdminGrokSharedFlightPreservesPrincipal(t *testing.T) {
svc := &GrokQuotaService{}
ctx := scopedStatisticsServiceContext("accounts.usage.read")
_, err := svc.runProbeFlight(ctx, "context", func(shared context.Context) (*GrokQuotaProbeResult, error) {
if adminaccess.FromContext(ctx) != adminaccess.FromContext(shared) {
return nil, fmt.Errorf("共享任务丢失授权身份")
}
return &GrokQuotaProbeResult{}, nil
})
require.NoError(t, err)
}
type scopedQuotaParentDisappears struct {
AccountRepository
shadow, parent *Account
parentReads int
}
func (r *scopedQuotaParentDisappears) GetByID(_ context.Context, id int64) (*Account, error) {
if id == r.shadow.ID {
return r.shadow, nil
}
r.parentReads++
if r.parentReads == 1 {
return r.parent, nil
}
return nil, fmt.Errorf("母账户读取失败")
}
func TestScopedAdminQuotaHeaderParentResolveFailureFailsClosed(t *testing.T) {
parentID := int64(2)
repo := &scopedQuotaParentDisappears{shadow: &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}, ParentAccountID: &parentID}, parent: &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}}}
svc := &OpenAIQuotaService{accountRepo: repo}
headers, _, err := svc.buildCodexQuotaHeaders(scopedStatisticsServiceContext("openai.quota.read"), 1, "old-token", "old-account-id", false)
require.Nil(t, headers)
require.Equal(t, 404, infraerrors.Code(err))
}
type scopedUsageRoundTripper func(*http.Request) (*http.Response, error)
func (f scopedUsageRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func TestScopedAdminOpenAIUsageRefreshNeverGeneratesModelRequests(t *testing.T) {
for _, tc := range []struct {
name string
restricted, shadow, full bool
wantModel int
wantUsage float64
}{
{"受限普通账户", true, false, false, 0, 37}, {"受限影子账户", true, true, false, 0, 67},
{"JWT普通账户", false, false, false, 1, 98}, {"全权密钥普通账户", false, false, true, 1, 98},
} {
t.Run(tc.name, func(t *testing.T) {
parentID := int64(2)
a := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}, Credentials: map[string]any{"access_token": "test-token", "chatgpt_account_id": "test-account"}}
parent := &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth, GroupIDs: []int64{1}, Credentials: a.Credentials}
if tc.shadow {
a.ParentAccountID = &parentID
a.QuotaDimension = QuotaDimensionSpark
}
updates := make(chan map[string]any, 1)
repo := &sparkShadowUsageTestRepo{accounts: map[int64]*Account{1: a, 2: parent}, updateExtraCh: updates}
var quotaCalls, nonReadCalls int
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
nonReadCalls++
}
if strings.HasSuffix(r.URL.Path, "/usage") {
quotaCalls++
}
w.Header().Set("Content-Type", "application/json")
if !strings.HasSuffix(r.URL.Path, "/usage") {
_, _ = w.Write([]byte(`[]`))
return
}
_, _ = w.Write([]byte(`{"rate_limit":{"primary_window":{"used_percent":37,"limit_window_seconds":18000,"reset_after_seconds":3600}},"additional_rate_limits":[{"metered_feature":"codex_bengalfox","rate_limit":{"primary_window":{"used_percent":67,"limit_window_seconds":18000,"reset_after_seconds":3600}}}],"rate_limit_reset_credits":{"available_count":0}}`))
}))
defer upstream.Close()
quota := NewOpenAIQuotaService(repo, nil, NewOpenAITokenProvider(repo, nil, nil), newQuotaRedirectingFactory(upstream), nil)
client, err := httppool.GetClient(httppool.Options{Timeout: 15 * time.Second, ResponseHeaderTimeout: 10 * time.Second})
require.NoError(t, err)
previous := client.Transport
defer func() { client.Transport = previous }()
modelCalls := 0
client.Transport = scopedUsageRoundTripper(func(r *http.Request) (*http.Response, error) {
modelCalls++
headers := make(http.Header)
headers.Set("x-codex-primary-used-percent", "98")
headers.Set("x-codex-primary-window-minutes", "300")
headers.Set("x-codex-primary-reset-after-seconds", "3600")
return &http.Response{StatusCode: 200, Header: headers, Body: io.NopCloser(strings.NewReader(""))}, nil
})
svc := &AccountUsageService{accountRepo: repo, openAIQuotaService: quota, cache: NewUsageCache()}
ctx := context.Background()
if tc.restricted {
ctx = scopedStatisticsServiceContext("accounts.usage.read")
}
if tc.full {
ctx = adminaccess.WithPrincipal(ctx, &adminaccess.Principal{Policy: adminaccess.Policy{FullAccess: true}})
}
usage, err := svc.GetUsageForAccount(ctx, a, true)
require.NoError(t, err)
require.Equal(t, tc.wantModel, modelCalls, "读取额度不能合成模型消费请求")
if tc.restricted {
require.Equal(t, 1, quotaCalls)
require.Zero(t, nonReadCalls)
} else {
require.Zero(t, quotaCalls)
}
require.NotNil(t, usage.FiveHour)
require.Equal(t, tc.wantUsage, usage.FiveHour.Utilization)
select {
case <-updates:
case <-time.After(time.Second):
t.Fatal("展示快照未写入")
}
})
}
}
+28 -15
View File
@@ -20,24 +20,27 @@ var ErrScopedAdminKeyConflict = infraerrors.Conflict("ADMIN_KEY_CONFLICT", "密
var ErrScopedAdminKeyNotFound = infraerrors.NotFound("ADMIN_KEY_NOT_FOUND", "Admin key not found")
type ScopedAdminKeyInput struct {
Name string `json:"name"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
ExpiresAt *time.Time `json:"expires_at"`
AllowedIPs []string `json:"allowed_ips"`
Policy adminaccess.Policy `json:"policy"`
ConfirmFullAccess bool `json:"confirm_full_access,omitempty"`
Name string `json:"name"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
ExpiresAt *time.Time `json:"expires_at"`
AllowedIPs []string `json:"allowed_ips"`
Policy adminaccess.Policy `json:"policy"`
}
type ScopedAdminKey struct {
ScopedAdminKeyInput
ID string `json:"id"`
KeyPrefix string `json:"key_prefix"`
Hash string `json:"-"`
CreatedBy int64 `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastUsedAt *time.Time `json:"last_used_at"`
LastUsedIP string `json:"last_used_ip"`
RevokedAt *time.Time `json:"revoked_at"`
PreviousFullAccess bool `json:"-"`
ExpectedUpdatedAt time.Time `json:"-"`
ID string `json:"id"`
KeyPrefix string `json:"key_prefix"`
Hash string `json:"-"`
CreatedBy int64 `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastUsedAt *time.Time `json:"last_used_at"`
LastUsedIP string `json:"last_used_ip"`
RevokedAt *time.Time `json:"revoked_at"`
}
type ScopedAdminKeyRepository interface {
ListScopedAdminKeys(context.Context) ([]*ScopedAdminKey, error)
@@ -126,6 +129,10 @@ func (s *SettingService) ListScopedAdminKeys(ctx context.Context) ([]*ScopedAdmi
return r.ListScopedAdminKeys(ctx)
}
func (s *SettingService) CreateScopedAdminKey(ctx context.Context, in ScopedAdminKeyInput, creator int64) (string, *ScopedAdminKey, error) {
if in.Policy.FullAccess && !in.ConfirmFullAccess {
return "", nil, infraerrors.BadRequest("ADMIN_KEY_FULL_ACCESS_CONFIRMATION_REQUIRED", "开启全权访问需要显式确认")
}
in.ConfirmFullAccess = false
if e := validateScopedAdminKeyInput(&in); e != nil {
return "", nil, e
}
@@ -161,9 +168,15 @@ func (s *SettingService) UpdateScopedAdminKey(ctx context.Context, id string, in
if item.RevokedAt != nil {
return nil, ErrScopedAdminKeyNotFound
}
if in.Policy.FullAccess && !item.Policy.FullAccess && !in.ConfirmFullAccess {
return nil, infraerrors.BadRequest("ADMIN_KEY_FULL_ACCESS_CONFIRMATION_REQUIRED", "开启全权访问需要显式确认")
}
in.ConfirmFullAccess = false
if e := validateScopedAdminKeyInputForUpdate(&in, item.ExpiresAt); e != nil {
return nil, e
}
item.PreviousFullAccess = item.Policy.FullAccess
item.ExpectedUpdatedAt = item.UpdatedAt
item.ScopedAdminKeyInput = in
item.UpdatedAt = time.Now().UTC()
if e = r.UpdateScopedAdminKey(ctx, item); e != nil {
+10 -1
View File
@@ -244,6 +244,12 @@ func (s *GrokQuotaService) probeUsage(ctx context.Context, accountID int64) (*Gr
// ProbeBilling only calls the xAI billing endpoints. Account usage refreshes
// use this method so opening the account list never consumes model quota.
func (s *GrokQuotaService) ProbeBilling(ctx context.Context, accountID int64) (*GrokQuotaProbeResult, error) {
// 每个调用者在加入共享查询前独立验权,不能继承任务发起者的范围。
if s != nil {
if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, "accounts.usage.read", false); err != nil {
return nil, err
}
}
return s.runProbeFlight(ctx, "billing:"+strconv.FormatInt(accountID, 10), func(sharedCtx context.Context) (*GrokQuotaProbeResult, error) {
return s.probeBilling(sharedCtx, accountID)
})
@@ -353,7 +359,7 @@ func (s *GrokQuotaService) runProbeFlight(
return nil, infraerrors.New(http.StatusInternalServerError, "GROK_QUOTA_NOT_CONFIGURED", "grok quota service is not configured")
}
resultCh := s.probeFlight.DoChan(key, func() (any, error) {
sharedCtx, cancel := context.WithTimeout(context.Background(), grokQuotaUpstreamTimeout+5*time.Second)
sharedCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), grokQuotaUpstreamTimeout+5*time.Second)
defer cancel()
return probe(sharedCtx)
})
@@ -544,6 +550,9 @@ func (s *GrokQuotaService) loadGrokOAuthAccount(ctx context.Context, accountID i
if account == nil {
return nil, infraerrors.New(http.StatusNotFound, "GROK_QUOTA_ACCOUNT_NOT_FOUND", "account not found")
}
if err := scopedAccountAccess(ctx, s.accountRepo, account, "accounts.usage.read", false); err != nil {
return nil, err
}
if account.Platform != PlatformGrok {
return nil, infraerrors.New(http.StatusBadRequest, "GROK_QUOTA_INVALID_PLATFORM", "account is not a Grok account")
}
@@ -2,6 +2,8 @@ package service
import (
"context"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"time"
)
@@ -77,6 +79,15 @@ func (s *GroupCapacityService) GetAllGroupCapacity(ctx context.Context) ([]Group
}
func (s *GroupCapacityService) listActiveGroupIDs(ctx context.Context) ([]int64, error) {
if adminaccess.RestrictedFromContext(ctx) != nil {
if repo, ok := s.groupRepo.(interface {
ListScopedAdminCapacityGroupIDs(context.Context) ([]int64, error)
}); ok {
return repo.ListScopedAdminCapacityGroupIDs(ctx)
}
return nil, infraerrors.ServiceUnavailable("SCOPED_GROUP_CAPACITY_UNAVAILABLE", "受限分组容量服务不可用")
}
if lister, ok := s.groupRepo.(groupCapacityActiveGroupIDLister); ok {
return lister.ListActiveIDs(ctx)
}
@@ -11,6 +11,7 @@ import (
"sync"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/adminaccess"
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
"github.com/imroc/req/v3"
)
@@ -252,6 +253,9 @@ func (s *OpenAIQuotaService) CacheResetCreditsSnapshot(ctx context.Context, acco
// of reset-credit expiration details. A successful read with absent credits
// replaces the previous balance with unknown, never with a fabricated zero.
func (s *OpenAIQuotaService) CacheCreditsSnapshot(ctx context.Context, accountID int64, usage *OpenAIQuotaUsage) error {
if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, scopedAccountOperation(ctx, "openai.quota.read"), true); err != nil {
return err
}
if usage == nil {
return infraerrors.New(http.StatusBadGateway, "OPENAI_QUOTA_EMPTY_USAGE", "openai quota query returned an empty result")
}
@@ -265,6 +269,9 @@ func (s *OpenAIQuotaService) CacheCreditsSnapshot(ctx context.Context, accountID
// CachePostResetSnapshot persists the credits and usage windows observed after a reset.
func (s *OpenAIQuotaService) CachePostResetSnapshot(ctx context.Context, accountID int64, usage *OpenAIQuotaUsage) error {
if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, scopedAccountOperation(ctx, "openai.quota.reset"), true); err != nil {
return err
}
if usage == nil {
return s.cacheResetCreditsSnapshot(ctx, accountID, nil, nil)
}
@@ -282,6 +289,9 @@ func (s *OpenAIQuotaService) CachePostResetSnapshot(ctx context.Context, account
}
func (s *OpenAIQuotaService) cacheResetCreditsSnapshot(ctx context.Context, accountID int64, credits *OpenAIRateLimitResetCredits, updates map[string]any) error {
if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, scopedAccountOperation(ctx, "openai.quota.read"), true); err != nil {
return err
}
if credits == nil || (credits.AvailableCount > 0 && len(credits.Credits) == 0) {
return infraerrors.New(
http.StatusBadGateway,
@@ -358,6 +368,10 @@ func (s *OpenAIQuotaService) ResetCreditTargeted(ctx context.Context, accountID
}
func (s *OpenAIQuotaService) resetCredit(ctx context.Context, accountID int64, creditID, redeemRequestID string, targeted bool) (*OpenAIQuotaResetResult, error) {
ctx = WithScopedAdminAccountOperation(ctx, "openai.quota.reset")
if err := scopedAccountIDAccess(ctx, s.accountRepo, accountID, "openai.quota.reset", false); err != nil {
return nil, err
}
// Shadow guard: resetting credits via a shadow account would silently
// operate on the parent's quota; that is surprising and unwanted. Callers
// must reset the parent account directly.
@@ -453,6 +467,9 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID
if account == nil {
return "", "", "", false, infraerrors.New(http.StatusNotFound, "OPENAI_QUOTA_ACCOUNT_NOT_FOUND", "account not found")
}
if err := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), true); err != nil {
return "", "", "", false, err
}
if account.Platform != PlatformOpenAI {
return "", "", "", false, infraerrors.New(http.StatusBadRequest, "OPENAI_QUOTA_INVALID_PLATFORM", "account is not an OpenAI account")
}
@@ -469,6 +486,9 @@ func (s *OpenAIQuotaService) prepareUpstreamCall(ctx context.Context, accountID
return "", "", "", false, infraerrors.Newf(http.StatusBadGateway, "OPENAI_QUOTA_SHADOW_RESOLVE_FAILED", "failed to resolve shadow account: %v", rerr)
}
account = resolved
if err := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), false); err != nil {
return "", "", "", false, err
}
}
chatGPTAccountID = strings.TrimSpace(account.GetCredential("chatgpt_account_id"))
@@ -521,12 +541,18 @@ func (s *OpenAIQuotaService) recoverAgentIdentityTask(ctx context.Context, accou
if err != nil || account == nil {
return fmt.Errorf("account is unavailable")
}
if scopeErr := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), true); scopeErr != nil {
return scopeErr
}
if account.IsShadow() {
account, err = resolveCredentialAccount(ctx, s.accountRepo, account)
if err != nil || account == nil {
return fmt.Errorf("credential account is unavailable")
}
}
if scopeErr := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), false); scopeErr != nil {
return scopeErr
}
if !account.IsOpenAIAgentIdentity() {
return nil
}
@@ -553,10 +579,19 @@ func (s *OpenAIQuotaService) isAgentIdentityAccount(ctx context.Context, account
func (s *OpenAIQuotaService) buildCodexQuotaHeaders(ctx context.Context, accountID int64, accessToken, chatGPTAccountID string, fedRAMP bool) (map[string]string, string, error) {
headers := buildCodexCommonHeaders(accessToken, chatGPTAccountID, fedRAMP)
if s == nil || s.accountRepo == nil {
if adminaccess.RestrictedFromContext(ctx) != nil {
return nil, "", infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在")
}
return headers, "", nil
}
account, err := s.accountRepo.GetByID(ctx, accountID)
if scopeErr := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), true); scopeErr != nil {
return nil, "", scopeErr
}
if err != nil || account == nil {
if adminaccess.RestrictedFromContext(ctx) != nil {
return nil, "", infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在")
}
if strings.TrimSpace(accessToken) == "" {
return nil, "", fmt.Errorf("agent identity account credentials are unavailable")
}
@@ -565,6 +600,11 @@ func (s *OpenAIQuotaService) buildCodexQuotaHeaders(ctx context.Context, account
if account.IsShadow() {
if resolved, resolveErr := resolveCredentialAccount(ctx, s.accountRepo, account); resolveErr == nil && resolved != nil {
account = resolved
if scopeErr := scopedAccountAccess(ctx, s.accountRepo, account, scopedAccountOperation(ctx, "openai.quota.read"), false); scopeErr != nil {
return nil, "", scopeErr
}
} else if adminaccess.RestrictedFromContext(ctx) != nil {
return nil, "", infraerrors.NotFound("SCOPED_ACCOUNT_NOT_FOUND", "账户不存在")
} else if strings.TrimSpace(accessToken) == "" {
return nil, "", fmt.Errorf("agent identity shadow credentials are unavailable")
}
@@ -68,6 +68,13 @@ func (s *OpenAIQuotaService) referralAccount(ctx context.Context, id int64, send
if a == nil {
return nil, ErrAccountNotFound
}
action := scopedAccountOperation(ctx, "openai.referrals.read")
if sending {
action = "openai.referrals.invite"
}
if err := scopedAccountAccess(ctx, s.accountRepo, a, action, !sending); err != nil {
return nil, err
}
if a.Platform != PlatformOpenAI || a.Type != AccountTypeOAuth {
return nil, infraerrors.New(http.StatusBadRequest, "OPENAI_REFERRAL_INVALID_ACCOUNT", "referrals require an OpenAI OAuth account")
}
@@ -75,7 +82,14 @@ func (s *OpenAIQuotaService) referralAccount(ctx context.Context, id int64, send
if sending {
return nil, infraerrors.New(http.StatusConflict, "OPENAI_REFERRAL_SHADOW_ACCOUNT", "send invitations from the parent account")
}
return resolveCredentialAccount(ctx, s.accountRepo, a)
resolved, err := resolveCredentialAccount(ctx, s.accountRepo, a)
if err != nil {
return nil, err
}
if err := scopedAccountAccess(ctx, s.accountRepo, resolved, action, false); err != nil {
return nil, err
}
return resolved, nil
}
return a, nil
}
@@ -108,6 +122,7 @@ func (s *OpenAIQuotaService) referralCall(ctx context.Context, id int64, program
}
func (s *OpenAIQuotaService) QueryReferralEligibility(ctx context.Context, id int64) (*OpenAIReferralEligibility, error) {
ctx = WithScopedAdminAccountOperation(ctx, scopedAccountOperation(ctx, "openai.referrals.read"))
account, err := s.referralAccount(ctx, id, false)
if err != nil {
return nil, err
@@ -130,6 +145,9 @@ func (s *OpenAIQuotaService) QueryReferralEligibility(ctx context.Context, id in
}
func (s *OpenAIQuotaService) CacheReferralSnapshot(ctx context.Context, id int64, eligibility *OpenAIReferralEligibility) error {
if err := scopedAccountIDAccess(ctx, s.accountRepo, id, scopedAccountOperation(ctx, "openai.referrals.read"), true); err != nil {
return err
}
return s.accountRepo.UpdateExtra(ctx, id, map[string]any{openAIReferralSnapshotKey: eligibility})
}
@@ -145,6 +163,7 @@ type OpenAIReferralSendResult struct {
}
func (s *OpenAIQuotaService) SendReferralInvite(ctx context.Context, id int64, input OpenAIReferralSendRequest) (*OpenAIReferralSendResult, error) {
ctx = WithScopedAdminAccountOperation(ctx, "openai.referrals.invite")
email := strings.TrimSpace(input.Email)
address, err := mail.ParseAddress(email)
if err != nil || address.Address != email || len(email) > 254 || strings.ContainsAny(email, "\r\n") {
+39 -3
View File
@@ -1,6 +1,6 @@
# 受限管理员 API 密钥
# 管理员 API 密钥
受限管理员密钥用于自动化管理指定资源。它与调用模型使用的用户 API Key 不同,也不等同于管理员登录会话。通过请求头 `x-api-key` 使用;只有权限目录明确登记的接口和操作才会开放,新增接口不会自动继承权限。
受限管理员密钥用于自动化管理指定资源。它与调用模型使用的用户 API Key 不同,也不等同于管理员登录会话。通过请求头 `x-api-key` 使用。默认采用受限模式:只有权限目录明确登记的接口和操作才会开放,新增接口不会自动继承权限。确需旧版完整管理能力时,可显式开启下述全权兼容模式。
## 创建与配置
@@ -12,7 +12,43 @@
创建、更新、停用/启用、轮换、撤销和删除记录均沿用系统二次验证流程;是否弹出验证由系统的 step-up 配置和当前授权状态决定。密钥生命周期接口只接受管理员 JWT 会话,受限密钥不能管理自身或创建其他管理员密钥。
已有旧版全权密钥时,页面显示兼容折叠区,可轮换或删除。页面不再提供新建旧版全权密钥的入口;应将自动化任务迁移到受限密钥。
已有旧版全权密钥时,页面显示兼容折叠区,可轮换或删除。页面不再提供新建旧版单一密钥的入口;新密钥可选择受限模式或需确认的全权兼容模式。
## 全权兼容模式
每枚密钥可单独开启「全权访问(兼容旧版管理员 Key)」,默认关闭。开启前弹窗说明影响,必须输入确认文字;取消不会改变授权。关闭后恢复原资源规则,启用全权期间这些规则只保留配置、不参与限制。
- 全权模式使用原管理处理器及完整响应,可访问全部管理资源和未来新增的管理接口,包括敏感数据、账户及财务配置。它不是普通权限目录的「全选」。
- `policy.full_access` 控制模式。创建全权密钥或从受限切换到全权时,请求必须显式携带 `confirm_full_access: true`;服务端检查确认,确认值不保存为授权。
- 密钥管理接口始终只接受管理员 JWT 会话。系统启用 step-up 时,要求二次验证的接口继续拒绝机器密钥;全权模式不会绕过这些要求,也不替代模型调用使用的用户 API Key。
- 有效期、来源 IP、启停、轮换、永久撤销、按 Key 限流及审计继续生效。审计包含全权状态,模式修改记录变更前后状态。
- 并发编辑可能返回 `ADMIN_KEY_CONFLICT`,应重新读取当前配置后编辑,不要盲目覆盖。相同幂等键跨密钥或授权策略重用会冲突,不能重放其他权限下的结果或重复执行财务操作。
## 自动化查询与操作权限
以下账户权限均放在资源规则中,按同一规则的分组、账户类型和平台校验;分组权限只按分组和平台校验。升级不会给已有密钥自动增加这些权限。
| 权限 | 用途 |
| --- | --- |
| `accounts.identity.read` | 账户邮箱、套餐、订阅到期及创建时间;列表/详情仍需 `accounts.read` |
| `accounts.usage.read` | 单个及批量账户额度查询、主动刷新,以及列表/详情中的周额度快照 |
| `accounts.stats.read` | 单个/批量今日统计与历史统计,包含请求数、Token 和费用 |
| `accounts.options.write` | 创建 OpenAI OAuth 账户时写入已列明的身份和连接选项 |
| `accounts.rate.write` | 创建/修改账户计费倍率 |
| `groups.list.read` | 所选分组的 ID、名称、平台与状态,不含费率或模型配置 |
| `groups.capacity.read` | 所选启用分组的容量;统计整个分组,不按账户类型裁剪 |
| `openai.quota.read` | OpenAI 额度、点数及重置次数查询和展示快照刷新 |
| `openai.quota.reset` | 执行 OpenAI 上游额度重置,可能消耗可用次数 |
| `openai.referrals.read` | 查询邀请资格与名额并刷新展示快照 |
| `openai.referrals.invite` | 实际发送邀请;不由邀请查询权限附带授予 |
`openai.tokens.refresh` 是独立的**全站权限**:仅刷新调用方提交的 OpenAI 令牌并返回新令牌,不读取服务器已有账户凭证。指定代理必须存在、启用且未过期;无效代理不会静默回退为直连。它与 `accounts.refresh`(刷新已保存的授权账户凭证)不同。
账户列表接受 `group` 筛选,省略或 `group=` 表示不指定分组,`-1` 表示未分组;筛选不会扩大授权范围。分页返回 `items/total/page/page_size/pages`。周额度是当前快照(`codex_usage_updated_at`、`codex_7d_used_percent`、`codex_7d_reset_at`),不是历史事件记录;缺失不伪装为零用量。
批量查询一次接受 1 至 100 个账户 ID,先验证所有账户范围,再读取统计、缓存或访问上游。混入未授权账户时整批拒绝。受限 OpenAI 额度刷新只调用额度查询接口,不发送模型探测请求。只读额度权限不授权消耗重置次数、发送邀请或恢复账户状态及调度。影子账户借用母账户凭证时,母账户也必须有对应操作权限。重置或发送邀请后的响应仍分别检查额度或邀请读取权限,身份信息另行验权;响应不会返回完整凭证、任意 `extra` 或原始上游错误。
`accounts.options.write` 仅开放创建 OpenAI OAuth 账户时的 `extra.email`、`openai_oauth_responses_websockets_v2_mode`、`openai_oauth_responses_websockets_v2_enabled` 和 `openai_long_context_billing_enabled`,不能任意写入 `extra`、额度快照、影子关系或声明隐私设置成功。为兼容已有客户端,字符串 `privacy_mode` 入参会被移除,隐私状态仍由服务端原流程确认。创建倍率独立需要 `accounts.rate.write`,写入凭证及身份元数据仍遵循对应凭证权限。
## 账户规则如何匹配
+2 -1
View File
@@ -8,9 +8,10 @@ export interface AccessRule {
account_types: string[]
platforms: string[]
}
export interface AccessPolicy { rules: AccessRule[]; global_permissions: string[] }
export interface AccessPolicy { full_access?: boolean; rules: AccessRule[]; global_permissions: string[] }
export interface Permission { id: string; label: string; category: string; scope: 'account' | 'group' | 'global' }
export interface AdminKeyInput {
confirm_full_access?: boolean
name: string
description: string
enabled: boolean
@@ -21,6 +21,7 @@
<p class="text-sm text-gray-500">{{ item.description || t('adminAccessKeys.noDescription') }} · {{ t('adminAccessKeys.expires', { value: item.expires_at || t('adminAccessKeys.never') }) }}</p>
<p class="text-sm text-gray-500">{{ t('adminAccessKeys.lastUsed', { value: item.last_used_at || t('adminAccessKeys.neverUsed') }) }} {{ item.last_used_ip }}</p>
<div class="space-y-1 text-sm text-gray-500" :aria-label="t('adminAccessKeys.summaryLabel')">
<p v-if="item.policy.full_access" class="font-semibold text-red-600">{{ t('adminAccessKeys.fullAccessLabel') }}</p>
<p>{{ t('adminAccessKeys.summary', { globals: item.policy.global_permissions.length, rules: item.policy.rules.length }) }}</p>
<p v-for="(rule, index) in item.policy.rules" :key="index">{{ t('adminAccessKeys.ruleLine', { index: index + 1, summary: ruleSummary(rule) }) }}</p>
</div>
@@ -41,6 +42,12 @@
<label class="block">{{ t('adminAccessKeys.expiration') }}<input v-model="expiration" type="datetime-local" class="input mt-1" /></label>
<label class="block">{{ t('adminAccessKeys.allowedIps') }}<textarea v-model="ips" class="input mt-1" placeholder="192.0.2.1&#10;2001:db8::/32" /></label>
<label class="flex gap-2"><input v-model="draft.enabled" type="checkbox" />{{ t('adminAccessKeys.enabled') }}</label>
<div class="space-y-2 rounded-lg border border-red-300 p-3">
<label class="flex gap-2"><input data-test="full-access" type="checkbox" :checked="draft.policy.full_access || fullAccessPrompt" :disabled="busy" @change="changeFullAccess" />{{ t('adminAccessKeys.fullAccessLabel') }}</label>
<p class="text-sm text-red-700 dark:text-red-300">{{ t('adminAccessKeys.fullAccessWarning') }}</p>
<p v-if="draft.policy.full_access" class="text-sm">{{ t('adminAccessKeys.rulesSuspended') }}</p>
</div>
<fieldset :disabled="busy || !!draft.policy.full_access" class="space-y-4">
<fieldset v-for="(rule, index) in draft.policy.rules" :key="index" class="space-y-3 rounded-lg border border-gray-200 p-3 dark:border-dark-700">
<legend>{{ t('adminAccessKeys.ruleLegend', { index: index + 1 }) }}</legend>
<label class="flex gap-2"><input v-model="rule.all_groups" type="checkbox" />{{ t('adminAccessKeys.allGroups') }}</label>
@@ -64,8 +71,17 @@
<label v-for="permission in category.permissions" :key="permission.id" class="flex gap-2"><input v-model="draft.policy.global_permissions" type="checkbox" :value="permission.id" />{{ permission.label }} <span class="text-xs text-gray-500">{{ permission.id }}</span></label>
</fieldset>
</fieldset>
<div class="flex gap-2"><button type="button" data-test="save" class="btn btn-primary" :disabled="busy" @click="save">{{ busy ? t('adminAccessKeys.processing') : t('adminAccessKeys.save') }}</button><button type="button" class="btn btn-secondary" :disabled="busy" @click="draft = null">{{ t('adminAccessKeys.cancel') }}</button></div>
</fieldset>
<div class="flex gap-2"><button type="button" data-test="save" class="btn btn-primary" :disabled="busy || fullAccessPrompt" @click="save">{{ busy ? t('adminAccessKeys.processing') : t('adminAccessKeys.save') }}</button><button type="button" class="btn btn-secondary" :disabled="busy" @click="draft = null">{{ t('adminAccessKeys.cancel') }}</button></div>
</div>
<BaseDialog :show="fullAccessPrompt" :title="t('adminAccessKeys.fullAccessConfirmTitle')" width="normal" @close="cancelFullAccess">
<p class="text-red-700 dark:text-red-300">{{ t('adminAccessKeys.fullAccessWarning') }}</p>
<label class="mt-4 block">{{ t('adminAccessKeys.fullAccessPhraseHint', { phrase: t('adminAccessKeys.fullAccessPhrase') }) }}<input v-model="fullAccessPhrase" data-test="full-access-phrase" class="input mt-1" autocomplete="off" /></label>
<template #footer>
<button type="button" data-test="full-access-cancel" class="btn btn-secondary" @click="cancelFullAccess">{{ t('adminAccessKeys.cancel') }}</button>
<button type="button" data-test="full-access-confirm" class="btn btn-danger" :disabled="fullAccessPhrase !== t('adminAccessKeys.fullAccessPhrase')" @click="confirmFullAccess">{{ t('adminAccessKeys.fullAccessConfirmTitle') }}</button>
</template>
</BaseDialog>
<TotpStepUpDialog :controller="stepUp" />
</section>
</template>
@@ -77,6 +93,7 @@ import * as api from '@/api/admin/adminAccessKeys'
import type { AccessRule, AdminKey, AdminKeyInput, Permission } from '@/api/admin/adminAccessKeys'
import { getAllIncludingInactive } from '@/api/admin/groups'
import { CONCRETE_PLATFORM_OPTIONS } from '@/constants/platforms'
import BaseDialog from '@/components/common/BaseDialog.vue'
import TotpStepUpDialog from '@/components/auth/TotpStepUpDialog.vue'
import { isStepUpCancelled, useStepUp } from '@/composables/useStepUp'
@@ -96,6 +113,9 @@ const editingID = ref('')
const expiration = ref('')
const initialExpiration = ref('')
const ips = ref('')
const fullAccessPrompt = ref(false)
const fullAccessPhrase = ref('')
const fullAccessConfirmed = ref(false)
const accountTypes = ['oauth', 'setup-token', 'apikey', 'upstream', 'bedrock', 'service_account']
const accountPermissions = computed(() => permissions.value.filter(p => p.scope === 'account'))
const groupPermissions = computed(() => permissions.value.filter(p => p.scope === 'group'))
@@ -110,6 +130,7 @@ const globalCategories = computed(() => {
// Go 的空切片可能序列化为 null;统一为空数组且不增加任何授权。
function normalizeItem(item: AdminKey): AdminKey {
return { ...item, allowed_ips: item.allowed_ips ?? [], policy: {
full_access: item.policy?.full_access ?? false,
global_permissions: item.policy?.global_permissions ?? [],
rules: (item.policy?.rules ?? []).map(rule => ({ ...rule,
permissions: rule.permissions ?? [], group_ids: rule.group_ids ?? [],
@@ -139,6 +160,8 @@ async function load() {
}
function edit(item?: AdminKey) {
error.value = ''; notice.value = ''; secret.value = ''
cancelFullAccess()
fullAccessConfirmed.value = false
editingID.value = item?.id || ''
draft.value = item ? JSON.parse(JSON.stringify({ name: item.name, description: item.description, enabled: item.enabled, expires_at: item.expires_at, allowed_ips: item.allowed_ips, policy: item.policy })) : { name: '', description: '', enabled: true, expires_at: null, allowed_ips: [], policy: { rules: [emptyRule()], global_permissions: [] } }
const date = item?.expires_at ? new Date(item.expires_at) : null
@@ -146,17 +169,38 @@ function edit(item?: AdminKey) {
initialExpiration.value = expiration.value
ips.value = item?.allowed_ips.join('\n') || ''
}
function changeFullAccess(event: Event) {
if (!draft.value || busy.value) return
if ((event.target as HTMLInputElement).checked) {
fullAccessPhrase.value = ''
fullAccessPrompt.value = true
} else {
draft.value.policy.full_access = false
fullAccessConfirmed.value = false
}
}
function cancelFullAccess() {
fullAccessPrompt.value = false
fullAccessPhrase.value = ''
}
function confirmFullAccess() {
if (!draft.value || fullAccessPhrase.value !== t('adminAccessKeys.fullAccessPhrase')) return
draft.value.policy.full_access = true
fullAccessConfirmed.value = true
cancelFullAccess()
}
async function mutate(action: () => Promise<void>) {
busy.value = true; error.value = ''; notice.value = ''; secret.value = ''
try { await stepUp.run(action) } catch (e) { report(e) } finally { busy.value = false }
}
function replace(item: AdminKey) { items.value = [normalizeItem(item), ...items.value.filter(key => key.id !== item.id)] }
async function save() {
if (!draft.value) return
if (!draft.value || busy.value || fullAccessPrompt.value) return
if (!draft.value.name.trim()) { error.value = t('adminAccessKeys.nameRequired'); return }
const date = expiration.value ? new Date(expiration.value) : null
if (date && !Number.isFinite(date.getTime())) { error.value = t('adminAccessKeys.expirationInvalid'); return }
const input: AdminKeyInput = JSON.parse(JSON.stringify(draft.value))
input.confirm_full_access = !!input.policy.full_access && fullAccessConfirmed.value
input.name = input.name.trim()
// 未修改日期时保留服务端原值,避免丢失秒数、微秒或时区精度。
if (expiration.value !== initialExpiration.value) input.expires_at = date?.toISOString() || null
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import AdminAccessKeysSettings from '../AdminAccessKeysSettings.vue'
import zh from '@/i18n/locales/zh/adminAccessKeys'
import en from '@/i18n/locales/en/adminAccessKeys'
const mountSettings = () => mount(AdminAccessKeysSettings)
const mountSettings = () => mount(AdminAccessKeysSettings, { global: { stubs: { teleport: true } } })
vi.mock('vue-i18n', () => ({ useI18n: () => ({
t: (key: string, values: Record<string, unknown> = {}) => {
const message = zh[key.replace('adminAccessKeys.', '') as keyof typeof zh]
@@ -184,7 +184,7 @@ describe('管理员受限密钥配置', () => {
expect(wrapper.text()).not.toContain('kiro')
await wrapper.get('[data-test="save"]').trigger('click')
await flushPromises()
expect(mocks.update).toHaveBeenCalledWith('key-2', expect.objectContaining({ name: '新名称', allowed_ips: [], policy: { rules, global_permissions: [] } }))
expect(mocks.update).toHaveBeenCalledWith('key-2', expect.objectContaining({ name: '新名称', allowed_ips: [], policy: { rules, global_permissions: [], full_access: false } }))
})
it('空数组返回 null 时仍可创建默认无权限密钥', async () => {
mocks.list.mockResolvedValueOnce({ items: null, permissions: null })
@@ -245,3 +245,78 @@ describe('管理员受限密钥配置', () => {
})
})
describe('全权兼容模式', () => {
it('默认关闭,取消不会授权,输入确认文字后才允许保存全权', async () => {
mocks.create.mockResolvedValue({ key: 'once', item: { id: '1' } })
const wrapper = mountSettings()
await flushPromises()
await wrapper.get('[data-test="create"]').trigger('click')
await wrapper.get('[data-test="name"]').setValue('兼容工具')
const toggle = wrapper.get<HTMLInputElement>('[data-test="full-access"]')
expect(toggle.element.checked).toBe(false)
await toggle.setValue(true)
expect(wrapper.get('[data-test="full-access-confirm"]').attributes('disabled')).toBeDefined()
await wrapper.get('[data-test="full-access-cancel"]').trigger('click')
expect(toggle.element.checked).toBe(false)
await toggle.setValue(true)
await wrapper.get('[data-test="full-access-phrase"]').setValue('开启全权访问')
await wrapper.get('[data-test="full-access-confirm"]').trigger('click')
expect(wrapper.text()).toContain('资源规则已暂停')
await wrapper.get('[data-test="save"]').trigger('click')
await flushPromises()
expect(mocks.create.mock.calls[0]![0]).toMatchObject({ policy: { full_access: true }, confirm_full_access: true })
})
it('关闭后保留原规则,并清除确认状态', async () => {
const item = { id: 'key-1', name: '兼容', enabled: true, allowed_ips: [], policy: { full_access: true, rules: [{ permissions: ['accounts.read'], group_ids: [7], account_types: ['oauth'], platforms: ['openai'] }], global_permissions: [] } }
mocks.list.mockResolvedValueOnce({ items: [item], permissions: [] })
mocks.update.mockResolvedValueOnce(item)
const wrapper = mountSettings()
await flushPromises()
expect(wrapper.text()).toContain('全权访问')
await wrapper.findAll('button').find(b => b.text() === '编辑权限')!.trigger('click')
const toggle = wrapper.get<HTMLInputElement>('[data-test="full-access"]')
expect(toggle.element.checked).toBe(true)
await toggle.setValue(false)
await wrapper.get('[data-test="save"]').trigger('click')
await flushPromises()
const input = mocks.update.mock.calls[0]![1]
expect(input.policy.full_access).toBe(false)
expect(input.policy.rules[0].permissions).toEqual(['accounts.read'])
expect(input.confirm_full_access).not.toBe(true)
})
})
describe('全权确认失败与重复开启', () => {
it('取消确认仍可保存受限配置,不能借确认弹窗直接保存', async () => {
mocks.create.mockResolvedValue({ key: 'once', item: { id: '1' } })
const wrapper = mountSettings()
await flushPromises()
await wrapper.get('[data-test="create"]').trigger('click')
await wrapper.get('[data-test="name"]').setValue('受限工具')
await wrapper.get('[data-test="full-access"]').setValue(true)
expect(wrapper.get('[data-test="save"]').attributes('disabled')).toBeDefined()
await wrapper.get('[data-test="save"]').trigger('click')
expect(mocks.create).not.toHaveBeenCalled()
await wrapper.get('[data-test="full-access-cancel"]').trigger('click')
await wrapper.get('[data-test="save"]').trigger('click')
await flushPromises()
expect(mocks.create.mock.calls[0]![0].policy.full_access).not.toBe(true)
expect(mocks.create.mock.calls[0]![0].confirm_full_access).toBe(false)
})
it('关闭后再次开启需要重新输入确认文字', async () => {
const wrapper = mountSettings()
await flushPromises()
await wrapper.get('[data-test="create"]').trigger('click')
await wrapper.get('[data-test="full-access"]').setValue(true)
await wrapper.get('[data-test="full-access-phrase"]').setValue('开启全权访问')
await wrapper.get('[data-test="full-access-confirm"]').trigger('click')
expect(wrapper.get('input[value="accounts.read"]').element.closest('fieldset[disabled]')).not.toBeNull()
await wrapper.get('[data-test="full-access"]').setValue(false)
await wrapper.get('[data-test="full-access"]').setValue(true)
expect(wrapper.get<HTMLInputElement>('[data-test="full-access-phrase"]').element.value).toBe('')
expect(wrapper.get('[data-test="full-access-confirm"]').attributes('disabled')).toBeDefined()
})
})
@@ -5,7 +5,7 @@ export default {
"secretWarning": "The full key is shown only once. Copy and save it before closing.",
"copySecret": "Copy key",
"dismissSecret": "Saved, close",
"create": "Create scoped key",
"create": "Create administrator key",
"refresh": "Refresh",
"loading": "Loading keys and permissions…",
"noDescription": "No description",
@@ -31,7 +31,7 @@ export default {
"accountTypes": "Account types (account operations only; none means no account access)",
"platforms": "Platforms (multiple selection; empty allows all)",
"accountOperations": "Allowed account operations",
"groupOperations": "Allowed group model operations (subject to the group and platform scopes above)",
"groupOperations": "Allowed group operations (restricted by the groups and platforms above)",
"modelAllowlistHint": "The group model allowlist restricts which models the group can use.",
"removeRule": "Remove rule",
"addRule": "Add resource rule",
@@ -69,5 +69,11 @@ export default {
"rotateConfirm": "Rotating “{name}” immediately invalidates its current key. Continue?",
"revokeConfirm": "Permanently revoking “{name}” cannot be undone. Continue?",
"deleteConfirm": "Delete the key record “{name}”? This removes it from the list only. Historical operation records are retained.",
"legacy": "Legacy full-access key (migration to scoped keys recommended)"
"legacy": "Legacy full-access key (migration to scoped keys recommended)",
"fullAccessLabel": "Full access (legacy administrator key compatibility)",
"fullAccessWarning": "This key can access all administrative resources, read sensitive data, and change account and financial settings, including future administrative endpoints. Group, platform, account type, and operation rules no longer restrict this key. Endpoints requiring an administrator browser session or step-up verification keep those requirements.",
"rulesSuspended": "Resource rules are suspended and resume when full access is disabled. Expiration, IP restrictions, rate limits, and auditing remain active.",
"fullAccessConfirmTitle": "Confirm full access",
"fullAccessPhrase": "ENABLE FULL ACCESS",
"fullAccessPhraseHint": "Type “{phrase}” to confirm:"
}
@@ -5,7 +5,7 @@ export default {
"secretWarning": "完整密钥仅展示本次,请立即复制保存。关闭后无法再次查看。",
"copySecret": "复制密钥",
"dismissSecret": "已保存,关闭展示",
"create": "创建受限密钥",
"create": "创建管理密钥",
"refresh": "刷新列表",
"loading": "正在加载密钥及权限目录…",
"noDescription": "无备注",
@@ -31,7 +31,7 @@ export default {
"accountTypes": "账户类型(仅限制账户操作,未选表示无账户权限)",
"platforms": "平台(可多选,未选表示不限平台)",
"accountOperations": "允许的账户操作",
"groupOperations": "允许的分组模型操作(同样受上方分组与平台限制)",
"groupOperations": "允许的分组操作(受上方分组与平台限制)",
"modelAllowlistHint": "分组模型白名单会限制分组可调用的模型。",
"removeRule": "删除规则",
"addRule": "添加资源规则",
@@ -69,5 +69,11 @@ export default {
"rotateConfirm": "轮换“{name}”将立即使原密钥失效,是否继续?",
"revokeConfirm": "永久撤销“{name}”后无法恢复,是否继续?",
"deleteConfirm": "确定删除“{name}”的密钥记录?删除只是从列表移除,历史操作记录仍会继续保留。",
"legacy": "旧版全权密钥兼容区(建议迁移到受限密钥)"
"legacy": "旧版全权密钥兼容区(建议迁移到受限密钥)",
"fullAccessLabel": "全权访问(兼容旧版管理员 Key)",
"fullAccessWarning": "开启后,此密钥可访问全部管理资源、读取敏感数据并修改账户和财务配置;未来新增的管理接口也将允许访问。分组、平台、账户类型和操作规则不再限制此密钥。仅限管理员登录会话及二次验证的接口仍遵循原要求。",
"rulesSuspended": "资源规则已暂停,关闭全权访问后恢复;有效期、IP 限制、限流和审计继续生效。",
"fullAccessConfirmTitle": "确认开启全权访问",
"fullAccessPhrase": "开启全权访问",
"fullAccessPhraseHint": "请输入“{phrase}”以确认:"
}