fix(ollama): enforce the ollama cloud model whitelist at runtime

This commit is contained in:
alfadb committed 2026-10-08 15:24:05 +08:00
1 parent 625f7b0d23
commit e5f75b7b02
8 files changed
+343 -8

No files matched your search

@@ -1287,6 +1287,13 @@ func (h *GatewayHandler) Models(c *gin.Context) {
return
}
// ollama_cloud 无静态默认模型列表(defaultModelIDsForPlatform 返回空):
// 账号侧清单缺失时返回空列表,不得回落 Claude 默认模型。
if platform == service.PlatformOllamaCloud {
writeModelsListResponse(c, []claude.Model{})
return
}
writeModelsListResponse(c, claude.DefaultModels)
}
@@ -1572,6 +1579,11 @@ func defaultModelIDsForPlatform(platform string) []string {
return service.DefaultOpenCodeGoModelIDs()
case service.PlatformTypeSafe:
return []string{"jev-latest"}
case service.PlatformOllamaCloud:
// ollama_cloud 没有静态默认模型列表:可服务模型完全来自账号侧的
// model_mapping / extra.allowed_models(缺失时 IsModelSupported 为
// deny-all)。default 分支的 Claude 列表对它只会造成虚假广告。
return nil
case service.PlatformComposite:
ids := make([]string, 0)
seen := make(map[string]struct{})
@@ -0,0 +1,85 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
middleware2 "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"
)
// ollama_cloud 没有静态默认模型列表:defaultModelIDsForPlatform 不得回落
// Claude 列表(default 分支),/models 在账号侧清单缺失时返回空列表。
func TestDefaultModelIDsForPlatform_OllamaCloudReturnsEmpty(t *testing.T) {
require.Empty(t, defaultModelIDsForPlatform(service.PlatformOllamaCloud))
require.NotEmpty(t, defaultModelIDsForPlatform(service.PlatformAnthropic))
}
func TestGatewayModels_OllamaCloudGroupListsAllowedModels(t *testing.T) {
gin.SetMode(gin.TestMode)
groupID := int64(9201)
h := newGatewayModelsHandlerForTest(
&gatewayModelsAccountRepoStub{
byGroup: map[int64][]service.Account{
groupID: {
{
ID: 1,
Platform: service.PlatformOllamaCloud,
Credentials: map[string]any{},
Extra: map[string]any{service.OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}},
},
},
},
},
)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
Group: &service.Group{ID: groupID, Platform: service.PlatformOllamaCloud},
})
h.Models(c)
require.Equal(t, http.StatusOK, rec.Code)
var got gatewayModelsResponseForTest
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
require.Equal(t, []string{"gpt-oss:120b"}, modelIDsForTest(got.Data))
}
// 账号侧清单缺失(deny-all)时 /models 必须返回空,而不是回落 Claude 列表。
func TestGatewayModels_OllamaCloudGroupWithoutListReturnsEmpty(t *testing.T) {
gin.SetMode(gin.TestMode)
groupID := int64(9202)
h := newGatewayModelsHandlerForTest(
&gatewayModelsAccountRepoStub{
byGroup: map[int64][]service.Account{
groupID: {
{ID: 1, Platform: service.PlatformOllamaCloud, Credentials: map[string]any{}},
},
},
},
)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
c.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{
Group: &service.Group{ID: groupID, Platform: service.PlatformOllamaCloud},
})
h.Models(c)
require.Equal(t, http.StatusOK, rec.Code)
var got gatewayModelsResponseForTest
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got))
require.Empty(t, got.Data, "ollama_cloud 不得回落 Claude 默认模型列表")
require.NotContains(t, modelIDsForTest(got.Data), "claude-sonnet-4-6")
}
@@ -1021,6 +1021,11 @@ func filterSchedulerExtra(extra map[string]any) map[string]any {
// 走网关报 no available accounts"。
"openai_passthrough",
"openai_oauth_passthrough",
// ollama_cloud 空 mapping 的出站白名单必须进投影:候选过滤的
// Account.IsModelSupported 以它为白名单(无清单即 deny-all)。
// 裁掉它,白名单账号会在选号阶段被整体误判为 model_not_supported,
// 表现为 ollama_cloud 分组恒 no available accounts。
service.OllamaCloudAllowedModelsExtraKey,
"codex_fingerprint_mode",
"codex_fingerprint_seed",
"codex_5h_used_percent",
@@ -0,0 +1,39 @@
//go:build unit
package repository
import (
"encoding/json"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
// ollama_cloud 空 mapping 的出站白名单(extra.allowed_models)必须穿过调度投影:
// 候选过滤的 Account.IsModelSupported 以它为白名单(无清单即 deny-all)。裁掉它,
// 白名单账号会在选号阶段被整体误判为 model_not_supported(#4936 同款投影缺失)。
func TestFilterSchedulerExtra_KeepsOllamaCloudAllowedModels(t *testing.T) {
extra := map[string]any{
service.OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b", "qwen3:32b"},
"unknown_key": "must-be-dropped",
}
filtered := filterSchedulerExtra(extra)
require.Len(t, filtered, 1)
kept, ok := filtered[service.OllamaCloudAllowedModelsExtraKey]
require.True(t, ok, "allowed_models 必须保留在调度投影中")
require.Contains(t, kept, "gpt-oss:120b")
// 走真实的序列化/反序列化路径:sched:meta 里的 []string 会以 []any 读回,
// ollamaCloudOutboundModelNames 两种形态都必须能解析。
payload, err := json.Marshal(filtered)
require.NoError(t, err)
var decoded map[string]any
require.NoError(t, json.Unmarshal(payload, &decoded))
account := service.Account{ID: 1, Platform: service.PlatformOllamaCloud, Extra: decoded}
require.True(t, account.IsModelSupported("gpt-oss:120b"))
require.False(t, account.IsModelSupported("totally-unpriced-model"))
}
+20
View File
@@ -894,6 +894,26 @@ func (a *Account) IsModelSupported(requestedModel string) bool {
if a.Platform == PlatformDeepseek {
return isDeepseekServableModel(requestedModel)
}
// ollama_cloud 运行时白名单:空映射时 extra.allowed_models 清单就是
// 唯一可出站白名单;既无映射也无清单则 deny-all(不支持任何模型)。
// 与保存期门禁 validateOllamaCloudAccountModelPricingGate 的「mapping
// 或清单至少其一」语义对齐。空映射下请求的公开模型名即出站名
// (ResolveMappedModel 原样透传),清单项又是按出站名断言过定价的,
// 因此对公开名做精确匹配即可;保存期门禁已确保清单不含通配符
// (通配符串无法解析到定价,保存即被拒)。
if a.IsOllamaCloud() {
allowed := ollamaCloudOutboundModelNames(a)
if len(allowed) == 0 {
return false
}
trimmed := strings.TrimSpace(requestedModel)
for _, model := range allowed {
if model == trimmed {
return true
}
}
return false
}
return true // 无映射 = 允许所有
}
if mappingSupportsRequestedModel(mapping, requestedModel) {
@@ -0,0 +1,159 @@
package service
// ollama_cloud 运行时白名单回归测试(钉死独立评审的探针场景):
// - 空 model_mapping + extra.allowed_models 清单 → IsModelSupported 只放行
// 清单内模型,清单外(含未定价模型名)一律拒绝、调度不选中;
// - 空 mapping 且无清单 → deny-all;
// - 非 ollama 平台空 mapping 仍放行所有(回归护栏);
// - /models 列表路径(GetAvailableModels)并入 allowed_models 清单。
//
// 与保存期门禁(account_ollama_cloud_pricing_gate_test.go)合起来形成闭环:
// 白名单决定能发什么,预检决定发出去的东西是否有价。
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
func newOllamaCloudWhitelistAccount(credentials map[string]any, extra map[string]any) *Account {
return &Account{
ID: 9101,
Platform: PlatformOllamaCloud,
Type: AccountTypeAPIKey,
Status: StatusActive,
Schedulable: true,
Credentials: credentials,
Extra: extra,
}
}
// 评审探针场景:空 mapping + 清单只含 gpt-oss:120b → totally-unpriced-model
// 必须不被支持、不被调度选中(评审当前观测到「仍 supported」)。
func TestOllamaCloudWhitelist_ProbeUnpricedModelNotSupported(t *testing.T) {
t.Parallel()
// Extra 走 JSON 反序列化的真实形态([]any 元素为 string)。
account := newOllamaCloudWhitelistAccount(
map[string]any{},
map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}},
)
require.False(t, account.IsModelSupported("totally-unpriced-model"),
"清单外未定价模型名不得放行(评审探针场景)")
require.False(t, account.IsModelSupported("claude-sonnet-4-6"),
"其它平台默认模型名同样在清单外")
require.True(t, account.IsModelSupported("gpt-oss:120b"), "清单内模型必须放行")
// 程序化构造形态([]string)语义一致。
stringListAccount := newOllamaCloudWhitelistAccount(
nil,
map[string]any{OllamaCloudAllowedModelsExtraKey: []string{"gpt-oss:120b"}},
)
require.False(t, stringListAccount.IsModelSupported("totally-unpriced-model"))
require.True(t, stringListAccount.IsModelSupported("gpt-oss:120b"))
// 调度候选过滤同样拒绝:不被选中。
ctx := context.Background()
reason := openAICompatibleAccountEligibilityFailureReasonBeforeProfit(
ctx, account, PlatformOllamaCloud, "totally-unpriced-model", false, OpenAIEndpointCapabilityChatCompletions)
require.Equal(t, "model_not_supported", reason)
reason = openAICompatibleAccountEligibilityFailureReasonBeforeProfit(
ctx, account, PlatformOllamaCloud, "gpt-oss:120b", false, OpenAIEndpointCapabilityChatCompletions)
require.Empty(t, reason, "清单内模型必须保持可选中")
}
func TestOllamaCloudWhitelist_EmptyMappingNoListDeniesAll(t *testing.T) {
t.Parallel()
account := newOllamaCloudWhitelistAccount(map[string]any{}, map[string]any{})
for _, model := range []string{"gpt-oss:120b", "totally-unpriced-model", "claude-sonnet-4-6", ""} {
require.False(t, account.IsModelSupported(model),
"空 mapping 且无清单必须 deny-all: %q", model)
}
// 清单存在但全为空白项:视同未提供,仍然 deny-all(与保存期门禁的
// 「清单缺失即拒绝」语义一致)。
blankAccount := newOllamaCloudWhitelistAccount(
nil,
map[string]any{OllamaCloudAllowedModelsExtraKey: []any{" ", ""}},
)
require.False(t, blankAccount.IsModelSupported("gpt-oss:120b"))
}
func TestOllamaCloudWhitelist_NonEmptyMappingKeepsMappingSemantics(t *testing.T) {
t.Parallel()
account := newOllamaCloudWhitelistAccount(
map[string]any{"model_mapping": map[string]any{"alias:latest": "gpt-oss:120b"}},
nil,
)
require.True(t, account.IsModelSupported("alias:latest"), "mapping 键即公开白名单")
require.False(t, account.IsModelSupported("totally-unpriced-model"))
// 既有语义:非 ollama 也一样——mapping 目标值不是公开名,不因本次改动改变。
require.False(t, account.IsModelSupported("gpt-oss:120b"), "mapping 目标值不是公开名")
}
// 回归护栏:非 ollama 平台的空 mapping 仍放行所有(钉住 4 处风险面语义)。
// 不含 antigravity / grok:这两个平台空 mapping 的既有语义是注入平台默认映射
// (resolveModelMapping),从来不是「放行所有」,与本次改动无关。
func TestOllamaCloudWhitelist_NonOllamaEmptyMappingStillAllowsAll(t *testing.T) {
t.Parallel()
for _, platform := range []string{
"", PlatformAnthropic, PlatformOpenAI, PlatformGemini,
PlatformDeepseek, PlatformKimi, PlatformMiniMax, PlatformZhipu, PlatformOpenCodeGo,
} {
account := &Account{ID: 1, Platform: platform, Type: AccountTypeAPIKey, Credentials: map[string]any{}}
require.Truef(t, account.IsModelSupported("totally-unpriced-model"),
"平台 %s 空 mapping 必须仍放行所有模型", platform)
}
}
// /models 列表路径:GetAvailableModels 并入 ollama_cloud 的 allowed_models 清单。
func TestGetAvailableModels_MergesOllamaCloudAllowedModels(t *testing.T) {
t.Parallel()
groupID := int64(9102)
repo := &modelsListAccountRepoStub{
byGroup: map[int64][]Account{
groupID: {
{
ID: 1,
Platform: PlatformOllamaCloud,
Credentials: map[string]any{},
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b", "qwen3:32b"}},
},
{
ID: 2,
Platform: PlatformOllamaCloud,
Credentials: map[string]any{"model_mapping": map[string]any{"alias:latest": "gpt-oss:120b"}},
},
{
ID: 3,
Platform: PlatformOllamaCloud,
Credentials: map[string]any{},
},
},
},
}
svc := &GatewayService{accountRepo: repo}
models := svc.GetAvailableModels(context.Background(), &groupID, PlatformOllamaCloud)
require.Equal(t, []string{"alias:latest", "gpt-oss:120b", "qwen3:32b"}, models)
// 全部账号都是 deny-all(无 mapping 无清单)→ 无可用模型列表。
denyAllGroup := int64(9103)
repo.byGroup[denyAllGroup] = []Account{
{ID: 4, Platform: PlatformOllamaCloud, Credentials: map[string]any{}},
}
require.Nil(t, svc.GetAvailableModels(context.Background(), &denyAllGroup, PlatformOllamaCloud))
// 非 ollama 平台的既有语义不变:无任何 mapping → 仍返回 nil(用默认列表)。
nonOllamaGroup := int64(9104)
repo.byGroup[nonOllamaGroup] = []Account{
{ID: 5, Platform: PlatformDeepseek, Credentials: map[string]any{}},
}
require.Nil(t, svc.GetAvailableModels(context.Background(), &nonOllamaGroup, PlatformDeepseek))
}
+20 -8
View File
@@ -1438,15 +1438,27 @@ func (s *GatewayService) GetAvailableModels(ctx context.Context, groupID *int64,
}
mapping := acc.GetModelMapping()
for model := range mapping {
// Accounts pulled in through mixed scheduling only contribute the
// models that belong to the listing platform (e.g. an antigravity
// account's claude-* mappings must not surface on a gemini group).
if platform != "" && acc.Platform != platform && !mixedListingModelAllowed(platform, model) {
continue
if len(mapping) > 0 {
for model := range mapping {
// Accounts pulled in through mixed scheduling only contribute the
// models that belong to the listing platform (e.g. an antigravity
// account's claude-* mappings must not surface on a gemini group).
if platform != "" && acc.Platform != platform && !mixedListingModelAllowed(platform, model) {
continue
}
modelSet[model] = struct{}{}
hasAnyMapping = true
}
} else if acc.IsOllamaCloud() {
// ollama_cloud 空 mapping:extra.allowed_models 清单即公开模型
// 列表(空映射下公开名=出站名);无清单(deny-all)账号不贡献
// 任何模型名,与 IsModelSupported 的运行时白名单语义一致。
if allowed := ollamaCloudOutboundModelNames(&acc); len(allowed) > 0 {
hasAnyMapping = true
for _, model := range allowed {
modelSet[model] = struct{}{}
}
}
modelSet[model] = struct{}{}
hasAnyMapping = true
}
}
@@ -70,6 +70,9 @@ func TestOllamaCloudPlatform_EntersOpenAISchedulerCandidatePool(t *testing.T) {
Schedulable: true,
Concurrency: 1,
Credentials: map[string]any{"api_key": "ollama-key", "base_url": "https://ollama.com/v1"},
// 运行时白名单生效后,空 mapping 且无清单的 ollama_cloud 账号是
// deny-all(保存期门禁本就拒绝该配置),夹具必须声明清单才能入选。
Extra: map[string]any{OllamaCloudAllowedModelsExtraKey: []any{"gpt-oss:120b"}},
},
{
ID: 77022,