fix(ollama): validate the ollama cloud pricing gate on all account write paths

评审确认三条 admin 写路径绕过保存期无价门禁
(validateOllamaCloudAccountModelPricingGate),本修复把同一门禁与同一触发
收窄判定复用到这三条路径,不另写判定规则:

- BulkUpdateAccounts:对每个受影响的 ollama_cloud 账号,按仓库 BulkUpdate
  的实际生效方式(credentials/extra JSONB 顶层 key 合并、status/schedulable
  列覆盖)先算出「变更后的账号」再校验;任一账号不合规即整批拒绝、不落库,
  错误信息点名账号 ID/名称与未定价模型名,便于批量操作定位。
- DuplicateAccount:用「将要创建的账号」(深拷贝后的最终 credentials/extra)
  校验,不合规拒绝;复制产物保持暂停语义不变。
- SetAccountSchedulable:只在启用方向(当前不满足 active+Schedulable → true)
  且账号是 ollama_cloud 时校验,判定复用 ollamaCloudSchedulableBySave;停用
  放行。

定位说明:运行时模型白名单(IsModelSupported)与转发前定价预检已经落地,
即使绕过保存期门禁也不会再产生「成功但不计费」的流量(最坏是账号 deny-all
或对客户端返 400)。因此这是「门禁不可绕过」的一致性与运维反馈修复,不是
计费漏损修复。

非 ollama 平台行为不变:门禁短路 + 触发收窄(维护性更新放行)均有回归测试
覆盖(bulk 改名/停用、kimi 平台的同样操作全部放行)。
This commit is contained in:
alfadb committed 2026-09-13 10:38:56 +08:00
1 parent 5801d10b5f
commit f1afabb6a9
2 files changed
+355 -2

No files matched your search

@@ -392,3 +392,282 @@ func TestAdminUpdateAccountOllamaCloudPricingGateOnlyOnModelSetOrSchedulingChang
requireModelPricingMissing(t, err)
})
}
// ─────────────────────────────────────────────────────────────────────────────
// 评审收口回归:三条此前绕过门禁的 admin 写路径(BulkUpdateAccounts /
// DuplicateAccount / SetAccountSchedulable)。定位是「门禁不可绕过」的一致性——
// 运行时白名单与转发前定价预检已兜底最坏情形,本组测试锁的是保存期拦截行为
// 本身:不合规整批拒绝且不落库、错误点名账号、维护性更新与非 ollama 平台放行。
// ─────────────────────────────────────────────────────────────────────────────
// ollamaGateSchedulableCall 记录一次 SetSchedulable 调用,用于断言「拒绝时未触达 DB」。
type ollamaGateSchedulableCall struct {
accountID int64
schedulable bool
}
// ollamaGateAdminRepoStub 在 upstreamBillingProbeAccountRepo 之上补齐本组回归所需的
// 两个写入口:SetSchedulable(记录调用)与 CreateWithAccountGroups(复制路径的原子创建)。
type ollamaGateAdminRepoStub struct {
*upstreamBillingProbeAccountRepo
schedulableCalls []ollamaGateSchedulableCall
}
func newOllamaGateAdminRepoStub() *ollamaGateAdminRepoStub {
return &ollamaGateAdminRepoStub{
upstreamBillingProbeAccountRepo: &upstreamBillingProbeAccountRepo{accounts: make(map[int64]*Account)},
}
}
func (r *ollamaGateAdminRepoStub) SetSchedulable(_ context.Context, id int64, schedulable bool) error {
r.mu.Lock()
defer r.mu.Unlock()
if account := r.accounts[id]; account != nil {
account.Schedulable = schedulable
}
r.schedulableCalls = append(r.schedulableCalls, ollamaGateSchedulableCall{accountID: id, schedulable: schedulable})
return nil
}
func (r *ollamaGateAdminRepoStub) CreateWithAccountGroups(ctx context.Context, account *Account, _ []AccountGroup) error {
return r.Create(ctx, account)
}
// seedOllamaGateAccount 直接经 repo 落库一个账号(绕过 Create 路径门禁),
// 用于模拟「门禁上线前迁移过来的存量账号」。
func seedOllamaGateAccount(t *testing.T, repo *ollamaGateAdminRepoStub, mutate func(*Account)) *Account {
t.Helper()
account := &Account{
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Name: "ollama-gate-seed",
Status: StatusActive,
Schedulable: false,
Credentials: map[string]any{"api_key": "k"},
}
if mutate != nil {
mutate(account)
}
require.NoError(t, repo.Create(context.Background(), account))
return account
}
func TestAdminBulkUpdateAccountsOllamaCloudPricingGate(t *testing.T) {
ctx := context.Background()
newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) {
t.Helper()
repo := newOllamaGateAdminRepoStub()
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
return repo, svc
}
t.Run("bulk写入未定价mapping_整批拒绝点名账号且不落库", func(t *testing.T) {
repo, svc := newSvc(t)
first := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-a" })
second := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "ollama-bulk-b"
a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}}
})
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
AccountIDs: []int64{first.ID, second.ID},
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}},
})
requireModelPricingMissing(t, err, "totally-unpriced-model")
// 批量操作要能定位:错误信息必须点名每个不合规账号。
require.Contains(t, infraerrors.Message(err), first.Name)
require.Contains(t, infraerrors.Message(err), second.Name)
// 整批拒绝:任何账号都不得写入。
require.Empty(t, repo.bulkUpdates, "被拒绝的批量更新不得触达 DB")
})
t.Run("bulk写入已定价mapping_通过", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, nil)
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
AccountIDs: []int64{account.ID},
Credentials: map[string]any{"api_key": "k", "model_mapping": map[string]any{"big": "gpt-oss:120b"}},
})
require.NoError(t, err)
require.Len(t, repo.bulkUpdates, 1)
})
t.Run("bulk启用legacy无配置账号_拒绝且不落库", func(t *testing.T) {
repo, svc := newSvc(t)
first := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy-a" })
second := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy-b" })
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
AccountIDs: []int64{first.ID, second.ID},
Schedulable: boolPtr(true),
})
requireModelPricingMissing(t, err)
require.Contains(t, infraerrors.Message(err), first.Name)
require.Contains(t, infraerrors.Message(err), second.Name)
require.Empty(t, repo.bulkUpdates)
})
t.Run("bulk停用_放行", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "ollama-bulk-disable"
a.Schedulable = true
})
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
AccountIDs: []int64{account.ID},
Schedulable: boolPtr(false),
})
require.NoError(t, err, "停用(退出调度准入)属于维护性更新,不得被拦截")
require.Len(t, repo.bulkUpdates, 1)
})
t.Run("bulk仅改name_legacy账号放行", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-bulk-legacy" })
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
AccountIDs: []int64{account.ID},
Name: "ollama-bulk-legacy-renamed",
})
require.NoError(t, err, "维护性更新(仅改 name)不得被 MODEL_PRICING_MISSING 锁死")
require.Len(t, repo.bulkUpdates, 1)
})
t.Run("非ollama平台bulk不受影响_回归", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "kimi-bulk"
a.Platform = PlatformKimi
a.Schedulable = false
})
_, err := svc.BulkUpdateAccounts(ctx, &BulkUpdateAccountsInput{
AccountIDs: []int64{account.ID},
Credentials: map[string]any{
"api_key": "k",
"model_mapping": map[string]any{"k2": "totally-unpriced-model"},
},
Schedulable: boolPtr(true),
})
require.NoError(t, err, "非 ollama 平台的批量更新行为必须保持不变")
require.Len(t, repo.bulkUpdates, 1)
})
}
func TestAdminDuplicateAccountOllamaCloudPricingGate(t *testing.T) {
ctx := context.Background()
newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) {
t.Helper()
repo := newOllamaGateAdminRepoStub()
svc := &adminServiceImpl{accountRepo: repo, accountDuplicateRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
return repo, svc
}
t.Run("复制不合规账号_拒绝且不落库", func(t *testing.T) {
repo, svc := newSvc(t)
source := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "ollama-dup-bad"
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}
})
_, err := svc.DuplicateAccount(ctx, source.ID, "", "")
requireModelPricingMissing(t, err, "totally-unpriced-model")
require.Len(t, repo.accounts, 1, "被拒绝的复制不得落库")
})
t.Run("复制无配置legacy账号_拒绝", func(t *testing.T) {
repo, svc := newSvc(t)
source := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-dup-legacy" })
_, err := svc.DuplicateAccount(ctx, source.ID, "", "")
requireModelPricingMissing(t, err)
require.Len(t, repo.accounts, 1)
})
t.Run("复制已配置清单账号_通过且保持暂停", func(t *testing.T) {
repo, svc := newSvc(t)
source := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "ollama-dup-good"
a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}}
})
duplicate, err := svc.DuplicateAccount(ctx, source.ID, "", "")
require.NoError(t, err)
require.NotNil(t, duplicate)
require.Len(t, repo.accounts, 2)
require.False(t, duplicate.Schedulable, "复制产物必须保持暂停,等人工复核后再启用")
})
t.Run("非ollama平台复制不受影响_回归", func(t *testing.T) {
repo, svc := newSvc(t)
source := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "kimi-dup"
a.Platform = PlatformKimi
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "totally-unpriced-model"}}
})
duplicate, err := svc.DuplicateAccount(ctx, source.ID, "", "")
require.NoError(t, err, "非 ollama 平台的复制行为必须保持不变")
require.NotNil(t, duplicate)
require.Len(t, repo.accounts, 2)
})
}
func TestAdminSetAccountSchedulableOllamaCloudPricingGate(t *testing.T) {
ctx := context.Background()
newSvc := func(t *testing.T) (*ollamaGateAdminRepoStub, *adminServiceImpl) {
t.Helper()
repo := newOllamaGateAdminRepoStub()
svc := &adminServiceImpl{accountRepo: repo, billingService: NewBillingService(&config.Config{}, nil)}
return repo, svc
}
t.Run("启用无配置legacy账号_拒绝且不落库", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, func(a *Account) { a.Name = "ollama-enable-legacy" })
_, err := svc.SetAccountSchedulable(ctx, account.ID, true)
requireModelPricingMissing(t, err)
require.Empty(t, repo.schedulableCalls, "被拒绝的启用不得触达 DB")
})
t.Run("停用_放行", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "ollama-disable"
a.Schedulable = true
})
updated, err := svc.SetAccountSchedulable(ctx, account.ID, false)
require.NoError(t, err, "停用(true→false)属于维护性操作,不得被拦截")
require.NotNil(t, updated)
require.Len(t, repo.schedulableCalls, 1)
require.False(t, repo.schedulableCalls[0].schedulable)
})
t.Run("启用未定价mapping账号_拒绝", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "ollama-enable-unpriced"
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"alias": "totally-unpriced-model"}}
})
_, err := svc.SetAccountSchedulable(ctx, account.ID, true)
requireModelPricingMissing(t, err, "totally-unpriced-model")
require.Empty(t, repo.schedulableCalls)
})
t.Run("启用已定价账号_通过", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "ollama-enable-priced"
a.Extra = map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b-cloud"}}
})
updated, err := svc.SetAccountSchedulable(ctx, account.ID, true)
require.NoError(t, err)
require.NotNil(t, updated)
require.Len(t, repo.schedulableCalls, 1)
})
t.Run("非ollama平台启用不受影响_回归", func(t *testing.T) {
repo, svc := newSvc(t)
account := seedOllamaGateAccount(t, repo, func(a *Account) {
a.Name = "kimi-enable"
a.Platform = PlatformKimi
a.Credentials = map[string]any{"api_key": "k", "model_mapping": map[string]any{"k2": "totally-unpriced-model"}}
})
updated, err := svc.SetAccountSchedulable(ctx, account.ID, true)
require.NoError(t, err, "非 ollama 平台的手动启用行为必须保持不变")
require.NotNil(t, updated)
require.Len(t, repo.schedulableCalls, 1)
})
}
+76 -2
View File
@@ -332,6 +332,12 @@ func (s *adminServiceImpl) DuplicateAccount(ctx context.Context, id int64, actor
}
// A copied credential must be reviewed before it can share live traffic with its source.
duplicate.Schedulable = false
// B2-③ 保存期无价门禁:复制是创建路径的变体,产物与手工创建同样必须过门禁
// (评审收口)——否则不合规的存量账号可以被无限复制放大。用「将要创建的账号」
// 校验,credentials/extra 此时已是深拷贝后的最终形态。
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, duplicate); err != nil {
return nil, err
}
if s.accountDuplicateRepo == nil {
return nil, errors.New("account duplicate repository is not configured")
}
@@ -991,9 +997,11 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
needMixedChannelCheck := input.GroupIDs != nil && !input.SkipMixedChannelCheck
// 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查共用,避免多次 DB 查询。
// 预取所有目标账号,供凭据守卫/代理守卫/混合渠道检查/ollama_cloud 保存期门禁共用,
// 避免多次 DB 查询。ollama_cloud 门禁需要读到「变更后状态」(credentials/extra 合并、
// status/schedulable 切换),所以携带这些输入时也必须预取。
var cachedTargets []*Account
if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil {
if len(input.Credentials) > 0 || input.ProxyID != nil || needMixedChannelCheck || openAISettings.any() || input.ProbeEnabled != nil || input.RateMultiplier != nil || input.Schedulable != nil || input.Status != "" || len(input.Extra) > 0 {
loaded, err := s.accountRepo.GetByIDs(ctx, input.AccountIDs)
if err != nil {
return nil, err
@@ -1159,6 +1167,15 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
repoUpdates.Schedulable = input.Schedulable
}
// B2-③ 保存期无价门禁:批量路径同样不可绕过(评审收口)。先按仓库的同款合并
// 语义(JSONB 顶层 key 合并 + 列覆盖)算出每个受影响 ollama_cloud 账号「本次
// 请求生效后的状态」,再复用与单账号 UpdateAccount 相同的门禁与触发收窄判定。
// 任何账号不合规即整批拒绝、不落库,错误信息点名账号与未定价模型,便于批量
// 操作定位。
if err := s.validateOllamaCloudPricingGateForBulkUpdate(input.AccountIDs, targetsByID, repoUpdates); err != nil {
return nil, err
}
// Run bulk update for column/jsonb fields first.
if _, err := s.accountRepo.BulkUpdate(ctx, input.AccountIDs, repoUpdates); err != nil {
return nil, err
@@ -1201,6 +1218,48 @@ func (s *adminServiceImpl) BulkUpdateAccounts(ctx context.Context, input *BulkUp
return result, nil
}
// validateOllamaCloudPricingGateForBulkUpdate 把保存期无价门禁应用到批量更新:
// 对每个受影响的 ollama_cloud 账号,先把 AccountBulkUpdate 按仓库 BulkUpdate 的
// 实际生效方式模拟到「变更后的账号」上(credentials/extra 顶层 key 合并,status/
// schedulable 列覆盖),再复用 ollamaCloudPricingGateRevalidationNeeded + 门禁本体,
// 与单账号 UpdateAccount 保持同一判定,不另写一份规则。命中不合规时收集全部
// 违规项,由调用方整批拒绝(不产生任何写入)。
func (s *adminServiceImpl) validateOllamaCloudPricingGateForBulkUpdate(accountIDs []int64, targetsByID map[int64]*Account, updates AccountBulkUpdate) error {
var failures []string
for _, id := range accountIDs {
current, ok := targetsByID[id]
if !ok || !current.IsOllamaCloud() {
continue
}
next := *current
next.Credentials = mergeMap(nil, current.Credentials)
for key, value := range updates.Credentials {
next.Credentials[key] = value
}
next.Extra = mergeMap(nil, current.Extra)
for key, value := range updates.Extra {
next.Extra[key] = value
}
if updates.Status != nil {
next.Status = *updates.Status
}
if updates.Schedulable != nil {
next.Schedulable = *updates.Schedulable
}
if !ollamaCloudPricingGateRevalidationNeeded(current.Platform, ollamaCloudOutboundModelNames(current), ollamaCloudSchedulableBySave(current), &next) {
continue
}
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, &next); err != nil {
failures = append(failures, fmt.Sprintf("#%d(%s): %s", id, current.Name, infraerrors.Message(err)))
}
}
if len(failures) == 0 {
return nil
}
return infraerrors.BadRequest("MODEL_PRICING_MISSING",
fmt.Sprintf("批量更新被 ollama_cloud 保存期门禁拒绝,整批未写入(不合规账号: %s)", strings.Join(failures, "; ")))
}
func updatesUpstreamBillingProbeIdentity(credentials map[string]any) bool {
for _, key := range []string{"api_key", "base_url", credKeyHeaderOverrideEnabled, credKeyHeaderOverrides} {
if _, ok := credentials[key]; ok {
@@ -1328,6 +1387,21 @@ func (s *adminServiceImpl) SetAccountError(ctx context.Context, id int64, errorM
}
func (s *adminServiceImpl) SetAccountSchedulable(ctx context.Context, id int64, schedulable bool) (*Account, error) {
// B2-③ 保存期无价门禁:手动启用调度(false→true)与保存路径的「启用」是同一
// 调度准入开关,ollama_cloud 账号必须先过门禁,否则存量不合规账号可被一键放量
// (评审收口)。判定复用 ollamaCloudSchedulableBySave(active + Schedulable),
// 与单账号 Update 的启用语义一致;停用(true→false)属维护性操作,放行不校验。
if schedulable {
account, err := s.accountRepo.GetByID(ctx, id)
if err != nil {
return nil, err
}
if account.IsOllamaCloud() && !ollamaCloudSchedulableBySave(account) {
if err := validateOllamaCloudAccountModelPricingGate(s.billingService, account); err != nil {
return nil, err
}
}
}
if err := s.accountRepo.SetSchedulable(ctx, id, schedulable); err != nil {
return nil, err
}