mirror of
https://gitcode.com/JianFeeeee/ModelRouter.git
synced 2026-10-03 23:54:06 +00:00
问题:密钥控制只能限制模型范围。实测发现三个缺陷,其中前两个让
per-model token_quota 在真实链路上从未生效:
1. 桶键不含 key。scopeTokens 调 WindowTokens(model, source, win),
桶键是 model / source::model,与调用方无关。实测两把 key 各用
1000 token,窗口报 2000 —— A key 的额度被 B key 消耗。
2. 无 source pin 的桶永远是空的。真实记录 Source 总被填上,桶键存成
"deepseek::m1",而无 pin 的查询找 "m1" —— 读到 0,永远 < quota,
配额形同虚设。实测 WindowTokens("m1","",1h)=0 而 pinned=2000。
3. AUTO scope 走 KeyTokens(key),是全时段累计、永不重置。实测 30 天
前的 200 token 仍计入 1 小时配额(报 210 而非 10)。配了
period: hour 也不会每小时归零。
生产 5 把 user key 全是 token_quota: 0,所以前两条一直没暴露。
改动:
- Stats 新增 per-key 小时桶 keyModelHour(key → model → hour)与
keyHour(key 总量)、keyReqHour(请求数),retention 40 天,与既有
modelHour 对齐以覆盖最长的 month 窗口;LoadAudit 走 aggregateLocked,
所以窗口用量跨重启存活。modelHour 保持 key-blind:它服务的是 AUTO
槽位配额(限制整个网关对某槽位的消耗),语义不同,不应被 per-key
改造污染。
- 每个请求写两份模型桶:裸 model 与 source::model。无 pin 的 scope
条目读前者,有 pin 的读后者。
- GWKey 新增 TokenQuota / ReqQuota / Period / Hours:整钥配额,
跨该 key 所有模型共享一份预算;ReqQuota 覆盖持续请求量(源上的
RPM 只管突发)。
- 配额耗尽返回 429 + Retry-After(rate_limit_exceeded),而不是 403:
403 让客户端以为这把 key 永远不能用该模型,直接放弃;429 + 等待
才能在窗口重置后自动恢复。模型越权仍是 403。
- admin key 永不受配额限制 —— 否则操作者会把自己锁在门外。
- 周期词表在写入时校验,拼错的 period 被拒绝而不是静默当成永不过期
(那与操作者输入的意图正好相反)。
- PUT /api/keys 的配额字段是指针:省略=保留原值,显式 0=解除限制。
否则只改模型范围就会悄悄清空预算。
判据 3 个文件 24 例,9 个变异全部被抓:key 隔离、pin 桶缺失、
AUTO 周期、key-blind 退化、429→403、admin 被限、PUT 清空配额、
Validate 失效、pinned 桶缺失。前三个变异最初漏网 —— 判据只测了
Stats 层没测接线,补了走真实 HTTP 的接线层与 API 层判据后抓住。
端到端验证:真实进程 + 加密配置往返,配额字段与 enc:v1 密钥均正常。
231 lines
7.9 KiB
Go
231 lines
7.9 KiB
Go
package gateway
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
|
|
"llmsproxy/internal/config"
|
|
"llmsproxy/internal/core"
|
|
)
|
|
|
|
// adminGateway builds a gateway whose admin key can call /api/keys.
|
|
func adminGateway(t *testing.T, keys ...config.GWKey) *Gateway {
|
|
t.Helper()
|
|
td := t.TempDir()
|
|
cfgPath := td + "/config.yaml"
|
|
if err := os.WriteFile(cfgPath, []byte("listen: :0"), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cfg := &config.Config{
|
|
Path: cfgPath,
|
|
AdapterDir: td + "/adapters",
|
|
RuntimeFile: td + "/runtime.json",
|
|
Keys: keys,
|
|
}
|
|
if err := cfg.ApplyDefaults(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
c, err := core.NewFromConfig(cfg)
|
|
if err != nil {
|
|
t.Fatalf("core: %v", err)
|
|
}
|
|
t.Cleanup(c.Close)
|
|
g, err := New(c, []string{"sk-admin"})
|
|
if err != nil {
|
|
t.Fatalf("gateway: %v", err)
|
|
}
|
|
return g
|
|
}
|
|
|
|
func adminReq(t *testing.T, g *Gateway, method, path, body string) *httptest.ResponseRecorder {
|
|
t.Helper()
|
|
req, _ := http.NewRequest(method, path, strings.NewReader(body))
|
|
req.Header.Set("Authorization", "Bearer sk-admin")
|
|
req.Header.Set("Content-Type", "application/json")
|
|
rr := httptest.NewRecorder()
|
|
g.Handler().ServeHTTP(rr, req)
|
|
return rr
|
|
}
|
|
|
|
// keyRecord pulls one key's stored record out of the admin list.
|
|
func keyRecord(t *testing.T, g *Gateway, secret string) config.GWKey {
|
|
t.Helper()
|
|
rr := adminReq(t, g, "GET", "/api/keys", "")
|
|
if rr.Code != 200 {
|
|
t.Fatalf("GET /api/keys: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
var out struct {
|
|
Keys []config.GWKey `json:"keys"`
|
|
}
|
|
if err := json.Unmarshal(rr.Body.Bytes(), &out); err != nil {
|
|
t.Fatalf("decode: %v (%s)", err, rr.Body.String())
|
|
}
|
|
for _, k := range out.Keys {
|
|
if k.Key == secret {
|
|
return k
|
|
}
|
|
}
|
|
t.Fatalf("key %q not found in %s", secret, rr.Body.String())
|
|
return config.GWKey{}
|
|
}
|
|
|
|
func TestKeyAPIStoresQuota(t *testing.T) {
|
|
g := adminGateway(t, config.GWKey{Key: "sk-admin", Role: "admin"})
|
|
rr := adminReq(t, g, "POST", "/api/keys",
|
|
`{"name":"agent-x","role":"user","token_quota":50000,"req_quota":200,"period":"nhour","hours":6,"models":[{"model":"m1"}]}`)
|
|
if rr.Code != 200 {
|
|
t.Fatalf("create: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
var created struct {
|
|
Key config.GWKey `json:"key"`
|
|
}
|
|
if err := json.Unmarshal(rr.Body.Bytes(), &created); err != nil {
|
|
t.Fatalf("decode: %v", err)
|
|
}
|
|
if created.Key.TokenQuota != 50000 || created.Key.ReqQuota != 200 ||
|
|
created.Key.Period != "nhour" || created.Key.Hours != 6 {
|
|
t.Fatalf("created key did not carry the caps: %+v", created.Key)
|
|
}
|
|
// and it must survive a read-back (persisted, not just echoed)
|
|
back := keyRecord(t, g, created.Key.Key)
|
|
if back.TokenQuota != 50000 || back.Period != "nhour" || back.Hours != 6 {
|
|
t.Errorf("read-back lost the caps: %+v", back)
|
|
}
|
|
}
|
|
|
|
// Editing only the model scope must not silently clear a key's budget: the
|
|
// caps are pointers precisely so "absent" is not "zero".
|
|
func TestKeyAPIUpdateKeepsQuotaWhenOmitted(t *testing.T) {
|
|
g := adminGateway(t, config.GWKey{Key: "sk-admin", Role: "admin"})
|
|
rr := adminReq(t, g, "POST", "/api/keys",
|
|
`{"name":"agent-x","role":"user","token_quota":50000,"period":"day-typo-free","models":[{"model":"m1"}]}`)
|
|
rr = adminReq(t, g, "POST", "/api/keys", `{"name":"y","role":"user","token_quota":50000,"period":"hour","models":[{"model":"m1"}]}`)
|
|
if rr.Code != 200 {
|
|
t.Fatalf("setup create: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
var created struct {
|
|
Key config.GWKey `json:"key"`
|
|
}
|
|
_ = json.Unmarshal(rr.Body.Bytes(), &created)
|
|
|
|
// a scope-only edit
|
|
rr = adminReq(t, g, "PUT", "/api/keys/"+created.Key.Key,
|
|
`{"name":"agent-y","models":[{"model":"m1"},{"model":"m2"}]}`)
|
|
if rr.Code != 200 {
|
|
t.Fatalf("update: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
back := keyRecord(t, g, created.Key.Key)
|
|
if back.TokenQuota != 50000 {
|
|
t.Errorf("token_quota was cleared by a scope-only edit: %d", back.TokenQuota)
|
|
}
|
|
if back.Period != "hour" {
|
|
t.Errorf("period was cleared by a scope-only edit: %q", back.Period)
|
|
}
|
|
if len(back.Models) != 2 {
|
|
t.Errorf("scope edit did not apply: %+v", back.Models)
|
|
}
|
|
}
|
|
|
|
// Sending 0 explicitly must lift the cap, not be treated as "absent".
|
|
func TestKeyAPIUpdateZeroLiftsCap(t *testing.T) {
|
|
g := adminGateway(t, config.GWKey{Key: "sk-admin", Role: "admin"})
|
|
rr := adminReq(t, g, "POST", "/api/keys", `{"name":"z","role":"user","token_quota":1000,"period":"hour"}`)
|
|
if rr.Code != 200 {
|
|
t.Fatalf("create: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
var created struct {
|
|
Key config.GWKey `json:"key"`
|
|
}
|
|
_ = json.Unmarshal(rr.Body.Bytes(), &created)
|
|
|
|
rr = adminReq(t, g, "PUT", "/api/keys/"+created.Key.Key, `{"token_quota":0}`)
|
|
if rr.Code != 200 {
|
|
t.Fatalf("lift: %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
if back := keyRecord(t, g, created.Key.Key); back.TokenQuota != 0 {
|
|
t.Errorf("token_quota = %d, want 0 (cap lifted)", back.TokenQuota)
|
|
}
|
|
}
|
|
|
|
// A misspelled period must be refused, not quietly turned into an all-time
|
|
// quota — which is the exact opposite of what the operator typed.
|
|
func TestKeyAPIRejectsBadPeriod(t *testing.T) {
|
|
g := adminGateway(t, config.GWKey{Key: "sk-admin", Role: "admin"})
|
|
rr := adminReq(t, g, "POST", "/api/keys", `{"name":"bad","role":"user","token_quota":1000,"period":"houre"}`)
|
|
if rr.Code != http.StatusBadRequest {
|
|
t.Fatalf("want 400 for a bad period, got %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
if !strings.Contains(rr.Body.String(), "period") {
|
|
t.Errorf("error should name the period field: %s", rr.Body.String())
|
|
}
|
|
}
|
|
|
|
func TestKeyAPIRejectsNegativeQuota(t *testing.T) {
|
|
g := adminGateway(t, config.GWKey{Key: "sk-admin", Role: "admin"})
|
|
rr := adminReq(t, g, "POST", "/api/keys", `{"name":"bad","role":"user","token_quota":-5}`)
|
|
if rr.Code != http.StatusBadRequest {
|
|
t.Fatalf("want 400 for a negative quota, got %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
}
|
|
|
|
// A non-admin key must not be able to set or read another key's budget.
|
|
func TestKeyAPIQuotaIsAdminOnly(t *testing.T) {
|
|
g := adminGateway(t,
|
|
config.GWKey{Key: "sk-admin", Role: "admin"},
|
|
config.GWKey{Key: "sk-u", Role: "user", TokenQuota: 10, Period: "hour"},
|
|
)
|
|
req, _ := http.NewRequest("POST", "/api/keys", strings.NewReader(`{"name":"x","role":"admin","token_quota":0}`))
|
|
req.Header.Set("Authorization", "Bearer sk-u")
|
|
req.Header.Set("Content-Type", "application/json")
|
|
rr := httptest.NewRecorder()
|
|
g.Handler().ServeHTTP(rr, req)
|
|
if rr.Code != http.StatusForbidden {
|
|
t.Fatalf("non-admin create: want 403, got %d %s", rr.Code, rr.Body.String())
|
|
}
|
|
// /api/v1/keys echoes the caps but never the secret
|
|
rr = adminReq(t, g, "GET", "/api/v1/keys", "")
|
|
if rr.Code != 200 {
|
|
t.Fatalf("GET /api/v1/keys: %d", rr.Code)
|
|
}
|
|
if strings.Contains(rr.Body.String(), "sk-u") {
|
|
t.Error("/api/v1/keys leaked a key secret")
|
|
}
|
|
if !strings.Contains(rr.Body.String(), `"token_quota":10`) {
|
|
t.Errorf("/api/v1/keys should expose the cap: %s", rr.Body.String())
|
|
}
|
|
}
|
|
|
|
// The AUTO scope entry must honour its reset window: usage that aged out of
|
|
// the window must not count against a per-key cap.
|
|
func TestAutoScopeQuotaHonoursWindow(t *testing.T) {
|
|
g, _ := quotaGateway(t,
|
|
config.GWKey{Key: "sk-a", Role: "user", Models: []config.ModelScope{
|
|
{Model: "AUTO", TokenQuota: 1000, Period: "hour"},
|
|
}},
|
|
config.GWKey{Key: "sk-b", Role: "user"},
|
|
)
|
|
ctx := quotaCtx(t, g, "sk-a")
|
|
sc := config.ModelScope{Model: "AUTO", TokenQuota: 1000, Period: "hour"}
|
|
|
|
// aged-out usage: 2 days old, 5M tokens — must be invisible to a 1h window
|
|
g.stats.Record(Req{Time: nowMSOffset(-48 * 3600 * 1000), Key: keyID("sk-a"),
|
|
Model: "m1", Source: "up", Prompt: 2500000, Compl: 2500000, OK: true, Status: 200})
|
|
if used := g.scopeTokens(ctx, sc); used != 0 {
|
|
t.Fatalf("AUTO scope saw %d tokens outside its 1h window; the period is being ignored", used)
|
|
}
|
|
|
|
// in-window usage counts
|
|
g.stats.Record(Req{Time: nowMSOffset(0), Key: keyID("sk-a"),
|
|
Model: "m1", Source: "up", Prompt: 400, Compl: 400, OK: true, Status: 200})
|
|
if used := g.scopeTokens(ctx, sc); used != 800 {
|
|
t.Fatalf("AUTO scope used = %d, want 800", used)
|
|
}
|
|
}
|
|
|
|
var _ = fmt.Sprintf
|