gateway keys: a key given a model is not given a routing group of it the user never handed out (kautism)

kautism on Discord: a gateway key held to gemini 3.8 alone was shown,
and could use, a routing group the user made of gemini 3.8 alone, though
the user never gave the key that group. groupAllowed let a key use any
group whose every member it may use (the #882 rule), so the group leaked
into /v1/models and every route that asks it.

- key_models.go groupAllowed, the one check every route asks (the model
  lists' entryAllowed, serve on every API, countHeld, embeddings, images,
  videos, decision groups, a subagent's and masking's route): a group of
  the user's own is a key's only when the key names it (group/<id> or
  group/*). A group magpie found (auto/<model>, one model several
  providers serve; foundGroup) still passes when the key may use every
  member, as it is that model. A key that names accounts and no model
  (Linka, access.HeldModels gives it "<provider>/*") still may use a
  group of those providers' models alone, as it may every such model:
  access.Identity.AccountModels says so, for an issued key too.
- keyGroupFor: a bare name that is both a group of the user's the key may
  not use and a model it may use is that model for the key (a group the
  user called "Gemini 3.8", id gemini-3-8, would otherwise have turned
  the key's bare gemini-3.8 into a 403). serve's grouped and countHeld
  use it.
- Decision models (v0.1.2681) unchanged: a group the key names still
  asks its own Jev; TestGatewayKeyHeldToAGroupKeepsItsDecider passes.
- A group named inside one the key doesn't name no longer makes the outer
  one the key's (TestGatewayKeyModelsNameAGroup updated); the key names
  the outer group to use it.
- docs/reference.md and gateway-routing.md say so.

TestGatewayKeyGivenAModelIsNotGivenItsGroup is the reporter's case: a key
given google/gemini-3.8 alone, a group "Only 3.8" and one "Gemini 3.8" of
that model alone. Neither is listed in /v1/models nor found at
/v1/models/{id}; each is refused on chat completions, messages and
count_tokens, by id and by name; the model is served by id and bare;
a found group of two providers' gemini-3.8 is still listed and served to
a key given both; a key naming group/only-38 is given it.
TestGatewayKeyModelsHoldAKey, TestKeyListSeesChangesNextRequest updated
from the old rule.

Broken by hand: groupAllowed back to the old rule: the new test,
TestGatewayKeyModelsHoldAKey and TestGatewayKeyModelsNameAGroup red. The
bare-name fallback off: the new test red (chat gemini-3.8 403). The
accounts-only exception off: TestGatewayKeyAccountsOnlyHoldTheModels red.

Run on mote at this commit (rebased on origin/main 1747559d0): go build
./... ok; go vet of internal/gateway and internal/access for darwin,
linux and windows ok; gofmt -l clean; go test ./internal/access ok;
go test -run 'Key|Count|Group|Model|Identity|Issue' ./internal/gateway
ok; go test -run 'CallerKey|Key' ./internal/gui ok. Before the rebase
(at e7185daeb) the whole internal/gateway package and internal/cli ran:
red only in TestCodexPoolSaysTheClientsVersion (#4807, red in a full
package run on mote, passes alone) and TestEveryRouteHasACommandOrIsNamed
(#4826, red on main since e87140242), neither touched here.

Not tried: a real magpie with the reporter's own key and group; an issued
key under an accounts-only issuer (set in identityOf, no test of its own).
This commit is contained in:
yetone
2026-11-02 15:34:08 +08:00
parent 1747559d02
commit 1aca55909f
8 changed files with 206 additions and 28 deletions
+12 -4
View File
@@ -707,10 +707,18 @@ serves the call, so a bare model name is resolved first, or a routing group,
`group/<id>` (`group/*` for every group). A key that names a group may use
the group with every member in it, though not those members asked for by
name. Such a key sees only its models in `/v1/models`, `/v1/codex/models`
and the Anthropic and Gemini lists, a routing group it doesn't name only when it may use every
member, and is refused any other model with a 403 in the API's error shape
before a provider is asked; a fallback it may not use is skipped. A key with
no models listed may use every model.
and the Anthropic and Gemini lists, and is refused any other model with a
403 in the API's error shape before a provider is asked; a fallback it may
not use is skipped. A routing group of your own is the key's only when it
names it, even when every model in the group is one the key may use (a key
given `google/gemini-3.8` neither sees nor may ask a group you made of that
model alone; kautism on Discord); a group magpie found (`auto/<model>`,
one model several providers serve) is the key's when it may use every
provider's model in it. A key that names accounts and no model may use a
group of yours made only of those accounts' providers' models, as it may
every such model. A bare name that is both a group of yours and a model
the key may use is that model for the key. A key with no models
listed may use every model.
A decision model (Jev, Clef and the like) is a model too: a routing group
the key names asks its own decision model for every turn, whatever the key
+1 -1
View File
@@ -151,7 +151,7 @@ recorded as a prediction failure (`noPrediction`).
- What is done with a value found is the user's per kind (#1977, `redactActions` in settings, `Options.Actions`, set by `POST /api/settings/redact-actions`; a kind left out is masked). `redact.Warn` sends it as written: the masker tells it, with a placeholder no one remembers, and it isn't counted as masked. `redact.Block` masks it as any other, and the gateway holds the request back with a 400 that names the kind and the value's hint, never the value (`blocked`, `maskBlocked` in [`redact.go`](../../internal/gateway/redact.go)); nothing is sent and the record is kept as `Blocked` (`noteBlocked`). A value on the *Never mask* list (`redactAllow`, `Options.Allow`, `POST /api/settings/redact-allow`) goes as written when it is the whole value found, in any case, and isn't told; a longer value it is part of is masked. Settings → Privacy's *Try it* posts a text to `POST /api/masking/preview` ([`masking.go`](../../internal/gui/masking.go)), which masks it as a request would be (`redact.Preview`) and remembers nothing: its placeholders stand for nothing afterwards, its values aren't masked later as seen before, and it returns only the masked text and each hit's kind, finder, action, placeholder and hint. The page keeps the text in no storage.
- Each request that had anything masked is recorded as it goes to the vendor (`noteMasked` in [`masked.go`](../../internal/gateway/masked.go), from chat, the Codex backend, search, images, video, System One, embeddings and audio; count_tokens is masked and not recorded). The masker says what it swapped through `gwmw.Teller` (`JSONHits`, `TextHits`: each placeholder's kind, its finder, `redact.ByRule`, `ByYours`, `ByWord`, `ByModel` or `ByKnown`, and a hint of its first characters and its length), and [`internal/maskrec`](../../internal/maskrec/maskrec.go) keeps one line per request in a file per day under `~/.config/magpie/masking`, 30 days and 100 MB in all: the agent (the one usage records, `callerOf`, so a request another magpie passed on is named by the agent it came from, not as `magpie`; linkaww on Discord), session, provider, model, and each placeholder with its kind, finder, action and hint, never the value. A chat, an embedding or a video whose group can pass it to another member is held in memory until the request is over (`noteMaskedUntil`, `maskrec.Hold`), and its line names the provider and model the last try went to, not the first planned, which a failover may never have reached; the list sorts each day's lines by key, since a long request's line is written after later ones. The text around each placeholder as the vendor saw it is kept in memory only, for the last 400 records, and what a placeholder stood for only in the masker's own memory (`Teller.Value`); after a restart neither is there. A recent call (`Call.Masked`) and the route trace (`Route.Masked`) carry the counts and the record's key, which the Gateway and Routing pages' badge opens in Settings → Privacy (`/api/masking/*`, [`internal/gui/masking.go`](../../internal/gui/masking.go)). A masker without `Teller`, a plugin's, masks as before and records nothing. Under a test binary testenv isolated nothing is written (`maskrec.inTest`). The page's Clear records… (after a confirm) posts `/api/masking/clear`, and `maskrec.Clear` removes every day's file whole under the store's lock, with the in-memory text around placeholders; a day it can't remove stays listed and is named in the error. What the masker holds for each placeholder stays, so a placeholder still in an agent's context is put back in its answers.
- `DecidesModel` gives a 400 (`decisionModelRefused`; a decision group, `decisionGroupRefused`), and count_tokens gives the same 400 before the vendor is asked. For OpenRouter, a variant of a model its decisions list names (`inception/mercury-decide:free`, picked by hand) is a decision model too (`openRouterVariant`): OpenRouter lists the model once, and answered such a variant 400 "is a decisions model" on chat/completions (coeo91 on Discord).
- A gateway key held to some models (`keyHolds`, #882) gets a 403 for any other model. A decision model is one: `serveSystemOne` and the decision list another magpie asks for (`DecidersHeader`) hold the key to it, while a group the key names asks its own decider in `askJev` with no key check (`TestGatewayKeyHeldToAGroupKeepsItsDecider`); the key editor offers the decision models (`GET /api/caller-keys/models`, `decides`, `TestCallerKeyModelsOfferDeciders`, `gateway-key-deciders.test.cjs`).
- A gateway key held to some models (`keyHolds`, #882) gets a 403 for any other model. A routing group passes only through `groupAllowed`, which every route asks (the model lists' `entryAllowed`, `serve`, `countHeld`, embeddings, images, videos, decision groups, a subagent's and masking's route): a group of the user's own only when the key names it, whatever its members (kautism on Discord), a found group (`foundGroup`), or any group for a key that names accounts and no model (`Identity.AccountModels`), when the key may use every member; a bare name that is both a group of the user's the key may not use and a model it may use is that model for the key (`keyGroupFor`; `TestGatewayKeyGivenAModelIsNotGivenItsGroup`). A decision model is one: `serveSystemOne` and the decision list another magpie asks for (`DecidersHeader`) hold the key to it, while a group the key names asks its own decider in `askJev` with no key check (`TestGatewayKeyHeldToAGroupKeepsItsDecider`); the key editor offers the decision models (`GET /api/caller-keys/models`, `decides`, `TestCallerKeyModelsOfferDeciders`, `gateway-key-deciders.test.cjs`).
- A model the user disabled (#1867) gets a 403 for every caller (`idOff`), before anything is sent; see [Disabled models](#disabled-models).
- Sealed tasks (#619) are checked here. A Codex subagent's task its lead's `spawn_agent` sealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (`leadProvider`, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (`send_message`) goes back to the Responses provider that answered the lead's own conversation (`leadProvider` of the request's `conversationID`, #1237); otherwise it is refused before anyone is asked (`sealedReader`, `sealedTaskError`). A sealed message (`Message Type: MESSAGE`, not a task) that nobody asked can open is left out instead, an `input_text` note naming its sender in its place (`withoutSealedMessages`, #1613): a lead on a chat provider whose subagent is on one of Codex's own models goes on, as the subagent's final result still reaches it as text. Only a sealed task (`NEW_TASK`, or an item with neither header) is refused. Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversations `affinity.json` keeps, or the lead's last reply broken off, `unanswered`), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (`loggedAnswers`, #1367), and `leadFirst` reads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it. It also says what is sealed (`sealedTaskItself`, #1855): the task itself, `spawn_agent`'s `message`, which the backend returns sealed (`encrypted_function_args`) and Codex hands the subagent as it came, so `fork_turns="none"`, which only leaves the lead's turns out, doesn't help; nothing in it can be left out for the subagent to go on.
- A model set for Codex's subagents (`settings.CodexSubagentModel`, the Agents page's Codex "subagent model", willz on Discord) is put on a Codex subagent's request (`x-openai-subagent` read as `kind:collab_spawn`) before this check, whatever model its lead's `spawn_agent` asked for (`codexSubagentPick` in [`codex_subagent.go`](../../internal/gateway/codex_subagent.go)): in `codexBackend` for one of Codex's own bare models, which then goes through `serveAgent`, and in `serve` for any other. Any model magpie serves can be set (`provider.SetCodexSubagentModel`, #1633): a task handed as text (a lead magpie served on a chat provider, or multi-agent V1) is read by any model. A request carrying a task the ChatGPT backend sealed (`sealedTaskIn`: a sealed agent message that isn't a `MESSAGE`, which `withoutSealedMessages` leaves out) is put only on a ChatGPT account's model; set to another, the subagent stays on the model asked for, which the sealed gate below handles as with nothing set. When magpie doesn't serve the model set now, or a gateway key held to some models may not use it, the subagent goes on the model asked for too. The route trace keeps both models and the reason it stayed (`Route.Subagent`), and the Routing page's `kindWhy` says it. The lead's turns, titles and every other kind are never moved.
+10 -3
View File
@@ -158,9 +158,16 @@ type Identity struct {
Limit *Limit
More []Limit
Models []string
Accounts []string
Quotas bool
ReadOnly bool
// AccountModels says Models are only HeldModels' "<provider>/*" of
// a key that names accounts and no model, nor does the key it was
// issued under: every model of those accounts' providers is the
// key's, a routing group of them alone too. A key that lists models
// is given a routing group of the user's only by naming it (kautism
// on Discord).
AccountModels bool
Accounts []string
Quotas bool
ReadOnly bool
// Expires is when the key stops working, its issuer's expiry if
// sooner; zero for never.
Expires time.Time
+2 -1
View File
@@ -256,7 +256,7 @@ func Check(secret string) (Identity, error) {
// identityOf is who k is, folded into its issuer when it has one.
func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Accounts: k.Accounts, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Expires: k.Expires, Issues: k.Issues && k.Issuer == ""}
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), AccountModels: len(k.Models) == 0 && len(k.Accounts) > 0, Accounts: k.Accounts, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Expires: k.Expires, Issues: k.Issues && k.Issuer == ""}
// the default key as Default tells it: marked LAN, or the id the
// settings name (settings read only for an unmarked key)
who.Default = k.LAN || (k.ID != "" && settings.Load().LANKeyID == k.ID)
@@ -269,6 +269,7 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
}
p := keys[j]
pModels := HeldModels(p.Models, p.Accounts)
who.AccountModels = len(k.Models) == 0 && len(p.Models) == 0 && (len(k.Accounts) > 0 || len(p.Accounts) > 0)
if len(pModels) > 0 {
if who.Models = foldModels(who.Models, pModels); len(who.Models) == 0 {
return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q may use none of its models now: the key it was issued under no longer lets it", k.Name)}
+2 -2
View File
@@ -2071,7 +2071,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// spelling of a group's model (#750) — is that group, as asked for or
// as an agent's config names its stand-in
grouped := func(m string) string {
if id, ok := provider.GroupFor(m); ok {
if id, ok := keyGroupFor(r, m); ok {
return id
}
if id, ok := provider.AutoStandIn(m); ok {
@@ -2222,7 +2222,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
r = heldByGroup(r, g)
}
// a gateway key held to some models (#882) is refused another, or a
// group it doesn't name with one it may not use in it
// group it wasn't given (groupAllowed)
keyWho, keyHeld := keyHolds(r)
_, accHeld := accountHolds(r)
chose, _ := r.Context().Value(magpieChoseKey{}).(bool)
+49 -7
View File
@@ -19,8 +19,12 @@ import (
// called it. A routing group passes when the key names it, "group/<id>"
// (or "group/*", every group), a group magpie found by its auto/<model>
// too, either id passing for the other (allows), and then every member of
// it does, through it; else only when every model in it does. A group the
// key names inside one it doesn't counts for its own members.
// it does, through it. A group of the user's own the key doesn't name is
// never the key's, however few models it has and all of them the key's
// (kautism on Discord: a key given gemini 3.8 was shown, and could use, a
// group the user made of gemini 3.8 alone, a group never handed out); a
// group magpie found, one model several providers serve, passes when
// every model in it does, as it is that model.
// magpieChoseKey marks, in a request's context, a call magpie makes for a
// model the user picked in its settings rather than the caller (a web
@@ -109,9 +113,47 @@ func groupNamed(who access.Identity, g provider.Group) bool {
}
// groupAllowed says the key may use the routing group g: it names it, or
// may use every member of it.
// g is a group magpie found (foundGroup) and the key may use every member
// of it. A group of the user's own that a key listing models doesn't name
// is not its, every member its or not: what the key lists is what it was
// given (kautism). A key that names accounts and no model was given every
// model of their providers (access.HeldModels, Linka), and a group of
// those alone is one of them, as before.
// Every route asks this: the model lists (entryAllowed), a request on
// each API, count_tokens, embeddings, images, videos, the decision
// groups, a subagent's and masking's route.
func groupAllowed(who access.Identity, g provider.Group, ms []provider.Member) bool {
return groupNamed(who, g) || membersAllowed(who, ms)
return groupNamed(who, g) || (foundGroup(g) || who.AccountModels) && membersAllowed(who, ms)
}
// foundGroup says g is a group magpie found (one model several providers
// serve, auto/<model>), the user's changes to it kept or not.
func foundGroup(g provider.Group) bool {
return g.Auto || strings.HasPrefix(g.ID, "auto-")
}
// keyGroupFor is provider.GroupFor for the request's gateway key: a bare
// name that is a routing group of the user's the key may not use, and a
// model it may use, is that model for the key, as it would be were there
// no such group — the key is held away from the group, not from the model
// (a group the user named gemini-3.8, a key given google/gemini-3.8
// asking for gemini-3.8). Every other name is GroupFor's.
func keyGroupFor(r *http.Request, id string) (string, bool) {
gid, ok := provider.GroupFor(id)
if !ok {
return gid, ok
}
who, held := keyHolds(r)
if !held {
return gid, true
}
if g, ms, found := provider.FindGroup(gid); !found || groupAllowed(who, g, ms) {
return gid, true
}
if p, model, served := provider.Resolve(id); served && !provider.IsGroupRef(id) && modelAllowed(who, p, model) {
return "", false
}
return gid, true
}
// groupKeeps is the members of g a request through it may go to for the
@@ -467,14 +509,14 @@ func keyAccountNames(who access.Identity) string {
// for counting tokens on one it may not use, as it would be refused
// serving it: Anthropic's count_tokens and Gemini's :countTokens, id the
// model as each asks it, resolved — a bare group's name, an auto group's
// stand-in — and a group judged by its members. proto is the API the
// error is answered on.
// stand-in — and a group judged as a request to it is (groupAllowed).
// proto is the API the error is answered on.
func countHeld(w http.ResponseWriter, r *http.Request, proto provider.Protocol, id string) bool {
keyWho, held := keyHolds(r)
if !held {
return false
}
if gid, ok := provider.GroupFor(id); ok {
if gid, ok := keyGroupFor(r, id); ok {
id = gid
}
if sid, ok := provider.AutoStandIn(id); ok {
+4 -3
View File
@@ -179,11 +179,12 @@ func TestKeyListSeesChangesNextRequest(t *testing.T) {
if got := listed(); !slices.Equal(got, []string{"gemini:plan/m1", "plan/m1"}) {
t.Fatalf("held to plan/*: %v", got)
}
// g loses spare's member: every member is the key's, and it is back
// g loses spare's member: every member is the key's, but the key was
// never given g (kautism), so it stays out
if err := provider.SaveGroup(provider.Group{ID: "g", Name: "G", Members: []string{"plan/m1"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
if got := listed(); !slices.Equal(got, []string{"gemini:group/g", "gemini:plan/m1", "group/g", "plan/m1"}) {
if got := listed(); !slices.Equal(got, []string{"gemini:plan/m1", "plan/m1"}) {
t.Fatalf("group g narrowed: %v", got)
}
// held to plan's key, which is then set to serve another model only
@@ -199,7 +200,7 @@ func TestKeyListSeesChangesNextRequest(t *testing.T) {
if err := provider.SetAccountModels("plan", provider.KeyID("k"), nil); err != nil {
t.Fatal(err)
}
if got := listed(); len(got) != 4 {
if got := listed(); !slices.Equal(got, []string{"gemini:plan/m1", "plan/m1"}) {
t.Fatalf("plan's key serves m1 again: %v", got)
}
}
+126 -7
View File
@@ -57,7 +57,8 @@ func TestGatewayKeyModelsHoldAKey(t *testing.T) {
}
return ids
}
if ids := listed(secrets[0]); !slices.Contains(ids, "plan/m1") || !slices.Contains(ids, "group/solo") || slices.Contains(ids, "spare/m2") || slices.Contains(ids, "group/both") {
// Solo, of plan/m1 alone, is a group the key wasn't given (kautism)
if ids := listed(secrets[0]); !slices.Contains(ids, "plan/m1") || slices.Contains(ids, "group/solo") || slices.Contains(ids, "spare/m2") || slices.Contains(ids, "group/both") {
t.Fatalf("held key lists %v", ids)
}
if ids := listed(secrets[1]); !slices.Contains(ids, "spare/m2") || !slices.Contains(ids, "group/both") {
@@ -73,7 +74,7 @@ func TestGatewayKeyModelsHoldAKey(t *testing.T) {
chat := func(secret, model string) *httptest.ResponseRecorder {
return do(secret, "POST", "/v1/chat/completions", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`)
}
for _, model := range []string{"spare/m2", "m2", "group/both"} {
for _, model := range []string{"spare/m2", "m2", "group/both", "group/solo"} {
w := chat(secrets[0], model)
var e struct {
Error struct{ Message, Type string }
@@ -99,7 +100,7 @@ func TestGatewayKeyModelsHoldAKey(t *testing.T) {
if w.Code != 403 || a.Type != "error" || a.Error.Type != "permission_error" {
t.Fatal("anthropic refusal", w.Code, w.Body.String())
}
for _, model := range []string{"plan/m1", "m1", "group/solo"} {
for _, model := range []string{"plan/m1", "m1"} {
if w := chat(secrets[0], model); w.Code != 200 || !strings.Contains(w.Body.String(), "from-plan") {
t.Fatalf("%s: %d %s", model, w.Code, w.Body.String())
}
@@ -157,8 +158,8 @@ func TestGatewayKeyModelsMatchTheServingProvider(t *testing.T) {
// Discord), is shown the group and may use it, every member of it going
// through it — the next one too when the first fails — but not the
// members asked by name, a group it doesn't name, or a fallback outside
// the group; "group/*" names every group, and a group named inside one
// it doesn't name counts for its own members.
// the group; "group/*" names every group, and a group the key doesn't
// name is not its for a group named inside it.
func TestGatewayKeyModelsNameAGroup(t *testing.T) {
fresh(t)
plan := &fake{t: t, ctype: "application/json", reply: `{"id":"from-plan","choices":[]}`}
@@ -206,7 +207,7 @@ func TestGatewayKeyModelsNameAGroup(t *testing.T) {
if ids := listed(secrets[1]); !slices.Equal(ids, []string{"group/both", "group/outer", "group/solo"}) {
t.Fatalf("a key naming group/* lists %v", ids)
}
if ids := listed(secrets[2]); !slices.Contains(ids, "group/outer") || !slices.Contains(ids, "group/solo") || slices.Contains(ids, "plan/m1") || slices.Contains(ids, "group/both") {
if ids := listed(secrets[2]); slices.Contains(ids, "group/outer") || !slices.Contains(ids, "group/solo") || slices.Contains(ids, "plan/m1") || slices.Contains(ids, "group/both") {
t.Fatalf("a key naming group/solo and spare/m2 lists %v", ids)
}
chat := func(secret, model string) *httptest.ResponseRecorder {
@@ -225,7 +226,8 @@ func TestGatewayKeyModelsNameAGroup(t *testing.T) {
{0, "group/solo", 403, ""},
{1, "group/solo", 200, "from-plan"},
{1, "plan/m1", 403, ""},
{2, "group/outer", 200, "from-plan"},
{2, "group/solo", 200, "from-plan"},
{2, "group/outer", 403, ""},
{2, "group/both", 403, ""},
} {
w := chat(secrets[c.key], c.model)
@@ -509,3 +511,120 @@ func TestGatewayKeyHeldToAGroupKeepsItsDecider(t *testing.T) {
t.Fatal("Jev picked for the key isn't listed to it")
}
}
// kautism on Discord: a gateway key given one model, gemini 3.8, was
// shown — and could use — a routing group the user made of gemini 3.8
// alone, though the user never gave the key that group. A group of the
// user's own is the key's only when it names it, on every route: the
// model lists, chat completions, Anthropic's messages and count_tokens.
// A bare name that is both such a group and the key's model is the model.
// A group magpie found, one model two providers serve, is the key's when
// it may use both, as before; a key naming the group is given it.
func TestGatewayKeyGivenAModelIsNotGivenItsGroup(t *testing.T) {
fresh(t)
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
google := &fake{t: t, ctype: "application/json", reply: `{"id":"from-google","choices":[]}`}
vertex := &fake{t: t, ctype: "application/json", reply: `{"id":"from-vertex","choices":[]}`}
for _, x := range []struct {
p provider.Provider
f *fake
}{
{provider.Provider{ID: "google", Name: "Google", Key: "k", Models: []string{"gemini-3.8", "gemini-3.1-pro"}}, google},
{provider.Provider{ID: "vertex", Name: "Vertex", Key: "k", Models: []string{"gemini-3.8"}}, vertex},
} {
up := httptest.NewServer(x.f)
t.Cleanup(up.Close)
x.p.Chat = up.URL + "/v1"
if err := provider.Save(x.p); err != nil {
t.Fatal(err)
}
}
for _, g := range []provider.Group{
{ID: "only-38", Name: "Only 3.8", Members: []string{"google/gemini-3.8"}, Routing: provider.Ordered},
{ID: "gemini-3-8", Name: "Gemini 3.8", Members: []string{"google/gemini-3.8"}, Routing: provider.Ordered},
} {
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
}
keys, secrets := newCaller(t, "One model", "Both providers", "Given the group")
for i, ms := range [][]string{{"google/gemini-3.8"}, {"google/gemini-3.8", "vertex/gemini-3.8"}, {"google/gemini-3.8", "group/only-38"}} {
if _, err := access.Update("models-key", access.Change{Key: keys[i].ID, Models: ms}); err != nil {
t.Fatal(err)
}
}
h := New().Handler()
do := func(secret, path, body string) *httptest.ResponseRecorder {
method := "POST"
if body == "" {
method = "GET"
}
r := httptest.NewRequest(method, path, strings.NewReader(body))
r.Header.Set("Authorization", "Bearer "+secret)
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
listed := func(secret string) []string {
var l struct{ Data []struct{ ID string } }
w := do(secret, "/v1/models", "")
if err := json.Unmarshal(w.Body.Bytes(), &l); err != nil {
t.Fatal(w.Body.String())
}
var ids []string
for _, m := range l.Data {
ids = append(ids, m.ID)
}
slices.Sort(ids)
return ids
}
chat := func(secret, model string) *httptest.ResponseRecorder {
return do(secret, "/v1/chat/completions", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`)
}
if ids := listed(secrets[0]); !slices.Equal(ids, []string{"google/gemini-3.8"}) {
t.Fatalf("a key given google/gemini-3.8 lists %v", ids)
}
if w := do(secrets[0], "/v1/models/group/only-38", ""); w.Code == 200 {
t.Fatal("a key found a group it wasn't given", w.Body.String())
}
for _, model := range []string{"group/only-38", "group/gemini-3-8", "Only 3.8", "google/gemini-3.1-pro"} {
if w := chat(secrets[0], model); w.Code != 403 {
t.Fatalf("chat %s: %d %s", model, w.Code, w.Body.String())
}
msg := `{"model":"` + model + `","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`
if w := do(secrets[0], "/v1/messages", msg); w.Code != 403 {
t.Fatalf("messages %s: %d %s", model, w.Code, w.Body.String())
}
if w := do(secrets[0], "/v1/messages/count_tokens", msg); w.Code != 403 {
t.Fatalf("count_tokens %s: %d %s", model, w.Code, w.Body.String())
}
}
if google.calls != 0 || vertex.calls != 0 {
t.Fatal("a refused request reached a provider", google.calls, vertex.calls)
}
// its model, by id and bare — the bare name the group Gemini 3.8 goes
// by too — is served, and counted
for _, model := range []string{"google/gemini-3.8", "gemini-3.8"} {
if w := chat(secrets[0], model); w.Code != 200 || !strings.Contains(w.Body.String(), "from-google") {
t.Fatalf("chat %s: %d %s", model, w.Code, w.Body.String())
}
if w := do(secrets[0], "/v1/messages/count_tokens", `{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`); w.Code != 200 {
t.Fatalf("count_tokens %s: %d %s", model, w.Code, w.Body.String())
}
}
// a group magpie found: one model of both providers
if ids := listed(secrets[1]); !slices.ContainsFunc(ids, func(id string) bool { return strings.HasPrefix(id, "auto/") }) || slices.Contains(ids, "group/only-38") || slices.Contains(ids, "group/gemini-3-8") {
t.Fatalf("a key given both providers' gemini-3.8 lists %v", ids)
}
if w := chat(secrets[1], "group/auto-gemini-3-8"); w.Code != 200 {
t.Fatalf("the found group: %d %s", w.Code, w.Body.String())
}
// given the group, it is the key's
if ids := listed(secrets[2]); !slices.Equal(ids, []string{"google/gemini-3.8", "group/only-38"}) {
t.Fatalf("a key given group/only-38 lists %v", ids)
}
if w := chat(secrets[2], "group/only-38"); w.Code != 200 || !strings.Contains(w.Body.String(), "from-google") {
t.Fatalf("a group given: %d %s", w.Code, w.Body.String())
}
}