From 0b38eb21c3ff24b4973313e506011aa3ebf2eb7d Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 13 Nov 2026 15:54:06 +0800 Subject: [PATCH] gateway: Claude Code's advisor is held to the calling key's models A gateway key held to some models (#882) could reach any other model through Claude Code's advisor tool, which names a second model inside the request: - served advisor (advisor_serve.go, db9a5ec7c): advise() asked the advisor model under magpieChose, which drops the key's models list because magpie picked the model from its settings. Here the caller named it, so it is now asked as the caller and the key's models and limits hold it; a refused model comes back as an advisor_tool_result_error. - native advisor (advisor.go, pre-existing): any same-provider Claude model passed upstream as the advisor for a held key. advisorTools now takes keyAllows(r, p) and leaves out an advisor whose model the key may not use (by magpie's id, the bare Claude id, and with [1m]). Run (on mote; load ~36, mica out of disk): - go test ./internal/gateway -run 'Advisor|Advised|KeyModels|Key' ok - broken by hand (magpieChose back, nil allowed): both new tests red (advisor asked 1 time; advisor sent upstream for 3 of 3 refused cases) - go vet darwin, GOOS=windows, linux nogui: ok; gofmt clean Not run: the full suite. --- internal/gateway/advisor.go | 21 +++++- internal/gateway/advisor_key_test.go | 97 ++++++++++++++++++++++++++++ internal/gateway/advisor_serve.go | 5 +- internal/gateway/gateway.go | 2 +- internal/gateway/key_models.go | 11 ++++ 5 files changed, 132 insertions(+), 4 deletions(-) create mode 100644 internal/gateway/advisor_key_test.go diff --git a/internal/gateway/advisor.go b/internal/gateway/advisor.go index 6cea1f1db..69f8928ae 100644 --- a/internal/gateway/advisor.go +++ b/internal/gateway/advisor.go @@ -25,8 +25,11 @@ import ( // advisor when the request's model is not Claude's (a vendor's Messages // API knows no such tool): the turn is answered without one, as a model // that isn't on magpie would be. What Claude Code put in the conversation -// for an advisor left out goes with it (withoutAdvisor). -func advisorTools(body []byte, p provider.Provider, upstream string, wires map[string]string) []byte { +// for an advisor left out goes with it (withoutAdvisor). allowed says +// whether the calling key may use one of p's models (keyAllows): the +// advisor's model is the client's to name, and the vendor runs it on the +// user's account, so a key held to some models is held here too. +func advisorTools(body []byte, p provider.Provider, upstream string, wires map[string]string, allowed func(model string) bool) []byte { if !bytes.Contains(body, []byte(`"advisor_`)) { return body } @@ -52,6 +55,9 @@ func advisorTools(body []byte, p provider.Provider, upstream string, wires map[s } json.Unmarshal(t["model"], &model) name, ok := advisorModel(p, model, wires) + if ok && allowed != nil && !allowed(advisorKeyModel(model)) { + ok = false + } if !claude || !ok { var n string json.Unmarshal(t["name"], &n) @@ -84,6 +90,17 @@ func advisorTools(body []byte, p provider.Provider, upstream string, wires map[s return out } +// advisorKeyModel is the model id a key's models are checked against for +// an advisor named model: magpie's model id when it names one, else the +// bare id as it was sent. +func advisorKeyModel(model string) string { + model = strings.TrimSuffix(strings.TrimSpace(model), "[1m]") + if _, m, ok := provider.Resolve(model); ok && !provider.IsGroupRef(model) { + return m + } + return model +} + // advisorModel is the name p's upstream knows the advisor model by, and // whether p can run it: one of p's models, by magpie's id, or a Claude // model's own id that names no provider. diff --git a/internal/gateway/advisor_key_test.go b/internal/gateway/advisor_key_test.go new file mode 100644 index 000000000..4d915211a --- /dev/null +++ b/internal/gateway/advisor_key_test.go @@ -0,0 +1,97 @@ +package gateway + +import ( + "net/http/httptest" + "strings" + "testing" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// advisorKey is a gateway key whose models are models, and its secret. +func advisorKey(t *testing.T, models ...string) string { + t.Helper() + keys, secrets := newCaller(t, "Held") + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: models}); err != nil { + t.Fatal(err) + } + return secrets[0] +} + +func sendAs(t *testing.T, s *Server, secret, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest("POST", "/v1/messages?beta=true", strings.NewReader(body)) + req.Header.Set("User-Agent", "claude-cli/2.1.316 (external, cli)") + req.Header.Set("Authorization", "Bearer "+secret) + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + return rec +} + +// Claude Code's advisor names a second model inside the request. A key +// held to some models may not reach another through it: magpie asks the +// advisor model as the caller (not as a model magpie chose), so the key's +// models hold it, and the advisor fails as an advisor does. +func TestAdvisorHeldToTheKeysModels(t *testing.T) { + u := advisedSetup(t) + secret := advisorKey(t, "v/*") + body := strings.Replace(advisorTurn("v/glm-5.1", "adv/adv-pro"), `"stream":true`, `"stream":false`, 1) + rec := sendAs(t, New(), secret, body) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + u.mu.Lock() + adv := len(u.advisor) + u.mu.Unlock() + if adv != 0 { + t.Fatalf("the advisor model the key may not use was asked %d times", adv) + } + r := gjson.Parse(rec.Body.String()) + var result gjson.Result + r.Get("content").ForEach(func(_, b gjson.Result) bool { + if b.Get("type").String() == "advisor_tool_result" { + result = b + } + return true + }) + if result.Get("content.type").String() != "advisor_tool_result_error" { + t.Fatalf("advisor result %s", rec.Body) + } +} + +// The same on a Claude provider whose upstream runs the advisor itself: a +// held key's advisor is sent upstream only when the key may use its model. +func TestNativeAdvisorHeldToTheKeysModels(t *testing.T) { + fresh(t) + u, url := newBillingUpstream(t) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: url, Models: []string{"claude-opus-5-5", "claude-sonnet-5-5"}}); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + models []string + advisor string + sent bool + }{ + {[]string{"relay/claude-sonnet-5-5"}, "relay/claude-opus-5-5", false}, + {[]string{"relay/claude-sonnet-5-5"}, "claude-opus-5-5", false}, + {[]string{"relay/claude-sonnet-5-5"}, "relay/claude-opus-5-5[1m]", false}, + {[]string{"relay/*"}, "relay/claude-opus-5-5", true}, + } { + secret := advisorKey(t, c.models...) + rec := sendAs(t, New(), secret, advisorTurn("relay/claude-sonnet-5-5", c.advisor)) + if rec.Code != 200 { + t.Fatalf("%v %s: %d %s", c.models, c.advisor, rec.Code, rec.Body) + } + b := u.last(t) + sent := false + for _, tl := range gjson.Get(b, "tools").Array() { + sent = sent || strings.HasPrefix(tl.Get("type").String(), "advisor_") + } + if sent != c.sent { + t.Errorf("key %v, advisor %s: sent upstream %t, want %t: %s", c.models, c.advisor, sent, c.sent, b) + } + } +} diff --git a/internal/gateway/advisor_serve.go b/internal/gateway/advisor_serve.go index b67808e62..e0bab70df 100644 --- a/internal/gateway/advisor_serve.go +++ b/internal/gateway/advisor_serve.go @@ -229,7 +229,10 @@ func (e errAdvice) Error() string { return e.err.Error() } // what it said before calling the advisor. func (s *Server) advise(ctx context.Context, q *Request, said []Part, model string) (string, error) { body := buildAnthropic(adviceFor(q, said), model) - r, err := http.NewRequestWithContext(ownAsk(magpieChose(ctx)), http.MethodPost, "http://magpie/v1/messages", nil) + // the caller named the advisor's model, not magpie's settings, so it is + // asked as the caller: the key's models and limits hold it (no + // magpieChose, which a search's or a title's model takes) + r, err := http.NewRequestWithContext(ownAsk(ctx), http.MethodPost, "http://magpie/v1/messages", nil) if err != nil { return "", errAdvice{"unavailable", err} } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 7aca825c1..c687c0478 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6679,7 +6679,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. toolSeen = clientToolUseIDs(body) body = saltedCallIDsBack(body) // Claude Code's advisor, named by magpie's id (advisor.go) - body = advisorTools(body, p, upstream, wiresOf(r.Context())) + body = advisorTools(body, p, upstream, wiresOf(r.Context()), keyAllows(r, p)) if p.IsBedrock() { // Claude Code's metadata.user_id, a JSON string these days, is // not the plain id Bedrock checks it against (#176) diff --git a/internal/gateway/key_models.go b/internal/gateway/key_models.go index b00dad756..1d54327db 100644 --- a/internal/gateway/key_models.go +++ b/internal/gateway/key_models.go @@ -54,6 +54,17 @@ func keyHolds(r *http.Request) (access.Identity, bool) { return who, who.Restricted() || len(who.Spent) > 0 } +// keyAllows is whether the calling key may use one of p's models, nil when +// the key isn't held to any (keyHolds): for a model the client names inside +// a request, beside the one it asks for (Claude Code's advisor). +func keyAllows(r *http.Request, p provider.Provider) func(model string) bool { + who, held := keyHolds(r) + if !held { + return nil + } + return func(model string) bool { return modelAllowed(who, p, model) } +} + // keyListHolds is keyHolds for a list of models shown to the key: a // spent limit leaves its models listed, as a spent limit of the whole key // does, and a request for one is told why it is refused.