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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion backend/internal/app/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,9 +300,13 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
selector := gateway.NewSelector(accountRepo, concurrency, sticky, providers, cfg.Routing.StickyTTL.Value(), cfg.Routing.CooldownBase.Value(), cfg.Routing.CooldownMax.Value(), cfg.Routing.CapacityWait.Value())
selector.UpdatePreferFreeBuild(cfg.Routing.PreferFreeBuild)
selector.UpdateSegmentedSelector(cfg.Routing.SegmentedSelectorEnabled, cfg.Routing.SegmentedMinCandidates, cfg.Routing.SegmentedWindowSize)
invalidationService := invalidationapp.NewService(invalidationBus, invalidationSourceInstance(cfg), selector.ApplyInvalidation, logger)
invalidationService := invalidationapp.NewService(invalidationBus, invalidationSourceInstance(cfg), func(event repository.InvalidationEvent) {
selector.ApplyInvalidation(event)
clientKeyService.ApplyInvalidation(event)
}, logger)
accountRepo.SetInvalidationObserver(invalidationService.Notify)
modelRepo.SetInvalidationObserver(invalidationService.Notify)
clientKeyRepo.SetInvalidationObserver(invalidationService.Notify)
gatewayService := gateway.NewService(modelService, auditService, accountService, clientKeyService, providers, selector, responseRepo, cfg.Routing.MaxAttempts)
gatewayService.SetLogger(logger)
gatewayService.UpdateBuildForbiddenReauthPolicy(cfg.Accounts.MarkBuildForbiddenReauth, cfg.Accounts.BuildForbiddenReauthCodes)
Expand Down
6 changes: 6 additions & 0 deletions backend/internal/application/clientkey/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ func (c *authKeyCache) deleteIDs(ids []uint64) {
}
}

func (c *authKeyCache) clear() {
c.mu.Lock()
clear(c.byPrefix)
c.mu.Unlock()
}

// touchTracker 合并非关键的最近使用时间写入。
type touchTracker struct {
mu sync.Mutex
Expand Down
47 changes: 38 additions & 9 deletions backend/internal/application/clientkey/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ type CreateInput struct {
BillingLimitUSDTicks int64
AllowModelAliases bool
AllowedModels []uint64
ProviderScope clientkeydomain.ProviderScope
TierScope clientkeydomain.TierScope
}

type UpdateInput struct {
Expand All @@ -53,6 +55,8 @@ type UpdateInput struct {
BillingLimitUSDTicks *int64
AllowModelAliases *bool
AllowedModels *[]uint64
ProviderScope *clientkeydomain.ProviderScope
TierScope *clientkeydomain.TierScope
}

type Created struct {
Expand Down Expand Up @@ -97,6 +101,19 @@ func (s *Service) UpdateDefaults(defaultRPM, defaultMax int) {
s.defaultMax.Store(int64(defaultMax))
}

// ApplyInvalidation removes cached authorization policy after a local or remote
// client-key mutation. A zero ID represents a batch-wide invalidation.
func (s *Service) ApplyInvalidation(event repository.InvalidationEvent) {
if event.Kind != repository.InvalidationClientKeyChanged {
return
}
if event.ClientKeyID == 0 {
s.authCache.clear()
return
}
s.authCache.deleteID(event.ClientKeyID)
}

func (s *Service) List(ctx context.Context, page, pageSize int, search string, filter ListFilter) ([]clientkeydomain.Key, int64, error) {
page, pageSize = normalizePage(page, pageSize)
if !validListFilter(filter.Status, "", "active", "disabled", "expired") || !validListFilter(filter.ModelScope, "", "all", "restricted") || !repository.IsValidSort(filter.Sort, "name", "prefix", "status", "rpmLimit", "maxConcurrent", "billingLimit", "expiresAt", "lastUsedAt") {
Expand Down Expand Up @@ -131,6 +148,11 @@ func (s *Service) Create(ctx context.Context, input CreateInput) (Created, error
if input.BillingLimitUSDTicks < 0 || input.BillingLimitUSDTicks > clientkeydomain.MaxBillingLimitTicks {
return Created{}, invalidInput("billingLimitUsdTicks 超出允许范围")
}
providerScope, providerScopeValid := clientkeydomain.NormalizeProviderScope(input.ProviderScope)
tierScope, tierScopeValid := clientkeydomain.NormalizeTierScope(input.TierScope)
if !providerScopeValid || !tierScopeValid {
return Created{}, invalidInput("providerScope 或 tierScope 无效")
}
prefix, err := security.NewHexToken(6)
if err != nil {
return Created{}, err
Expand Down Expand Up @@ -164,6 +186,7 @@ func (s *Service) Create(ctx context.Context, input CreateInput) (Created, error
Name: strings.TrimSpace(input.Name), Prefix: prefix, SecretHash: security.HashToken(raw), EncryptedSecret: encryptedSecret,
Enabled: input.Enabled, ExpiresAt: input.ExpiresAt, RPMLimit: input.RPMLimit, MaxConcurrent: input.MaxConcurrent,
BillingLimitUSDTicks: input.BillingLimitUSDTicks, AllowModelAliases: input.AllowModelAliases, AllowedModels: input.AllowedModels,
ProviderScope: providerScope, TierScope: tierScope,
})
return Created{Key: value, Secret: raw}, mapRepositoryError(err)
}
Expand Down Expand Up @@ -231,6 +254,20 @@ func (s *Service) Update(ctx context.Context, id uint64, input UpdateInput) (cli
if input.AllowedModels != nil {
value.AllowedModels = *input.AllowedModels
}
if input.ProviderScope != nil {
providerScope, valid := clientkeydomain.NormalizeProviderScope(*input.ProviderScope)
if !valid {
return clientkeydomain.Key{}, invalidInput("providerScope 无效")
}
value.ProviderScope = providerScope
}
if input.TierScope != nil {
tierScope, valid := clientkeydomain.NormalizeTierScope(*input.TierScope)
if !valid {
return clientkeydomain.Key{}, invalidInput("tierScope 无效")
}
value.TierScope = tierScope
}
updated, err := s.keys.Update(ctx, value)
if err == nil {
s.authCache.deleteID(id)
Expand Down Expand Up @@ -336,15 +373,7 @@ func (s *Service) Authenticate(ctx context.Context, raw string) (clientkeydomain

// CanUseModel 判断空权限列表代表全部模型,否则要求显式授权。
func (s *Service) CanUseModel(value clientkeydomain.Key, modelID uint64) bool {
if len(value.AllowedModels) == 0 {
return true
}
for _, allowed := range value.AllowedModels {
if allowed == modelID {
return true
}
}
return false
return value.AllowsModel(modelID)
}

// ReserveBilling 为有限额 Key 原子预留本次请求的预计费用。
Expand Down
80 changes: 80 additions & 0 deletions backend/internal/application/clientkey/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,86 @@ func TestAuthenticateCachesUnlimitedKeyAndInvalidatesOnDisable(t *testing.T) {
}
}

func TestAccountScopePersistsAndAuthCacheInvalidatesOnChange(t *testing.T) {
ctx := context.Background()
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "account-pool-auth-cache.db"))
if err != nil {
t.Fatal(err)
}
defer database.Close()
if err := database.InitializeSchema(ctx); err != nil {
t.Fatal(err)
}
base := relational.NewClientKeyRepository(database)
service := NewService(base, successfulRateLimiter{}, successfulConcurrencyLimiter{}, 60, 5, testCipher(t))
created, err := service.Create(ctx, CreateInput{Name: "scoped", Enabled: true, ProviderScope: clientkeydomain.ProviderScopeBuild | clientkeydomain.ProviderScopeWeb, TierScope: clientkeydomain.TierScopeFree})
if err != nil {
t.Fatal(err)
}
value, release, err := service.Authenticate(ctx, created.Secret)
if err != nil {
t.Fatal(err)
}
release()
if value.ProviderScope != clientkeydomain.ProviderScopeBuild|clientkeydomain.ProviderScopeWeb || value.TierScope != clientkeydomain.TierScopeFree {
t.Fatalf("authenticated account scope = %+v", value.AccountScope())
}
consoleScope := clientkeydomain.ProviderScopeConsole
superTier := clientkeydomain.TierScopeSuper
if _, err := service.Update(ctx, created.Key.ID, UpdateInput{ProviderScope: &consoleScope, TierScope: &superTier}); err != nil {
t.Fatal(err)
}
value, release, err = service.Authenticate(ctx, created.Secret)
if err != nil {
t.Fatal(err)
}
release()
if value.ProviderScope != clientkeydomain.ProviderScopeConsole || value.TierScope != clientkeydomain.TierScopeSuper {
t.Fatalf("account scope after cache invalidation = %+v", value.AccountScope())
}
stored, err := base.Get(ctx, created.Key.ID)
if err != nil {
t.Fatal(err)
}
stored.ProviderScope = clientkeydomain.ProviderScopeWeb
stored.TierScope = clientkeydomain.TierScopeFree
if _, err := base.Update(ctx, stored); err != nil {
t.Fatal(err)
}
value, release, err = service.Authenticate(ctx, created.Secret)
if err != nil {
t.Fatal(err)
}
release()
if value.ProviderScope != clientkeydomain.ProviderScopeConsole || value.TierScope != clientkeydomain.TierScopeSuper {
t.Fatalf("cache unexpectedly changed before remote invalidation = %+v", value.AccountScope())
}
service.ApplyInvalidation(repository.InvalidationEvent{Kind: repository.InvalidationClientKeyChanged, ClientKeyID: created.Key.ID})
value, release, err = service.Authenticate(ctx, created.Secret)
if err != nil {
t.Fatal(err)
}
release()
if value.ProviderScope != clientkeydomain.ProviderScopeWeb || value.TierScope != clientkeydomain.TierScopeFree {
t.Fatalf("account scope after remote invalidation = %+v", value.AccountScope())
}
service.ApplyInvalidation(repository.InvalidationEvent{Kind: repository.InvalidationClientKeyChanged})
service.authCache.mu.RLock()
cacheEntries := len(service.authCache.byPrefix)
service.authCache.mu.RUnlock()
if cacheEntries != 0 {
t.Fatalf("batch invalidation retained %d auth cache entries", cacheEntries)
}
invalid := clientkeydomain.ProviderScope(8)
if _, err := service.Update(ctx, created.Key.ID, UpdateInput{ProviderScope: &invalid}); !errors.Is(err, ErrInvalidInput) {
t.Fatalf("invalid account scope error = %v", err)
}
all, err := service.Create(ctx, CreateInput{Name: "legacy-default", Enabled: true})
if err != nil || all.Key.ProviderScope != clientkeydomain.ProviderScopeAll || all.Key.TierScope != clientkeydomain.TierScopeAll {
t.Fatalf("default account scope = %+v, err = %v", all.Key.AccountScope(), err)
}
}

func testCipher(t *testing.T) *security.Cipher {
t.Helper()
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
Expand Down
10 changes: 8 additions & 2 deletions backend/internal/application/gateway/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gateway

import (
"context"
"errors"
"fmt"
"net/http"
"sync"
Expand Down Expand Up @@ -173,9 +174,14 @@ func (s *Service) executeImage(
var lastCredentialFailure *accountdomain.Credential
var lastCredentialError error
for attempt := 0; attemptPolicy.allows(attempt); attempt++ {
lease, err = s.selector.Acquire(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false)
lease, err = s.selector.AcquireForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false, key.AccountScope())
if err != nil {
writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", lastCredentialFailure)
errorCode := "upstream_unavailable"
var selectionFailure *SelectionUnavailableError
if errors.As(err, &selectionFailure) {
errorCode = selectionFailure.Code()
}
writeFailureAudit(http.StatusServiceUnavailable, errorCode, lastCredentialFailure)
return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err)
}
excluded[lease.Credential.ID] = true
Expand Down
Loading
Loading