diff --git a/internal/access/access.go b/internal/access/access.go index 84f00743e..4b717ca26 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -145,6 +145,11 @@ type Key struct { // "/*" or a group's "group/"; none for every model, // unless it lists accounts: then its accounts' providers' (HeldModels). Models []string `json:"models,omitempty"` + // Aliases are the names the key gives models (tsingchao on X): a name + // its client asks by, the model "/" it stands for. + // /v1/models lists the name in the model's place and a request by it + // goes to the model, which the key's Models must allow. + Aliases map[string]string `json:"aliases,omitempty"` // Accounts are the accounts and keys the key may use (#905), as // "/": a signed-in account by its stable id, a // key by its fingerprint; none for every account, as keys always did. @@ -200,6 +205,8 @@ type Identity struct { Limit *Limit More []Limit Models []string + // Aliases are Key.Aliases; an issued key has none. + Aliases map[string]string // AccountModels says Models are only HeldModels' "/*" 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 @@ -418,6 +425,8 @@ type Change struct { Index *int `json:"index,omitempty"` // Models is what "models-key" sets; none lets the key use every model. Models []string `json:"models,omitempty"` + // Aliases is what "aliases-key" sets; none takes the names away. + Aliases map[string]string `json:"aliases,omitempty"` // Accounts is what "accounts-key" sets (#905); none lets the key use // every account and key. Accounts []string `json:"accounts,omitempty"` @@ -583,6 +592,18 @@ func Update(action string, in Change) (string, error) { return "", err } keys[i].Models = ms + case "aliases-key": + as, err := CleanAliases(in.Aliases) + if err != nil { + return "", err + } + held := HeldModels(keys[i].Models, keys[i].Accounts) + for name, target := range as { + if !ModelAllowed(held, target) { + return "", fmt.Errorf("The key may not use %s, so it can't name it %s: add it to the key's models first", target, name) + } + } + keys[i].Aliases = as case "accounts-key": as, err := CleanAccounts(in.Accounts) if err != nil { @@ -647,7 +668,7 @@ func Update(action string, in Change) (string, error) { default: return "", fmt.Errorf("unknown key action %q", action) } - if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "access-key" && action != "issuer-key" && action != "move-key" { + if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "access-key" && action != "issuer-key" && action != "move-key" { mirror = &keys[i] } } diff --git a/internal/access/issue.go b/internal/access/issue.go index 417f07b81..134044811 100644 --- a/internal/access/issue.go +++ b/internal/access/issue.go @@ -103,6 +103,9 @@ func IssueKey(in Issue) (Issued, error) { if err != nil { return Issued{}, err } + if slices.ContainsFunc(models, IsPattern) { + return Issued{}, errors.New("An issued key's models are named one by one or with *: a re: pattern is for the keys you make yourself") + } var accounts []string if len(in.Accounts) > 0 { if accounts, err = CleanAccounts(in.Accounts); err != nil { @@ -349,7 +352,7 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) { return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q names an account group, and magpie can't read its account groups now: %v", k.Name, err)} } k.Accounts = accounts - 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 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency} + who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency} // 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) diff --git a/internal/access/model_pattern_test.go b/internal/access/model_pattern_test.go new file mode 100644 index 000000000..2f5bb660a --- /dev/null +++ b/internal/access/model_pattern_test.go @@ -0,0 +1,60 @@ +package access + +import ( + "slices" + "testing" +) + +func TestModelPatternsAreRegularExpressions(t *testing.T) { + for _, c := range []struct { + pat, id string + want bool + }{ + {"re:^gpt-", "openai/gpt-5", true}, + {"re:^openai/gpt-", "openai/gpt-5", true}, + {"re:^GPT-5$", "openai/gpt-5", true}, + {"re:^gpt-", "openai/o3", false}, + {"re:gpt", "group/gpt-fans", false}, // never a routing group + {"RE:^gpt-", "openai/gpt-5", true}, + {"re:(", "openai/gpt-5", false}, // a bad one names nothing, never all + } { + if got := ModelAllowed([]string{c.pat}, c.id); got != c.want { + t.Errorf("%s on %s: %v", c.pat, c.id, got) + } + } +} + +func TestCleanModelsRefusesABadPattern(t *testing.T) { + for _, bad := range []string{"re:(", "re:", "re:[a-", "re: "} { + if _, err := CleanModels([]string{"openai/gpt-5", bad}); err == nil { + t.Errorf("kept %q", bad) + } + } + got, err := CleanModels([]string{" re:^gpt-.* ", "openai/*", "RE:^GPT-.*"}) + if err != nil || !slices.Equal(got, []string{"re:^gpt-.*", "openai/*"}) { + t.Fatalf("%v %v", got, err) + } +} + +func TestCleanAliases(t *testing.T) { + got, err := CleanAliases(map[string]string{" fast ": " openai/gpt-5 ", "": ""}) + if err != nil || len(got) != 1 || got["fast"] != "openai/gpt-5" { + t.Fatalf("%v %v", got, err) + } + for _, bad := range []map[string]string{ + {"a b": "openai/gpt-5"}, {"re:x": "openai/gpt-5"}, {"x*": "openai/gpt-5"}, + {"fast": "gpt-5"}, {"fast": "openai/*"}, {"fast": "re:^gpt"}, {"openai/gpt-5": "openai/GPT-5"}, + {"fast": ""}, {"": "openai/gpt-5"}, {"Fast": "openai/gpt-5", "fast": "openai/gpt-4"}, + } { + if _, err := CleanAliases(bad); err == nil { + t.Errorf("kept %v", bad) + } + } +} + +func TestIssuedKeyTakesNoPattern(t *testing.T) { + _, err := IssueKey(Issue{Name: "x", TTL: 3600e9, Models: []string{"re:^gpt-"}}) + if err == nil { + t.Fatal("issued a key with a pattern") + } +} diff --git a/internal/access/models.go b/internal/access/models.go index 734006e89..189ce0e67 100644 --- a/internal/access/models.go +++ b/internal/access/models.go @@ -2,10 +2,13 @@ package access import ( "errors" + "fmt" + "maps" "regexp" "slices" "strings" "sync" + "unicode" ) // CleanModels is a key's model list as kept (#882): each pattern trimmed, @@ -19,12 +22,20 @@ func CleanModels(in []string) ([]string, error) { if m == "" || slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, m) }) { continue } - if !strings.Contains(m, "/") || strings.HasPrefix(m, "/") || strings.HasSuffix(m, "/") { - return nil, errors.New("A key's model is / or /*, like openai/gpt-5 or anthropic/*: " + m) - } if len(m) > 300 { return nil, errors.New("A key's model is at most 300 characters") } + if IsPattern(m) { + // refused here, never read as "every model" or as none later + if _, err := compilePattern(m); err != nil { + return nil, fmt.Errorf("A key's model pattern %s is not a valid regular expression: %v", m, err) + } + out = append(out, m) + continue + } + if !strings.Contains(m, "/") || strings.HasPrefix(m, "/") || strings.HasSuffix(m, "/") { + return nil, errors.New("A key's model is /, /*, or a pattern re:, like openai/gpt-5, anthropic/* or re:^gpt-5: " + m) + } out = append(out, m) } if len(out) > 500 { @@ -86,12 +97,19 @@ func (who Identity) Allows(ids ...string) bool { // ModelAllowed says id ("/") matches one of patterns, // letter case aside; a "*" in a pattern stands for any run of characters, -// slashes too. No patterns allow every model. +// slashes too, and "re:" is a regular expression +// (PatternPrefix). No patterns allow every model. func ModelAllowed(patterns []string, id string) bool { if len(patterns) == 0 { return true } for _, p := range patterns { + if IsPattern(p) { + if patternMatches(p, id) { + return true + } + continue + } if strings.EqualFold(p, id) { return true } @@ -136,3 +154,121 @@ func compileGlob(p string) *regexp.Regexp { } return regexp.MustCompile("(?is)^" + strings.Join(parts, ".*") + "$") } + +// PatternPrefix starts a model entry that is a regular expression +// (tsingchao on X): "re:^gpt-5" holds a key to every model whose id has +// that match. Go's RE2 syntax, letter case aside, unanchored (write ^ and $ +// to anchor), tried on the whole id "/" and on the model +// alone, so "re:^gpt-" names GPT models of any provider. It never names a +// routing group ("group/" does that), so a pattern like "re:.*" +// doesn't hand a key every group of the user's own. +const PatternPrefix = "re:" + +// IsPattern says the entry is a regular expression (PatternPrefix). +func IsPattern(p string) bool { + return len(p) >= len(PatternPrefix) && strings.EqualFold(p[:len(PatternPrefix)], PatternPrefix) +} + +func compilePattern(p string) (*regexp.Regexp, error) { + expr := strings.TrimSpace(p[len(PatternPrefix):]) + if expr == "" { + return nil, errors.New("it is empty") + } + return regexp.Compile("(?i)" + expr) +} + +var patterns struct { + sync.Mutex + m map[string]*regexp.Regexp // nil for one that doesn't compile +} + +// patternMatches says id is one the regular expression entry p names. An +// entry that doesn't compile (CleanModels refuses it, so only a file +// edited by hand has one) names no model: it never lets a key off to all. +func patternMatches(p, id string) bool { + if len(id) >= 6 && strings.EqualFold(id[:6], "group/") { + return false + } + patterns.Lock() + re, ok := patterns.m[p] + patterns.Unlock() + if !ok { + re, _ = compilePattern(p) + patterns.Lock() + if patterns.m == nil || len(patterns.m) >= maxGlobs { + patterns.m = map[string]*regexp.Regexp{} + } + patterns.m[p] = re + patterns.Unlock() + } + if re == nil { + return false + } + if re.MatchString(id) { + return true + } + if _, model, ok := strings.Cut(id, "/"); ok { + return re.MatchString(model) + } + return false +} + +// MaxAliases is the most model names a key may give. +const MaxAliases = 200 + +// CleanAliases is a key's model names as kept: each name a key's client +// asks by, mapped to the model it is, "/" or a routing +// group "group/" (tsingchao on X). A name is one word of at most 120 +// characters that is no pattern. +func CleanAliases(in map[string]string) (map[string]string, error) { + if len(in) > MaxAliases { + return nil, fmt.Errorf("A key can name at most %d models", MaxAliases) + } + out := map[string]string{} + for name, target := range in { + name, target = strings.TrimSpace(name), strings.TrimSpace(target) + if name == "" && target == "" { + continue + } + if name == "" || target == "" { + return nil, errors.New("A model name needs both the name and the model it stands for") + } + if len(name) > 120 || strings.ContainsFunc(name, func(r rune) bool { return unicode.IsSpace(r) || unicode.IsControl(r) || r == '*' }) || IsPattern(name) { + return nil, errors.New("A model name is one word of at most 120 characters, with no * or re: pattern: " + name) + } + if !strings.Contains(target, "/") || strings.HasPrefix(target, "/") || strings.HasSuffix(target, "/") || strings.Contains(target, "*") || IsPattern(target) || len(target) > 300 { + return nil, errors.New("A model name stands for one model, / like openai/gpt-5: " + target) + } + if strings.EqualFold(name, target) { + return nil, errors.New("A model name must differ from the model: " + name) + } + if slices.ContainsFunc(slices.Collect(maps.Keys(out)), func(o string) bool { return strings.EqualFold(o, name) }) { + return nil, errors.New("A model name is given once: " + name) + } + out[name] = target + } + if len(out) == 0 { + return nil, nil + } + return out, nil +} + +// AliasFor is the model a name the key gives stands for, letter case aside. +func (who Identity) AliasFor(name string) (string, bool) { + for a, t := range who.Aliases { + if strings.EqualFold(a, name) { + return t, true + } + } + return "", false +} + +// AliasOf is the name the key gives the model id, if it does (case aside). +func (who Identity) AliasOf(id string) (string, bool) { + for a, t := range who.Aliases { + if strings.EqualFold(t, id) { + return a, true + } + } + return "", false +} diff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.go index d0833c750..b52913f9b 100644 --- a/internal/cli/gateway_keys_cli.go +++ b/internal/cli/gateway_keys_cli.go @@ -34,6 +34,10 @@ func gatewayKeysTo(out io.Writer, args []string) error { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyModels(out, args[1:]) } + if action == "aliases" { + access.MigrateLegacyLANKeyBestEffort() + return gatewayKeyAliases(out, args[1:]) + } if action == "accounts" { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyAccounts(out, args[1:]) @@ -102,7 +106,7 @@ func gatewayKeysTo(out io.Writer, args []string) error { args = args[:2] } if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) { - return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/* ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") + return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate [--key | --key -] | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads] [--model /|/* ...]] | models [all | /|/*|re: ...] | aliases [none | =/ ...] | accounts [all | /|/ ...] | quotas [on | off] | concurrency [ | off] | mcp [all | none | |/ ...] | access [read-only | full] | move | issue --ttl [--name ] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from ] | issuer [on | off] | oidc [list | add --key --repo owner/name … | remove ]") } switch action { case "list", "add", "rotate", "remove": @@ -482,6 +486,53 @@ func gatewayKeyModels(out io.Writer, args []string) error { return err } +// gatewayKeyAliases shows or sets the names a key gives models +// (tsingchao on X): +// +// magpie gateway-key aliases its names +// magpie gateway-key aliases none no names +// magpie gateway-key aliases fast=openai/gpt-5 ... only these +func gatewayKeyAliases(out io.Writer, args []string) error { + if len(args) == 0 { + return fmt.Errorf("usage: magpie gateway-key aliases [none | =/ ...]") + } + id := args[0] + if len(args) > 1 { + as := map[string]string{} + if !(len(args) == 2 && args[1] == "none") { + for _, a := range args[1:] { + name, target, ok := strings.Cut(a, "=") + if !ok { + return fmt.Errorf("usage: magpie gateway-key aliases [none | =/ ...]: %q has no =", a) + } + as[name] = target + } + } + if _, err := access.Update("aliases-key", access.Change{Key: id, Aliases: as}); err != nil { + return err + } + } + keys, err := access.List() + if err != nil { + return err + } + i := slices.IndexFunc(keys, func(k access.Key) bool { return k.ID == id }) + if i < 0 { + return fmt.Errorf("Key not found") + } + k := keys[i] + if len(k.Aliases) == 0 { + _, err = fmt.Fprintf(out, "%s: no model names\n", k.Name) + return err + } + for _, name := range slices.Sorted(maps.Keys(k.Aliases)) { + if _, err = fmt.Fprintf(out, "%s: %s = %s\n", k.Name, name, k.Aliases[name]); err != nil { + return err + } + } + return nil +} + // gatewayKeyMCP shows or sets the MCP servers and tools a key may use // (wakaka on Discord): // diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 6cebefa00..47a076b20 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1763,6 +1763,8 @@ func (s *Server) listModels(w http.ResponseWriter, r *http.Request) { data = append(data, m) } } + // the names the calling key gives models, where the models were + aliasNames(r, data) // ?format=text: the ids one a line, to paste into a client that takes // its models typed by hand, one a line, and asks no list of its own // (ZCode's custom provider), from a browser on another computer with @@ -1797,7 +1799,11 @@ func (s *Server) model(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, scienceObject(e, provider.LabelsFor(ScienceID, []provider.Entry{e})[0])) return } - writeJSON(w, 200, pricedModelObject(r, e)) + o := pricedModelObject(r, e) + if name, ok := access.Caller(r.Context()).AliasOf(e.ID); ok { + o["id"] = name + } + writeJSON(w, 200, o) return } } diff --git a/internal/gateway/key_aliases.go b/internal/gateway/key_aliases.go new file mode 100644 index 000000000..5caccb211 --- /dev/null +++ b/internal/gateway/key_aliases.go @@ -0,0 +1,113 @@ +package gateway + +import ( + "bytes" + "io" + "mime" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/yetone/magpie/internal/access" +) + +// A gateway key may give models names of its own (access.Key.Aliases, +// tsingchao on X): /v1/models lists the name where the model was, and a +// request that asks by the name is the request for the model. The one +// place that happens is identifyCaller, before any route reads the model: +// the body's "model" of a JSON request, a Gemini call's model in its path, +// and /v1/models/. Every route after it, and every check of the +// key's models, sees the real model, so the models the key may use hold +// the name as they hold the model. Replies say the real model. + +// maxAliasBody is the largest JSON body read to find its model: a larger +// one goes on as it came, which asks the model by its real id only. +const maxAliasBody = 32 << 20 + +// aliasRequest is r with the model a key's name stands for in the model's +// place: r as it is when the key gives no names, or r asks none of them. +func aliasRequest(r *http.Request, who access.Identity) *http.Request { + if len(who.Aliases) == 0 { + return r + } + switch r.Method { + case http.MethodGet: + if id, ok := strings.CutPrefix(r.URL.Path, "/v1/models/"); ok { + if real, ok := who.AliasFor(id); ok { + return withPath(r, "/v1/models/"+real) + } + } + case http.MethodPost, http.MethodPut, http.MethodPatch: + if call, ok := strings.CutPrefix(r.URL.Path, "/v1beta/models/"); ok { + if i := strings.LastIndex(call, ":"); i > 0 { + if real, ok := who.AliasFor(call[:i]); ok { + return withPath(r, "/v1beta/models/"+real+call[i:]) + } + } + return r + } + return aliasBody(r, who) + } + return r +} + +func withPath(r *http.Request, path string) *http.Request { + u := url.URL{} + if r.URL != nil { + u = *r.URL + } + u.Path, u.RawPath = path, "" + r = r.Clone(r.Context()) + r.URL = &u + return r +} + +// aliasBody swaps the model of a JSON body, every other byte as it was. +func aliasBody(r *http.Request, who access.Identity) *http.Request { + if r.Body == nil || r.Body == http.NoBody || r.Header.Get("Content-Encoding") != "" { + return r + } + // a form or a multipart body is no JSON; a client that says no type + // sends it + if mt, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")); mt != "" && !strings.HasSuffix(mt, "json") { + return r + } + orig := r.Body + buf, err := io.ReadAll(io.LimitReader(orig, maxAliasBody+1)) + rest := io.MultiReader(bytes.NewReader(buf), orig) + r.Body = struct { + io.Reader + io.Closer + }{rest, orig} + if err != nil || len(buf) > maxAliasBody { + return r + } + real, ok := who.AliasFor(modelOf(buf)) + if !ok { + return r + } + buf = rewriteModel(buf, real) + r.Body = io.NopCloser(bytes.NewReader(buf)) + r.ContentLength = int64(len(buf)) + r.Header = r.Header.Clone() + r.Header.Set("Content-Length", strconv.Itoa(len(buf))) + r.GetBody = nil + return r +} + +// aliasNames puts the names a key gives models where the models were in a +// list /v1/models gives it. +func aliasNames(r *http.Request, data []map[string]any) { + who := access.Caller(r.Context()) + if len(who.Aliases) == 0 { + return + } + for _, m := range data { + if id, _ := m["id"].(string); id != "" { + if name, ok := who.AliasOf(id); ok { + m["id"] = name + } + } + } +} diff --git a/internal/gateway/key_patterns_test.go b/internal/gateway/key_patterns_test.go new file mode 100644 index 000000000..3549abbe1 --- /dev/null +++ b/internal/gateway/key_patterns_test.go @@ -0,0 +1,191 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// keyDo sends a request with a gateway key to a handler. +func keyDo(h http.Handler, secret, method, path, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+secret) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +func keyListedIDs(t *testing.T, h http.Handler, secret, path string) []string { + t.Helper() + var l struct{ Data []struct{ ID string } } + w := keyDo(h, secret, "GET", path, "") + 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) + } + return ids +} + +// A key's model may be a regular expression, "re:" (tsingchao +// on X), and holds a key on every route that checks its models: the lists, +// a chat, Anthropic's and the Responses API, counting tokens, Gemini's +// path and System One's decision model. +func TestGatewayKeyModelPatternHoldsEveryRoute(t *testing.T) { + fresh(t) + plan := &fake{t: t, ctype: "application/json", reply: `{"id":"from-plan","choices":[]}`} + spare := &fake{t: t, ctype: "application/json", reply: `{"id":"from-spare","choices":[]}`} + twoProviders(t, plan, spare) + var decided int + jev := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + decided++ + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"answers":{"intent":{"choice":"bug"}},"usage":{"input_tokens":10,"output_tokens":2}}`) + })) + t.Cleanup(jev.Close) + if err := provider.Save(provider.Provider{ID: "jev", Name: "Jev", Key: "k", Decide: jev.URL + "/v1"}); err != nil { + t.Fatal(err) + } + if err := provider.SaveGroup(provider.Group{Name: "Both", Members: []string{"plan/m1", "spare/m2"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + keys, secrets := newCaller(t, "Held") + // the model alone, or the whole id + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"re:^m1$"}}); err != nil { + t.Fatal(err) + } + h := New().Handler() + ids := keyListedIDs(t, h, secrets[0], "/v1/models") + if !slices.Contains(ids, "plan/m1") || slices.Contains(ids, "spare/m2") || slices.Contains(ids, "group/both") { + t.Fatalf("lists %v", ids) + } + if w := keyDo(h, secrets[0], "GET", "/v1beta/models", ""); strings.Contains(w.Body.String(), "m2") || !strings.Contains(w.Body.String(), "m1") { + t.Fatalf("gemini list %s", w.Body.String()) + } + msg := `"messages":[{"role":"user","content":"hi"}]` + for _, c := range []struct{ path, body string }{ + {"/v1/chat/completions", `{"model":"spare/m2",` + msg + `}`}, + {"/v1/messages", `{"model":"spare/m2","max_tokens":10,` + msg + `}`}, + {"/v1/messages/count_tokens", `{"model":"spare/m2",` + msg + `}`}, + {"/v1/responses", `{"model":"spare/m2","input":"hi"}`}, + {"/v1/chat/completions", `{"model":"group/both",` + msg + `}`}, + {"/v1beta/models/spare/m2:generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`}, + {"/v1/systemone", `{"model":"jev/jev-latest","state":{"message":"hi"},"questions":{"intent":{"type":"choice"}}}`}, + } { + if w := keyDo(h, secrets[0], "POST", c.path, c.body); w.Code != 403 { + t.Fatalf("%s %s: %d %s", c.path, c.body, w.Code, w.Body.String()) + } + } + if plan.calls != 0 || spare.calls != 0 || decided != 0 { + t.Fatal("a refused request reached a provider", plan.calls, spare.calls, decided) + } + for _, c := range []struct{ path, body string }{ + {"/v1/chat/completions", `{"model":"plan/m1",` + msg + `}`}, + {"/v1/messages/count_tokens", `{"model":"plan/m1",` + msg + `}`}, + } { + if w := keyDo(h, secrets[0], "POST", c.path, c.body); w.Code != 200 { + t.Fatalf("%s: %d %s", c.path, w.Code, w.Body.String()) + } + } + // the decision model by a pattern of its own + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"re:^jev/jev-"}}); err != nil { + t.Fatal(err) + } + if w := keyDo(h, secrets[0], "POST", "/v1/systemone", `{"model":"jev/jev-latest","state":{"message":"hi"},"questions":{"intent":{"type":"choice"}}}`); w.Code != 200 || decided != 1 { + t.Fatalf("system one by pattern: %d %s", w.Code, w.Body.String()) + } + // a pattern that names everything names no routing group of the + // user's own: that is "group/" + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"re:.*"}}); err != nil { + t.Fatal(err) + } + if ids := keyListedIDs(t, h, secrets[0], "/v1/models"); !slices.Contains(ids, "plan/m1") || slices.Contains(ids, "group/both") { + t.Fatalf("re:.* lists %v", ids) + } + if w := keyDo(h, secrets[0], "POST", "/v1/chat/completions", `{"model":"group/both",`+msg+`}`); w.Code != 403 { + t.Fatalf("re:.* reached a group: %d %s", w.Code, w.Body.String()) + } +} + +// A key gives a model another name (tsingchao on X): /v1/models lists the +// name in the model's place, and a request by it goes to the model on +// every route that carries one: the body, Gemini's path, a model's URL. +func TestGatewayKeyAliasRenamesAModel(t *testing.T) { + fresh(t) + plan := &fake{t: t, ctype: "application/json", reply: `{"id":"from-plan","choices":[]}`} + spare := &fake{t: t, ctype: "application/json", reply: `{"id":"from-spare","choices":[]}`} + twoProviders(t, plan, spare) + keys, secrets := newCaller(t, "Named", "Plain") + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"plan/*"}}); err != nil { + t.Fatal(err) + } + // a model the key may not use can't be named + if _, err := access.Update("aliases-key", access.Change{Key: keys[0].ID, Aliases: map[string]string{"gpt-4": "spare/m2"}}); err == nil { + t.Fatal("named a model the key may not use") + } + if _, err := access.Update("aliases-key", access.Change{Key: keys[0].ID, Aliases: map[string]string{"gpt-4": "plan/m1"}}); err != nil { + t.Fatal(err) + } + h := New().Handler() + ids := keyListedIDs(t, h, secrets[0], "/v1/models") + if !slices.Contains(ids, "gpt-4") || slices.Contains(ids, "plan/m1") { + t.Fatalf("lists %v", ids) + } + if ids := keyListedIDs(t, h, secrets[1], "/v1/models"); slices.Contains(ids, "gpt-4") || !slices.Contains(ids, "plan/m1") { + t.Fatalf("another key lists %v", ids) + } + if w := keyDo(h, secrets[0], "GET", "/v1/models?format=text", ""); !strings.Contains(w.Body.String(), "gpt-4\n") { + t.Fatalf("text list %q", w.Body.String()) + } + if w := keyDo(h, secrets[0], "GET", "/v1/models/gpt-4", ""); w.Code != 200 || !strings.Contains(w.Body.String(), `"id":"gpt-4"`) { + t.Fatalf("one model: %d %s", w.Code, w.Body.String()) + } + msg := `"messages":[{"role":"user","content":"hi"}]` + for _, c := range []struct{ path, body string }{ + {"/v1/chat/completions", `{"model":"gpt-4",` + msg + `}`}, + {"/v1/chat/completions", `{"model":"GPT-4","stream":false,` + msg + `}`}, + {"/v1/messages", `{"model":"gpt-4","max_tokens":10,` + msg + `}`}, + {"/v1/messages/count_tokens", `{"model":"gpt-4",` + msg + `}`}, + } { + plan.calls = 0 + w := keyDo(h, secrets[0], "POST", c.path, c.body) + // the fake answers in chat's JSON, which Anthropic's route can't + // stream: what counts is that it reached the model, not a 403 + if w.Code == 403 || w.Code == 404 { + t.Fatalf("%s %s: %d %s", c.path, c.body, w.Code, w.Body.String()) + } + if strings.HasSuffix(c.path, "count_tokens") { + continue + } + if plan.calls != 1 || !strings.Contains(string(plan.got), `"m1"`) || strings.Contains(string(plan.got), "gpt-4") { + t.Fatalf("%s: the provider got %s", c.path, plan.got) + } + } + if w := keyDo(h, secrets[0], "POST", "/v1beta/models/gpt-4:countTokens", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`); w.Code != 200 || !strings.Contains(w.Body.String(), "totalTokens") { + t.Fatalf("gemini by name: %d %s", w.Code, w.Body.String()) + } + // another key has no such name + if w := keyDo(h, secrets[1], "POST", "/v1/chat/completions", `{"model":"gpt-4",`+msg+`}`); w.Code == 200 { + t.Fatalf("another key reached the name: %s", w.Body.String()) + } + // the name stands for a model the key still must be given: taken out + // of its models, the name is refused and no longer listed + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"spare/*"}}); err != nil { + t.Fatal(err) + } + if w := keyDo(h, secrets[0], "POST", "/v1/chat/completions", `{"model":"gpt-4",`+msg+`}`); w.Code != 403 { + t.Fatalf("name of a model the key lost: %d %s", w.Code, w.Body.String()) + } + if ids := keyListedIDs(t, h, secrets[0], "/v1/models"); slices.Contains(ids, "gpt-4") { + t.Fatalf("lists %v", ids) + } +} diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index 88ada726a..413a7ecbf 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -831,6 +831,8 @@ func identifyCaller(w http.ResponseWriter, r *http.Request) (*http.Request, bool } if ok { r = r.WithContext(access.WithIdentity(r.Context(), who)) + // the names the key gives models, before any route reads one + r = aliasRequest(r, who) } r.Header = r.Header.Clone() r.Header.Set("Authorization", "Bearer "+Token)