mirror of
https://gitcode.com/JianFeeeee/ModelRouter.git
synced 2026-11-07 09:47:23 +00:00
用户判据:「priority 直接移除」「即使带 key 也没有 /v1/responses」
「channel 插件的问题还没完全解决」「生图和聊天合并到一个导航项」
## 一、删除 priority(它从未参与跨源调度)
`config.Model.Priority` 号称"高者优先参与 AUTO 选源",**那是错的**:
AUTO 链由 `config.ModelScope.Tier` 驱动(scheduler.Chain),priority 只被
`bestChatModel/bestImageModel` 用于"本源内部该发哪个模型",与跨源调度无关。
把它当调度依据会让人以为拖个数字就能改顺序,改完毫无效果。
- 删 `config.Model.Priority` 字段与 `bestChatModel/bestImageModel` 的优先级比较
- 删 `seedAuto()`:**AUTO 链为空时网关应直接 503**,不能凭空播种用户没配过的档位
- 删 UI `buildLanes` 的 discovery 回退(按源 priority 自动铺开)与 sourceRows
- 清掉 config.yaml 里 140 行 priority
## 二、一通道 = 一个适配器 = 一个源(channels 插件)
旧设计「一账号一源」(`channels-<平台>-<12位hex>`) 有三个结构性后果:
1. 三个账号 ⇒ 三个源、三份同名模型,用户看到三行无法区分的东西
2. 谁先谁后**取决于注册顺序,不是余额**(rankAccounts 只用于展示,从未接进同步路径)
3. 换号要改源名 ⇒ 用户书签里的 `源:模型` 全部失效
新设计:
- 源名只跟通道绑定:`channels-<平台>`,换号 = 同名 add_source 覆盖 api_key
(内核 AddSource 是 UpsertSourceInYAML + 内存替换),对客户端完全透明
- `pickAccountForSource()`:凭据可用 → 余额分档(先快作废后永久)→
跳过已标记失效的号。没有 balance 声明的平台不据此排除(不因"不会查"判死)
- `request_end` 钩子:真实请求失败且是**终态**错误(需充值/封禁/凭据永久失效)
时给当前账号打 termErr,下次选号跳过;成功则清标记。
⚠️ 只认终态 —— 429/超时/抖动都**不**标记(那会把好号一个个废掉)
- `refresh_creds` 每 30 分钟巡检后重新选号(兜底心跳,纯本地判定)
- 迁移:同步时自动清掉旧版按账号拆的源(按已知平台前缀匹配,不用贪婪 match)
- 顺带修:`refresh_creds` 漏认 `refresh_fn` ⇒ codearts 的 DPoP 续期永不触发
## 三、discover 支持用已存凭据(真实缺口)
刷新已有源的模型目录,此前必须让运维**再粘一次明文 key** —— 而库里是
`enc:v1:` 密文,WebUI 也不回显明文。结果就是"想刷新 → 得重新申请 key",
很多人干脆不刷,源的目录越放越旧(实例:某源 3 个生图模型从未登记)。
- `{"name":"oin"}` ⇒ 从已存源取 base_url + 解密凭据 + adapter
- 安全边界:已要求 admin;只能探测**本网关已配置的**源(不能拿任意 URL+key
做探测,那就成了 SSRF/密钥外带);响应不回显 key
## 四、image_models 显式声明(补元数据缺失)
`discoveredModelKind` 只看上游 modality 字段,并刻意**不从模型名推断**
(错误的 kind 会毒死 AUTO 链)。但有些网关的 /v1/models 只返回
`{id,object,created,owned_by}` —— 零 modality,于是生图模型全落成 chat,
生图端点永远 `no image source configured`。
不解这个两难:默认仍完全按元数据(不猜),但允许 `image_models` **显式声明**。
写错的 id 明确报 400,不静默造一个不存在的模型。
## 五、UI:对话与生图合并为一个导航项
两者本是同一件事的两种输入(都选模型、都发请求、都读结果),只是 kind 与端点
不同。合并只发生在**导航层**:模型下拉仍按 kind 分组/禁选(把图片模型选进 chat
会请求到错误端点)。两个面板同时存在于 DOM,切换只改 display —— 来回切不会丢
已输入的文字、对话历史或已生成的图。
## 测试
- `TestUI_ImageModeIsReachableFromChatTab`:改为钉"合并后仍可达"(分段控件、
切换函数、面板容器、端点),并断言**旧 tab 三件套必须消失**(否则 goTab 会找
一个不存在的面板)
- 测试夹具显式建 AUTO 链(内核不再 seedAuto):默认一源一 tier 倒序
(TestChatAUTO 验优先级);TestChatAutoChainTierFailover 自己覆盖成同 tier
(验 tier 内轮转)—— 两者验不同机制,不能共用一个默认
- core 的一批断言从"按账号 id 找源"改为"按平台名找源"
gateway/config/provider 全绿;core 的 channels 用例全绿。
TestRealMutants 需工作树干净后才跑(其自带的变异残留防护)。
BREAKING CHANGE: config.Model.Priority 已删除。旧的 priority 字段会被 YAML
解码静默忽略(内核不校验未知字段),因此既有 config.yaml 仍可加载,但该字段
不再有任何作用 —— 调度顺序请通过 AUTO 链的 tier 表达。
179 lines
5.6 KiB
Go
179 lines
5.6 KiB
Go
package core
|
|
|
|
import (
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"llmsproxy/internal/config"
|
|
)
|
|
|
|
// Startup must be idempotent, and every credential consumer must see PLAINTEXT.
|
|
//
|
|
// Two bugs shared one root cause: NewFromConfig unsealed the config at the END,
|
|
// after the steps that read credentials had already run.
|
|
//
|
|
// 1. seedKeys() deduped cfg.Keys[i].Key against the plaintext gateway_keys
|
|
// entries. With ciphertext keys the comparison never matched, so every
|
|
// restart appended another copy of the same admin key — production reached
|
|
// four identical admin keys.
|
|
// 2. rebuildRegistry() handed cfg.Sources[i].APIKey to provider.New, so with
|
|
// ciphertext it built every upstream client with "enc:v1:..." as its bearer
|
|
// token and every upstream call would 401.
|
|
//
|
|
// They masked each other: seedKeys' Save() unsealed memory as a side effect, so
|
|
// bug 2 was invisible until the redundant saves were removed. These tests drive
|
|
// the real entry point (core.New -> config.Load off disk), because building a
|
|
// fresh in-memory config per attempt hides both bugs — that is exactly how the
|
|
// first draft of this test failed to reproduce anything.
|
|
|
|
// writeSealedInstall creates a config on disk the way a real install looks
|
|
// after its first run: credentials already sealed, gateway_keys still plaintext.
|
|
func writeSealedInstall(t *testing.T, dir string) string {
|
|
t.Helper()
|
|
path := filepath.Join(dir, "config.yaml")
|
|
cfg := &config.Config{
|
|
Path: path,
|
|
AdapterDir: filepath.Join(dir, "adapters"),
|
|
RuntimeFile: filepath.Join(dir, "runtime.json"),
|
|
Listen: "127.0.0.1:0",
|
|
DefaultModel: "AUTO",
|
|
GatewayKeys: []string{"sk-gw-seed-me"},
|
|
Sources: []config.Source{{
|
|
Name: "up", BaseURL: "http://127.0.0.1:1/v1", APIKey: "sk-upstream-secret",
|
|
Adapter: "openai", Models: []config.Model{{ID: "gpt-4o"}},
|
|
}},
|
|
}
|
|
c, err := NewFromConfig(cfg)
|
|
if err != nil {
|
|
t.Fatalf("initial install: %v", err)
|
|
}
|
|
c.Close()
|
|
|
|
raw, err := os.ReadFile(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !strings.Contains(string(raw), "enc:v1:") {
|
|
t.Fatalf("fixture is wrong: on-disk config holds no sealed credential, "+
|
|
"so this test cannot detect ciphertext leaking into consumers:\n%s", raw)
|
|
}
|
|
return path
|
|
}
|
|
|
|
// writeSealedInstallNoSeed is writeSealedInstall without gateway_keys, so no
|
|
// key is ever seeded and no startup Save() can unseal the config as a side
|
|
// effect. That isolation is what makes the ciphertext leak observable.
|
|
func writeSealedInstallNoSeed(t *testing.T, dir string) string {
|
|
t.Helper()
|
|
path := filepath.Join(dir, "config.yaml")
|
|
cfg := &config.Config{
|
|
Path: path,
|
|
AdapterDir: filepath.Join(dir, "adapters"),
|
|
RuntimeFile: filepath.Join(dir, "runtime.json"),
|
|
Listen: "127.0.0.1:0",
|
|
DefaultModel: "AUTO",
|
|
Sources: []config.Source{{
|
|
Name: "up", BaseURL: "http://127.0.0.1:1/v1", APIKey: "sk-upstream-secret",
|
|
Adapter: "openai", Models: []config.Model{{ID: "gpt-4o"}},
|
|
}},
|
|
}
|
|
c, err := NewFromConfig(cfg)
|
|
if err != nil {
|
|
t.Fatalf("initial install: %v", err)
|
|
}
|
|
c.Close()
|
|
raw, err := os.ReadFile(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !strings.Contains(string(raw), "enc:v1:") {
|
|
t.Fatalf("fixture is wrong: no sealed credential on disk:\n%s", raw)
|
|
}
|
|
return path
|
|
}
|
|
|
|
// countKeysWithSecret loads the config, unseals it, and counts keys whose
|
|
// plaintext equals one of the gateway_keys entries.
|
|
func countKeysWithSecret(t *testing.T, path string) (total, matching int) {
|
|
t.Helper()
|
|
cfg, err := config.Load(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
box, err := config.NewSecretBox(cfg.RuntimeFile)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := cfg.UnsealSecrets(box); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := map[string]bool{}
|
|
for _, g := range cfg.GatewayKeys {
|
|
want[g] = true
|
|
}
|
|
for _, k := range cfg.Keys {
|
|
total++
|
|
if want[k.Key] {
|
|
matching++
|
|
}
|
|
}
|
|
return total, matching
|
|
}
|
|
|
|
// Restarting must not grow the key list. Before the fix this went 2 -> 3 -> 4.
|
|
func TestRestartDoesNotDuplicateSeededKeys(t *testing.T) {
|
|
dir := t.TempDir()
|
|
path := writeSealedInstall(t, dir)
|
|
|
|
if _, n := countKeysWithSecret(t, path); n != 1 {
|
|
t.Fatalf("after install: %d keys carry the seeded secret, want 1", n)
|
|
}
|
|
|
|
for i := 2; i <= 4; i++ {
|
|
c, err := New(path) // production path: reads the file
|
|
if err != nil {
|
|
t.Fatalf("restart %d: %v", i, err)
|
|
}
|
|
c.Close()
|
|
total, n := countKeysWithSecret(t, path)
|
|
if n != 1 {
|
|
t.Fatalf("restart %d: %d keys carry the seeded secret (total %d), want "+
|
|
"exactly 1 — seedKeys is comparing ciphertext against plaintext and "+
|
|
"appending a duplicate on every start", i, n, total)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Every provider must hold the real upstream credential, not its ciphertext.
|
|
//
|
|
// This deliberately runs with gateway_keys EMPTY. The buggy order was masked
|
|
// whenever seedKeys had work to do, because its Save() unsealed memory as a
|
|
// side effect — providers then happened to see plaintext. With no key to seed,
|
|
// no Save runs, and the ciphertext reaches the registry directly. An earlier
|
|
// version of this test kept gateway_keys populated and was insensitive: it
|
|
// passed even with the bug present.
|
|
func TestProvidersGetPlaintextCredentials(t *testing.T) {
|
|
dir := t.TempDir()
|
|
path := writeSealedInstallNoSeed(t, dir)
|
|
|
|
c, err := New(path)
|
|
if err != nil {
|
|
t.Fatalf("restart: %v", err)
|
|
}
|
|
defer c.Close()
|
|
|
|
for _, p := range c.registry.Providers() {
|
|
key := p.Config().APIKey
|
|
if strings.HasPrefix(key, "enc:v1:") {
|
|
t.Errorf("provider %q holds CIPHERTEXT api_key %q — every upstream call "+
|
|
"would 401", p.Name(), key)
|
|
}
|
|
if key != "sk-upstream-secret" {
|
|
t.Errorf("provider %q api_key = %q, want the plaintext upstream secret",
|
|
p.Name(), key)
|
|
}
|
|
}
|
|
}
|