gateway: a gateway key can be held to some accounts (#905, LCorleone) — a key could burn any account a provider had: two coding plans of one vendor, and a key given to someone had them both. A key now keeps an optional list of accounts and keys (caller-keys.json "accounts", none = every account, so older files read as before): "<provider>/<account>", an account by its stable id — the login's, set once it is written and kept through renames (logins.json's savedLogin id, written by every write and stood in for by one made of the name until then, so an entry made before stands), a key by its fingerprint — every one a provider has when the list is set, and one gone later (a key rotated, an account signed out) kept as it is, matching nothing, holding the key closer, never wider. The command line and the menu name an account by who is signed in and keep its id. Routing holds a plan to the key's accounts beside its models: a candidate whose account the key may not use is left out — through a routing group the key names no less, for naming a group is not naming its accounts — the plan's order keeping step and its left-out list marking what the key held out (Weighed's held); magpie's own calls for the key — a web search, a picture described, a Codex title — are of the models the user picked, so the models don't hold them, but their spend lands on an account all the same, and the accounts hold them too. When every account or key a model has is one the key may not use, the request is refused with a 403 in the API's own error shape naming the model and the accounts the key may use, logged as a rejected call: after a usage cap's 429 and before an account barred for the model's, itself before the no-member 404. /v1/models and the Anthropic and Gemini lists show the key only the models an account or key it may use serves (a provider's account set not to serve one, #474, is none of the key's); a provider with no account and no key (a local ollama) is one the key names no account of — its models stay listed and its asks pass — while an entry kept after its provider lost its last account or key serves none, holding the key closer. The embeddings, images and videos endpoints hold their candidate to the key's accounts the same way, and counting tokens counts on those alone (the local estimate where it may use none). System One asks its decision model of an account or key the key may use — and sends on that key, of those in use, not the provider's first, which a key held to a later one was spent on; the videos and images keyed paths send on one the key may use too, held to a later key no longer refused for the first alone. Set it in the app's menu the models are picked in — the accounts after the models, an account by who is signed in with their plan in the note, a key by its fingerprint, what the CLI kept that no provider has now kept as "Not signed in now" — or magpie gateway-key accounts <id> codex/me@example.com openai/<key id> (all takes it off); gateway-key list has an ACCOUNTS column. en/zh/ja/de, the German "{n} accounts" main already had left to it rather than written twice. The images API's fan-out over a subscription's accounts is held to the key's accounts as one: one of the key's whose plan refuses to draw no longer hands the pen to an account it may not use, and the second in the order, when it is the key's, draws what the first may not (drawOnAccounts filters the candidates, the account pinned to with the account header told plainly when the key may not use it). The Routing view's left-out list says an account the key held out for what it is, not that its plan lacks the model, in Chinese, Japanese and German too; the key's badge names its accounts by who is signed in, not by the stable ids it keeps. (#932)

This commit is contained in:
july_lu
2026-10-06 10:51:50 +08:00
committed by GitHub
parent 6f1da2c585
commit 47c2382467
28 changed files with 1514 additions and 53 deletions
+25
View File
@@ -238,6 +238,8 @@ magpie gateway-key limit <id> # limit, used, left and reset
magpie gateway-key limit <id> off # no limit
magpie gateway-key models <id> openai/gpt-5 anthropic/* # only these models
magpie gateway-key models <id> all # every model
magpie gateway-key accounts <id> codex/me@example.com # only these accounts
magpie gateway-key accounts <id> all # every account
```
Each gateway key can have its own **limit**: a token total, an estimated
@@ -272,6 +274,29 @@ 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.
A gateway key can also be held to some **accounts** (#905): the accounts
and keys its requests may use, picked in the same menu after the models —
an account by who is signed in, a key by its fingerprint — or with
`magpie gateway-key accounts <id> codex/me@example.com openai/<key id>`
(`all` takes the restriction off). The list holds a key to some accounts
**of the providers it names**: a provider it names no account of, the key
uses as it always did. The list keeps an account by its stable id, kept
through renames, shown by who is signed in; one gone later — a key
rotated, an account signed out, an account of an agent that keeps no
logins renamed — is kept as it is, matching nothing, so the key is held
closer, never wider. A routing group the key names is its members'
through the accounts it may use only: naming a group is not naming its
accounts, and magpie's own calls for the key — a web search, a picture
described, a Codex title — are of the models the user picked, but their
spend lands on an account, so the accounts hold them too. When every
account or key behind a model is one the key may not use, the request is
refused with a 403 in the API's own error shape naming the model and the
accounts it may use, before a provider is asked — after a usage cap's 429
and before an account barred for the model's — and `/v1/models` lists the
key only the models an account or key it may use serves, the Routing
view's left-out list marking what the key held out. A key with no
accounts listed may use every account, as keys always did.
While LAN sharing is enabled, remote requests require an enabled gateway key
sent as Bearer, `x-api-key`, `x-goog-api-key` or `?key=`. Loopback remains
permissive: any token works, including a stale or disabled gateway key.
+1
View File
@@ -45,6 +45,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
- An unreadable `providers.json` is an error, never an empty list. Saving over an empty list would lose every provider.
- A switched-off provider (`Off`, #163) stays saved. The gateway says it is off instead of saying the model is unknown.
- A provider removed or switched off takes its models out of the catalog. [Agent wiring](agent-wiring.md)'s `Reseat` moves agents off them.
- A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as it always did. The list keeps an account by its stable id — `logins.json`'s `id`, set once written and kept through renames; the agents that keep no logins (and plugins) are known by a hash of the account's name, so an account renamed there drops out of a key's list, holding it closer, never wider. Storing an id for every agent is a larger change, not this one's.
## Verification
+60 -4
View File
@@ -1,6 +1,7 @@
package main
import (
"cmp"
"fmt"
"io"
"os"
@@ -12,6 +13,7 @@ import (
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/provider"
)
func gatewayKeys(args []string) error { return gatewayKeysTo(os.Stdout, args) }
@@ -30,8 +32,12 @@ func gatewayKeysTo(out io.Writer, args []string) error {
access.MigrateLegacyLANKeyBestEffort()
return gatewayKeyModels(out, args[1:])
}
if action == "accounts" {
access.MigrateLegacyLANKeyBestEffort()
return gatewayKeyAccounts(out, args[1:])
}
if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) {
return fmt.Errorf("usage: magpie gateway-key list | add <name> | rotate <id> | remove <id> | limit <id> [off | day|week|month [--tokens N] [--cost USD] [--cache-reads]] | models <id> [all | <provider>/<model>|<provider>/* ...]")
return fmt.Errorf("usage: magpie gateway-key list | add <name> | rotate <id> | remove <id> | limit <id> [off | day|week|month [--tokens N] [--cost USD] [--cache-reads]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...]")
}
switch action {
case "list", "add", "rotate", "remove":
@@ -45,8 +51,10 @@ func gatewayKeysTo(out io.Writer, args []string) error {
return err
}
w := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
fmt.Fprintln(w, "ID\tNAME\tSTATE\tGATEWAY KEY\tLIMIT\tMODELS")
fmt.Fprintln(w, "ID\tNAME\tSTATE\tGATEWAY KEY\tLIMIT\tMODELS\tACCOUNTS")
now := time.Now()
// an account is shown by who is signed in, kept by its stable id (#905)
names := provider.AccountNames()
for _, k := range keys {
state := "enabled"
if k.Off {
@@ -56,12 +64,20 @@ func gatewayKeysTo(out io.Writer, args []string) error {
if len(k.Models) > 0 {
models = strings.Join(k.Models, ",")
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", k.ID, strings.Map(func(r rune) rune {
accounts := "all"
if len(k.Accounts) > 0 {
shown := make([]string, len(k.Accounts))
for i, a := range k.Accounts {
shown[i] = cmp.Or(names[a], a)
}
accounts = strings.Join(shown, ",")
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", k.ID, strings.Map(func(r rune) rune {
if r < 32 || r == 127 {
return ' '
}
return r
}, k.Name), state, k.Masked, limitWords(k, now), models)
}, k.Name), state, k.Masked, limitWords(k, now), models, accounts)
}
return w.Flush()
}
@@ -246,3 +262,43 @@ func limitWords(k access.Key, now time.Time) string {
}
return s
}
// gatewayKeyAccounts shows or sets a key's account whitelist (#905): the
// accounts and keys it may use, "<provider>/<account>" — a signed-in
// account by its name, a key by its KeyID — every one when none are set.
func gatewayKeyAccounts(out io.Writer, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: magpie gateway-key accounts <id> [all | <provider>/<account>|<provider>/<key id> ...]")
}
id := args[0]
if len(args) > 1 {
as := args[1:]
if len(as) == 1 && as[0] == "all" {
as = nil
}
if _, err := access.Update("accounts-key", access.Change{Key: id, Accounts: 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.Accounts) == 0 {
_, err = fmt.Fprintf(out, "%s: every account\n", k.Name)
return err
}
// shown by who is signed in, kept by the account's stable id (#905)
names := provider.AccountNames()
shown := make([]string, len(k.Accounts))
for i, a := range k.Accounts {
shown[i] = cmp.Or(names[a], a)
}
_, err = fmt.Fprintf(out, "%s: only %s\n", k.Name, strings.Join(shown, ", "))
return err
}
+52
View File
@@ -8,6 +8,7 @@ import (
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
@@ -174,3 +175,54 @@ func TestGatewayKeyModelsCLI(t *testing.T) {
t.Fatal("all kept", keys[0].Models)
}
}
// magpie gateway-key accounts sets, shows and takes off a key's account
// whitelist, and refuses an account no provider has (#905). An account's
// stable id, named by who is signed in, is exercised against a real
// sign-in in the gateway's tests; a key's fingerprint is one here.
func TestGatewayKeyAccountsCLI(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", os.Getenv("HOME"))
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := settings.Save(settings.Settings{LAN: true}); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "http://127.0.0.1:1/v1", Keys: []provider.KeyAccount{{Key: "sk-1", Name: "First"}, {Key: "sk-2", Name: "Second"}}}); err != nil {
t.Fatal(err)
}
k1, k2 := provider.KeyID("sk-1"), provider.KeyID("sk-2")
call := func(args ...string) (string, error) {
var out bytes.Buffer
err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...))
return out.String(), err
}
if _, err := call("add", "Phone"); err != nil {
t.Fatal(err)
}
keys, _ := access.List()
id := keys[0].ID
if got, err := call("accounts", id); err != nil || got != "Phone: every account\n" {
t.Fatal(got, err)
}
// named by the name it is shown by, kept by its fingerprint
if got, err := call("accounts", id, "relay/First", "relay/"+k2); err != nil || got != "Phone: only relay/First, relay/Second\n" {
t.Fatal(got, err)
}
if keys, _ = access.List(); !slices.Equal(keys[0].Accounts, []string{"relay/" + k1, "relay/" + k2}) {
t.Fatal("kept", keys[0].Accounts)
}
if got, _ := call("list"); !strings.Contains(got, "ACCOUNTS") || !strings.Contains(got, "relay/First,relay/Second") {
t.Fatal(got)
}
for _, args := range [][]string{{"accounts"}, {"accounts", id, "sk-1"}, {"accounts", id, "relay/" + provider.KeyID("sk-9")}, {"accounts", "missing", "relay/First"}, {"accounts", "missing"}} {
if _, err := call(args...); err == nil {
t.Error("accepted", args)
}
}
if got, err := call("accounts", id, "all"); err != nil || got != "Phone: every account\n" {
t.Fatal(got, err)
}
if keys, _ = access.List(); keys[0].Accounts != nil {
t.Fatal("all kept accounts", keys[0].Accounts)
}
}
+18 -4
View File
@@ -42,14 +42,19 @@ type Key struct {
// Models are the models the key may use (#882): "<provider>/<model>",
// "<provider>/*" or a group's "group/<name>"; none for every model.
Models []string `json:"models,omitempty"`
// Accounts are the accounts and keys the key may use (#905), as
// "<provider>/<account>": a signed-in account by its stable id, a
// key by its fingerprint; none for every account, as keys always did.
Accounts []string `json:"accounts,omitempty"`
}
// Identity is the gateway key a request came with, its budget and the
// models it may use.
// Identity is the gateway key a request came with, its budget, the
// models and the accounts it may use.
type Identity struct {
KeyID, KeyName string
Limit *Limit
Models []string
Accounts []string
}
type contextKey struct{}
@@ -154,6 +159,9 @@ type Change struct {
Limit *Limit `json:"limit,omitempty"`
// Models is what "models-key" sets; none lets the key use every model.
Models []string `json:"models,omitempty"`
// Accounts is what "accounts-key" sets (#905); none lets the key use
// every account and key.
Accounts []string `json:"accounts,omitempty"`
}
// Update writes the named key store atomically.
@@ -214,6 +222,12 @@ func Update(action string, in Change) (string, error) {
return "", err
}
keys[i].Models = ms
case "accounts-key":
as, err := CleanAccounts(in.Accounts)
if err != nil {
return "", err
}
keys[i].Accounts = as
case "on-key", "off-key":
keys[i].Off = action == "off-key"
case "remove-key":
@@ -228,7 +242,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 != "models-key" {
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "models-key" && action != "accounts-key" {
mirror = &keys[i]
}
}
@@ -275,7 +289,7 @@ func Authenticate(secret string) (Identity, bool) {
if k.Off {
return Identity{}, false
}
return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, Models: k.Models}, true
return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, Models: k.Models, Accounts: k.Accounts}, true
}
}
s := settings.Load()
+83
View File
@@ -0,0 +1,83 @@
package access
import (
"errors"
"fmt"
"slices"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// CleanAccounts is a key's account list as kept (#905): each entry
// "<provider>/<account>", an account named by its stable id — or by the
// name it is shown by, resolved to that id, so the command line reads
// while the list keeps what a rename doesn't move — and a key by its
// fingerprint; trimmed, told apart in lower case as accounts are, each
// once, in the order given. Every account the entry names must be one
// its provider has now, so a typo can't quietly hold a key to nothing;
// one gone later — a key rotated, an account signed out — is kept as it
// is, matching nothing.
func CleanAccounts(in []string) ([]string, error) {
var out []string
for _, a := range in {
a = strings.TrimSpace(a)
if a == "" {
continue
}
pid, ref, ok := strings.Cut(a, "/")
if !ok || pid == "" || ref == "" {
return nil, errors.New("A key's account is <provider>/<account> or <provider>/<key id>, like codex/me@example.com: " + a)
}
if len(a) > 300 {
return nil, errors.New("A key's account is at most 300 characters")
}
p, err := provider.Find(pid)
if err != nil {
return nil, err
}
id := ""
for _, r := range p.AccountIDs() {
if strings.EqualFold(r.ID, ref) || strings.EqualFold(r.User, ref) {
id = r.ID
break
}
}
if id == "" {
if p.Account == nil {
return nil, fmt.Errorf("%s has no key %q", p.Name, ref)
}
return nil, fmt.Errorf("%s has no account %q", p.Name, ref)
}
kept := p.ID + "/" + id
if !slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, kept) }) {
out = append(out, kept)
}
}
if len(out) > 500 {
return nil, errors.New("A key can list at most 500 accounts")
}
return out, nil
}
// AllowsAccount says the provider pid's account or key ref is among the
// key's accounts — "<provider>/<ref>", told apart in lower case, as
// accounts are. The list holds a key to some accounts **of the providers
// it names**: a provider it names no account of, the key uses as it
// always did, its every account and key. Any, for a key that lists none.
func (who Identity) AllowsAccount(pid, ref string) bool {
if len(who.Accounts) == 0 {
return true
}
pid = strings.ToLower(strings.TrimSpace(pid))
key := pid + "/" + strings.ToLower(strings.TrimSpace(ref))
named := false
for _, a := range who.Accounts {
if a = strings.ToLower(strings.TrimSpace(a)); a == key {
return true
} else if p, _, ok := strings.Cut(a, "/"); ok && p == pid {
named = true
}
}
return !named
}
+64
View File
@@ -0,0 +1,64 @@
package access
import (
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A key's account list as it is kept (#905): each entry a provider's
// account or key it has now — so a typo can't quietly hold a key to
// nothing — trimmed, told apart in lower case as accounts are, each once.
// An account's stable id, and a name resolving to it, is exercised
// against a real sign-in in the gateway's tests; a key's fingerprint is
// one here.
func TestCleanAccounts(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "http://127.0.0.1:1/v1", Keys: []provider.KeyAccount{{Key: "sk-1", Name: "First"}, {Key: "sk-2"}}}); err != nil {
t.Fatal(err)
}
k1, k2 := provider.KeyID("sk-1"), provider.KeyID("sk-2")
for _, c := range []struct {
name string
in []string
want []string
bad string
}{
{"an empty list is every account", nil, nil, ""},
{"a key by its fingerprint", []string{"relay/" + k1}, []string{"relay/" + k1}, ""},
{"another case of it is the same one", []string{" relay/" + strings.ToUpper(k1) + " ", "relay/" + k1}, []string{"relay/" + k1}, ""},
{"a key by the name it is shown by, kept by its fingerprint", []string{"relay/First", "relay/" + k2}, []string{"relay/" + k1, "relay/" + k2}, ""},
{"an account with no provider", []string{"sk-1"}, nil, "<provider>/<account>"},
{"a provider there is none of", []string{"nope/sk-1"}, nil, "no provider"},
{"a key the provider has not", []string{"relay/" + provider.KeyID("sk-9")}, nil, "has no key"},
{"an account the provider has none of", []string{"relay/me@example.com"}, nil, "has no key"},
} {
out, err := CleanAccounts(c.in)
if c.bad != "" {
if err == nil || !strings.Contains(err.Error(), c.bad) {
t.Errorf("%s: said %v, want %q in it", c.name, err, c.bad)
}
continue
}
if err != nil {
t.Fatalf("%s: %v", c.name, err)
}
if !slices.Equal(out, c.want) {
t.Errorf("%s: kept %v, want %v", c.name, out, c.want)
}
}
// matching is in lower case, both sides; a provider the list names no
// account of, the key uses as it always did
who := Identity{Accounts: []string{"relay/" + strings.ToUpper(k1)}}
if !who.AllowsAccount("relay", k1) || who.AllowsAccount("relay", k2) {
t.Fatal("told apart in lower case")
}
if !who.AllowsAccount("other", k1) {
t.Fatal("a provider the list names no account of was held")
}
if !(Identity{}).AllowsAccount("relay", k1) {
t.Fatal("a key that lists none uses every account")
}
}
+5 -4
View File
@@ -32,13 +32,14 @@ func CleanModels(in []string) ([]string, error) {
return out, nil
}
// Restricted says the key may use only the models it lists.
func (who Identity) Restricted() bool { return len(who.Models) > 0 }
// Restricted says the key may use only the models or accounts it lists.
func (who Identity) Restricted() bool { return len(who.Models) > 0 || len(who.Accounts) > 0 }
// Allows says one of ids is among the key's models; any, for a key that
// lists none.
// lists none. The accounts a key may be held to say nothing of its
// models: they hold the candidates of a plan, not its models.
func (who Identity) Allows(ids ...string) bool {
if !who.Restricted() {
if len(who.Models) == 0 {
return true
}
for _, id := range ids {
+26
View File
@@ -428,6 +428,32 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) {
writeError(w, provider.Chat, http.StatusForbidden, keyModelError(keyWho, asked))
return
}
// and held to some accounts (#905): the decision model's provider must
// have one the key may use, the call spend landing on it as any's —
// and asked on one such key, not the provider's first, which may be
// one the key may not: of the keys in use, the first the key may use
// and that is let serve the model, the request refused without one.
// A provider with no key asks as it is: an account's tokens, or none
// at all
if accWho, accHeld := accountHolds(r); accHeld {
if !accountServes(accWho, p, model) {
writeError(w, provider.Chat, http.StatusForbidden, keyAccountsError(accWho, asked))
return
}
if p.Account == nil && p.Key != "" {
kept := false
for _, k := range p.KeysOn() {
if q := p.WithKey(k); accountAllowed(accWho, candidate{p: q, model: model}) && p.AccountServes(q.AccountID(), model) {
p, kept = q, true
break
}
}
if !kept {
writeError(w, provider.Chat, http.StatusForbidden, keyAccountsError(accWho, asked))
return
}
}
}
seat := decideSeat(p, model)
var used Usage
tr := s.trace.begin(Route{Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), Model: asked, Provider: p.ID,
+21 -2
View File
@@ -300,7 +300,7 @@ func (s *Server) images(edit bool) http.HandlerFunc {
ctx, cancel := context.WithTimeout(r.Context(), drawTimeout)
defer cancel()
// the account that drew, or refused last, is the one recorded
drew, out, code, capBack, err := s.drawOnAccounts(ctx, p, model, d)
drew, out, code, capBack, err := s.drawOnAccounts(ctx, r, p, model, d)
p = drew
call.Millis = time.Since(start).Milliseconds()
call.Status, call.Usage.Input, call.Usage.Output = code, out.Input, out.Output
@@ -554,8 +554,18 @@ func viaFor(p provider.Provider, model string) drawVia {
// what the pinned one may not (#545). The refusal is of images alone, so
// no account rests for text over it. It answers with the account that
// drew, or the last one's error when every one refused.
func (s *Server) drawOnAccounts(ctx context.Context, p provider.Provider, model string, d drawing) (provider.Provider, drawn, int, time.Time, error) {
func (s *Server) drawOnAccounts(ctx context.Context, r *http.Request, p provider.Provider, model string, d drawing) (provider.Provider, drawn, int, time.Time, error) {
if p.Account == nil {
// a key of its own: the calling key's accounts hold it as one,
// drawn with a key it may use — of those in use, not the
// provider's first alone, which a key held to a later one was
// refused by — or none, refused
if keyWho, held := accountHolds(r); held {
var ok bool
if p, ok = allowedKey(keyWho, p, model); !ok {
return p, drawn{}, http.StatusForbidden, time.Time{}, errors.New(keyAccountsError(keyWho, d.Model))
}
}
out, code, err := s.draw(ctx, p, model, d)
return p, out, code, time.Time{}, err
}
@@ -570,6 +580,15 @@ func (s *Server) drawOnAccounts(ctx context.Context, p provider.Provider, model
cs = append(cs, c)
}
}
// the accounts the calling key may not use are left out of the whole
// fan-out (#905): the next one a refusal hands the request to no less
// than the first, so none it may not use draws
if keyWho, held := accountHolds(r); held {
cs = slices.DeleteFunc(cs, func(c candidate) bool { return !accountAllowed(keyWho, c) })
if len(cs) == 0 {
return p, drawn{}, http.StatusForbidden, time.Time{}, errors.New(keyAccountsError(keyWho, d.Model))
}
}
if len(cs) == 0 && slices.ContainsFunc(barred, func(c candidate) bool { return c.capped != nil }) {
// every account is held at its usage cap
msg, back := cappedError(model, barredOf(barred, q, false, provider.Chat, nil), time.Now())
+1 -1
View File
@@ -185,7 +185,7 @@ func TestDrawCappedSaysWhenItIsBack(t *testing.T) {
t.Fatal(err)
}
s := New()
_, _, code, back, err := s.drawOnAccounts(context.Background(), *p, "gpt-image-1", drawing{})
_, _, code, back, err := s.drawOnAccounts(context.Background(), httptest.NewRequest("POST", "/v1/images/generations", nil), *p, "gpt-image-1", drawing{})
if code != http.StatusTooManyRequests || err == nil {
t.Fatalf("%d %v", code, err)
}
+13
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"net/http"
"slices"
"strings"
"time"
@@ -75,6 +76,18 @@ func (s *Server) retrieve(path, operation string) http.HandlerFunc {
tries = cs
}
}
// the accounts or keys the calling key may not use are left out of
// the tries too (#905): a group's members through it no less
if keyWho, held := accountHolds(r); held {
tries = slices.DeleteFunc(tries, func(c candidate) bool { return !accountAllowed(keyWho, c) })
if len(tries) == 0 {
msg := keyAccountsError(keyWho, asked)
call.Status, call.Error = 403, msg
writeError(w, provider.Chat, 403, msg)
s.record(call)
return
}
}
var skipped []string
// masked once, as the settings say: a document a reranker gives
// back has its secrets again
+3
View File
@@ -1968,6 +1968,9 @@ func pinTo(want string, cands []candidate, pl planned) ([]candidate, planned, in
return nil, pl, http.StatusTooManyRequests, AccountHeader + ": " + strings.Join(rests, "; ") + "; no other account is tried in its place"
}
for _, w := range pl.left {
if match(w) && w.Held {
return nil, pl, http.StatusForbidden, fmt.Sprintf("%s: the gateway key may not use %s's account", AccountHeader, w.Who)
}
if match(w) && w.Capped > 0 {
msg, _ := cappedError(w.Model, []Weighed{w}, time.Now())
return nil, pl, http.StatusTooManyRequests, AccountHeader + ": " + msg + "; no other account is tried in its place"
+29 -4
View File
@@ -868,6 +868,12 @@ func (s *Server) countOn(w http.ResponseWriter, r *http.Request, p provider.Prov
counts = append(counts, c)
}
}
// the accounts or keys the calling key may not use are left out of
// the counts too (#905): counted on one it may, and where it may
// use none, the local estimate below says the count
if who, held := accountHolds(r); held {
counts = slices.DeleteFunc(counts, func(c candidate) bool { return !accountAllowed(who, c) })
}
}
// the names in force, read at most once however many candidates are
// counted, and not at all where there are none
@@ -1202,6 +1208,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// 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
keyWho, keyHeld := keyHolds(r)
_, accHeld := accountHolds(r)
chose, _ := r.Context().Value(magpieChoseKey{}).(bool)
if keyHeld && (isGroup && !groupAllowed(keyWho, g, ms) || !isGroup && !modelAllowed(keyWho, p, model)) {
call.Status, call.Error = 403, "model not allowed for the gateway key"
writeError(w, from, 403, keyModelError(keyWho, call.Model))
@@ -1327,15 +1335,23 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
if sealedTask {
cands, pl = sealedReaders(cands, pl)
}
if keyHeld {
var accountHeld bool // every candidate was an account or key the calling key may not use
if keyHeld || accHeld {
who := keyWho
var members map[string]bool
if isGroup {
if chose {
// magpie's own call for the key — a web search, a picture
// described, a Codex title: of the models the user picked, so
// the models don't hold it, but the spend lands on an account,
// and the accounts hold it too
who.Models = nil
} else if isGroup {
members = groupKeeps(keyWho, g, ms)
}
cands = allowedCandidates(keyWho, cands, members)
cands, pl, accountHeld = allowedCandidates(who, cands, pl, members)
}
if len(cands) == 0 && slices.ContainsFunc(pl.left, func(w Weighed) bool { return w.Capped > 0 }) &&
!slices.ContainsFunc(pl.left, func(w Weighed) bool { return !w.Barred && w.Capped == 0 }) {
!slices.ContainsFunc(pl.left, func(w Weighed) bool { return !w.Barred && !w.Held && w.Capped == 0 }) {
// every account there is is held at its usage cap: used up, as far
// as routing goes, until a window renews
msg, back := cappedError(call.Model, pl.left, time.Now())
@@ -1347,6 +1363,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
turnedAway()
return
}
if len(cands) == 0 && accountHeld {
// every account or key the model had is one the calling key may
// not use (#905), the plan's left saying so: told before the barred
// and ready ones it may also have
call.Status, call.Error = 403, "every account outside the key's accounts"
writeError(w, from, 403, keyAccountsError(keyWho, call.Model))
turnedAway()
return
}
if len(cands) == 0 && len(pl.left) > 0 && !slices.ContainsFunc(pl.left, func(w Weighed) bool { return !w.Barred }) {
// every account or key there is was set not to serve the model
call.Status, call.Error = 403, "every account barred"
+592
View File
@@ -0,0 +1,592 @@
package gateway
import (
"encoding/base64"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
)
// A gateway key held to some accounts (#905) is served by those alone:
// the account it names, the other one never tried, though the plan held
// both; a group it names is its members' still only through the accounts
// it may use; every candidate held out is said so on the route's left.
// When the accounts leave the plan nothing — the capped, the barred and
// the not-ready refusals say which came first: a cap holds before the
// key's accounts, those before an account barred for the model, and that
// before no candidate at all. A free key is served as before.
func TestGatewayKeyAccountsHoldAKey(t *testing.T) {
heads := twoAccounts(t)
s := New()
keys, secrets := newCaller(t, "Held", "Free")
setAccounts := func(t *testing.T, id string, as ...string) {
t.Helper()
if _, err := access.Update("accounts-key", access.Change{Key: id, Accounts: as}); err != nil {
t.Fatal(err)
}
}
post := func(secret string) (int, string) {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"codex/gpt-5.5","stream":true,"input":"ping"}`))
req.Header.Set("Authorization", "Bearer "+secret)
s.Handler().ServeHTTP(rec, req)
return rec.Code, rec.Body.String()
}
// the account the key names serves every request of its own; the other
// one is never tried, though the plan held both
setAccounts(t, keys[0].ID, "codex/me@example.com")
for range 3 {
*heads = nil
code, body := post(secrets[0])
if code != 200 || !strings.Contains(body, "from acct-1") {
t.Fatalf("held to me: %d %s", code, body)
}
for _, h := range *heads {
if got := h.Get("chatgpt-account-id"); got != "acct-1" {
t.Fatalf("the account not named was tried: %v", got)
}
}
if len(*heads) != 1 {
t.Fatalf("upstream heads %v", *heads)
}
}
// the plan's left says the other account was held out
if r := s.trace.routes[len(s.trace.routes)-1]; len(r.Left) != 1 || r.Left[0].Who != "spare@example.com" || !r.Left[0].Held || r.Left[0].Barred {
t.Fatalf("route left %+v", r.Left)
}
// the other account of the provider is the key's as well
setAccounts(t, keys[0].ID, "codex/spare@example.com")
*heads = nil
if code, body := post(secrets[0]); code != 200 || !strings.Contains(body, "from acct-2") {
t.Fatalf("held to spare: %d %s", code, body)
}
// a group the key names is its members' — through the accounts it may
// use only, not through the members by themselves
if err := provider.SaveGroup(provider.Group{Name: "Gpt", Members: []string{"codex/gpt-5.5"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"group/gpt"}}); err != nil {
t.Fatal(err)
}
*heads = nil
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"group/gpt","stream":true,"input":"ping"}`))
req.Header.Set("Authorization", "Bearer "+secrets[0])
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from acct-2") {
t.Fatalf("a named group through the accounts: %d %s", rec.Code, rec.Body.String())
}
if len(*heads) != 1 || (*heads)[0].Get("chatgpt-account-id") != "acct-2" {
t.Fatalf("a named group tried another account: %v", *heads)
}
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID}); err != nil {
t.Fatal(err)
}
// every candidate held out by the accounts is a 403 that names the
// key and its accounts — before the barred refusal the plan may also
// have: me is barred for the model, spare is not the key's
if err := provider.SetAccountModels("codex", "me@example.com", []string{"gpt-5.4-mini"}); err != nil {
t.Fatal(err)
}
setAccounts(t, keys[0].ID, "codex/me@example.com")
*heads = nil
code, body := post(secrets[0])
var e struct {
Error struct{ Message, Type string }
}
json.Unmarshal([]byte(body), &e)
if code != 403 || e.Error.Type != "permission_error" || !strings.Contains(e.Error.Message, `"Held"`) ||
!strings.Contains(e.Error.Message, "is not allowed to use the accounts behind") || !strings.Contains(e.Error.Message, "codex/me@example.com") {
t.Fatalf("every account held out: %d %s", code, body)
}
if len(*heads) != 0 {
t.Fatalf("a held-out request reached a provider: %v", *heads)
}
if rec := lastUsage(t); !rec.Rejected || rec.Status != 403 || rec.CallerKeyID != keys[0].ID {
t.Fatalf("held out recorded as %+v", rec)
}
// a cap holds before the key's accounts: me capped, spare not the
// key's, and the refusal is the cap's 429
if err := provider.SetAccountModels("codex", "me@example.com", nil); err != nil {
t.Fatal(err)
}
capUsage(t, map[string]float64{"me@example.com": 75})
if err := provider.SetAccountCap("codex", "me@example.com", 70); err != nil {
t.Fatal(err)
}
*heads = nil
code, body = post(secrets[0])
if code != 429 || !strings.Contains(body, "usage cap reached") || !strings.Contains(body, "me@example.com") {
t.Fatalf("a cap before the accounts: %d %s", code, body)
}
if err := provider.SetAccountCap("codex", "me@example.com", 0); err != nil {
t.Fatal(err)
}
// the barred refusal stands when the accounts held nothing out: both
// barred, one of them the key's
if err := provider.SetAccountModels("codex", "me@example.com", []string{"gpt-5.4-mini"}); err != nil {
t.Fatal(err)
}
if err := provider.SetAccountModels("codex", "spare@example.com", []string{"gpt-5.4-mini"}); err != nil {
t.Fatal(err)
}
*heads = nil
code, body = post(secrets[0])
if code != 403 || !strings.Contains(body, "own list of models") {
t.Fatalf("barred before the accounts held nothing: %d %s", code, body)
}
if err := provider.SetAccountModels("codex", "me@example.com", nil); err != nil {
t.Fatal(err)
}
if err := provider.SetAccountModels("codex", "spare@example.com", nil); err != nil {
t.Fatal(err)
}
// a free key is served as before, and one let off its accounts again
setAccounts(t, keys[0].ID)
for _, secret := range []string{secrets[0], secrets[1]} {
*heads = nil
if code, body := post(secret); code != 200 || !strings.Contains(body, "from acct-1") {
t.Fatalf("every account: %d %s", code, body)
}
}
}
// A gateway key held to some accounts (#905) is shown in /v1/models only
// the models an account or key it may use serves: one every allowed
// account is set not to serve (#474) is another's, not its.
func TestGatewayKeyAccountsListModels(t *testing.T) {
heads := twoAccounts(t)
if err := provider.Save(provider.Provider{ID: "codex", Models: []string{"gpt-5.5", "gpt-5.4-mini"}}); err != nil {
t.Fatal(err)
}
s := New()
keys, secrets := newCaller(t, "Held")
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"codex/me@example.com"}}); err != nil {
t.Fatal(err)
}
if err := provider.SetAccountModels("codex", "me@example.com", []string{"gpt-5.4-mini"}); err != nil {
t.Fatal(err)
}
list := func(secret string) string {
t.Helper()
r := httptest.NewRequest("GET", "/v1/models", nil)
if secret != "" {
r.Header.Set("Authorization", "Bearer "+secret)
} else {
r.RemoteAddr = "127.0.0.1:5000" // this computer asks without a key
}
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
return w.Body.String()
}
if got := list(secrets[0]); strings.Contains(got, `"codex/gpt-5.5"`) || !strings.Contains(got, `"codex/gpt-5.4-mini"`) {
t.Fatalf("the key's models: %s", got)
}
// a provider with no account and no key (a local ollama) is one the
// key names no account of: its models stay listed, as its requests
// pass (#905)
if err := provider.Save(provider.Provider{ID: "local", Name: "Local", Chat: "http://127.0.0.1:11434/v1", Models: []string{"tiny"}}); err != nil {
t.Fatal(err)
}
if err := catalog.SaveLive("local", "http://127.0.0.1:11434/v1", []catalog.Model{{ID: "tiny"}}); err != nil {
t.Fatal(err)
}
if got := list(secrets[0]); !strings.Contains(got, `"local/tiny"`) {
t.Fatalf("a provider with no account or key: %s", got)
}
// an entry kept after its provider lost its last key holds the key
// closer: the provider it names serves none of its models
if err := catalog.SaveLive("relay", "http://127.0.0.1:2/v1", []catalog.Model{{ID: "m"}}); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "http://127.0.0.1:2/v1", Key: "sk-r", Models: []string{"m"}}); err != nil {
t.Fatal(err)
}
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"codex/me@example.com", "relay/" + provider.KeyID("sk-r")}}); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "http://127.0.0.1:2/v1", Models: []string{"m"}}); err != nil {
t.Fatal(err)
}
if got := list(secrets[0]); strings.Contains(got, `"relay/m"`) || !strings.Contains(got, `"local/tiny"`) {
t.Fatalf("a named provider without a key: %s", got)
}
// a keyless request sees both, and the accounts hold no model back
if got := list(""); !strings.Contains(got, `"codex/gpt-5.5"`) || !strings.Contains(got, `"codex/gpt-5.4-mini"`) {
t.Fatalf("a keyless list: %s", got)
}
if len(*heads) != 0 {
t.Fatal("a list reached a provider", *heads)
}
}
// A gateway key held to some accounts (#905) is drawn with by those alone:
// the whole fan-out of a subscription's accounts, not only its first. One
// of the key's whose plan refuses to draw doesn't hand the request to an
// account it may not use; the second in the order, when it is the key's,
// draws what the first may not; a keyless request fans out as before.
func TestGatewayKeyAccountsDrawOnAllowedAccounts(t *testing.T) {
var drew []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
acct := r.Header.Get("chatgpt-account-id")
drew = append(drew, acct)
w.Header().Set("Content-Type", "application/json")
if acct == "acct-1" { // a plan without images, as chatgpt.com refuses
w.WriteHeader(http.StatusForbidden)
io.WriteString(w, `{"detail":{"message":"Forbidden"}}`)
return
}
io.WriteString(w, `{"created":1,"data":[{"b64_json":"eA=="}]}`)
}))
t.Cleanup(up.Close)
codexSignedIn(t, "spare@example.com")
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
if err := provider.Save(provider.Provider{ID: "codex", Models: []string{"gpt-image-2"}}); err != nil {
t.Fatal(err)
}
s := New()
keys, secrets := newCaller(t, "Held")
setAccounts := func(as ...string) {
t.Helper()
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: as}); err != nil {
t.Fatal(err)
}
}
draw := func(secret string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", "/v1/images/generations", strings.NewReader(`{"model":"codex/gpt-image-2","prompt":"a magpie"}`))
r.Header.Set("Authorization", "Bearer "+secret)
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
return w
}
// the key's first account's plan refuses: the refusal stands, the
// other account — one the key may not use — is never handed the pen
setAccounts("codex/me@example.com")
if w := draw(secrets[0]); w.Code == 200 || strings.Contains(w.Body.String(), "b64_json") {
t.Fatalf("a refusing account drew: %d %s", w.Code, w.Body.String())
}
if !slices.Equal(drew, []string{"acct-1"}) {
t.Fatalf("the fan-out reached an account the key may not use: %v", drew)
}
// the second account, when it is the key's, draws what the first may not
setAccounts("codex/spare@example.com")
drew = nil
if w := draw(secrets[0]); w.Code != 200 || !strings.Contains(w.Body.String(), "b64_json") {
t.Fatalf("the allowed account didn't draw: %d %s", w.Code, w.Body.String())
}
if !slices.Equal(drew, []string{"acct-2"}) {
t.Fatalf("another account was tried: %v", drew)
}
// a keyless request fans out to the next account, as before
drew = nil
r := httptest.NewRequest("POST", "/v1/images/generations", strings.NewReader(`{"model":"codex/gpt-image-2","prompt":"a magpie"}`))
r.RemoteAddr = "127.0.0.1:5000"
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if w.Code != 200 || !slices.Equal(drew, []string{"acct-1", "acct-2"}) {
t.Fatalf("a keyless fan-out: %d %s, drew %v", w.Code, w.Body.String(), drew)
}
}
// A gateway key held to some accounts (#905) counts tokens on those alone:
// the counting candidates — a relay's keys, each an account the key may
// name — are held to the key's accounts as the serving ones are, none but
// the local estimate when it may use none. Gemini's counting, answered by
// the gateway itself, reaches no provider either way.
func TestGatewayKeyAccountsCountTokens(t *testing.T) {
fresh(t)
var counted []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
counted = append(counted, strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"input_tokens":5}`)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Anthropic: up.URL, Key: "sk-0",
Keys: []provider.KeyAccount{{Key: "sk-A"}, {Key: "sk-B"}}, Models: []string{"m"}}); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Held")
setAccounts := func(as ...string) {
t.Helper()
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: as}); err != nil {
t.Fatal(err)
}
}
h := New().Handler()
count := func(path, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", path, strings.NewReader(body))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
// only the key the key may use counts
for _, k := range []string{"sk-A", "sk-B"} {
setAccounts("relay/" + provider.KeyID(k))
counted = nil
w := count("/v1/messages/count_tokens", `{"model":"relay/m","messages":[{"role":"user","content":"hi"}]}`)
if w.Code != 200 || !strings.Contains(w.Body.String(), "input_tokens") {
t.Fatalf("counted on %s: %d %s", k, w.Code, w.Body.String())
}
if !slices.Equal(counted, []string{k}) {
t.Fatalf("counted on %s by %v", k, counted)
}
}
// the one key it may use, set not to serve the model: the local
// estimate, no provider asked
if err := provider.SetAccountModels("relay", provider.KeyID("sk-A"), []string{"other"}); err != nil {
t.Fatal(err)
}
setAccounts("relay/" + provider.KeyID("sk-A"))
counted = nil
w := count("/v1/messages/count_tokens", `{"model":"relay/m","messages":[{"role":"user","content":"hi"}]}`)
if w.Code != 200 || !strings.Contains(w.Body.String(), "input_tokens") || len(counted) != 0 {
t.Fatalf("the local estimate: %d %s, asked %v", w.Code, w.Body.String(), counted)
}
// Gemini's counting, the model in its URL: the gateway's own estimate
counted = nil
w = count("/v1beta/models/relay/m:countTokens", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)
if w.Code != 200 || !strings.Contains(w.Body.String(), "totalTokens") || len(counted) != 0 {
t.Fatalf("gemini counting: %d %s, asked %v", w.Code, w.Body.String(), counted)
}
}
// magpie's own calls for a held key — a Codex title, of the model Settings
// names — are of the models the user picked, so the models don't hold them,
// but their spend lands on an account: the accounts hold them too (#905),
// and the title is written by an account the key may use alone.
func TestGatewayKeyAccountsHoldASideCall(t *testing.T) {
var heads []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
heads = append(heads, r.Header.Get("chatgpt-account-id"))
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"{\"title\":\"Fix login bug\"}"}]}],"usage":{"input_tokens":9,"output_tokens":2}}}`))
}))
t.Cleanup(up.Close)
codexSignedIn(t, "spare@example.com")
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
if err := provider.Save(provider.Provider{ID: "codex", Models: []string{"gpt-5.5"}}); err != nil {
t.Fatal(err)
}
st := settings.Load()
st.CodexTitles = "codex/gpt-5.5"
if err := settings.Save(st); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Held")
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"codex/spare@example.com"}}); err != nil {
t.Fatal(err)
}
body := `{"model":"gpt-5.6-luna","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Generate a concise title. User prompt:\nfix the login bug"}]}],` +
`"text":{"format":{"type":"json_schema","name":"codex_output_schema","strict":true,"schema":{"type":"object","properties":{"title":{"type":"string"}},"required":["title"],"additionalProperties":false}}}}`
r := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(body))
r.Header.Set("Authorization", "Bearer "+secrets[0])
r.Header.Set("session_id", "title-thread")
r.Header.Set("x-codex-turn-metadata", `{"thread_source":"thread_title","parent_thread_id":"main-chat"}`)
w := httptest.NewRecorder()
New().Handler().ServeHTTP(w, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "Fix login bug") {
t.Fatalf("the title: %d %s", w.Code, w.Body.String())
}
if !slices.Equal(heads, []string{"acct-2"}) {
t.Fatalf("the title was written by %v, the key may use acct-2 alone", heads)
}
}
// System One asks its decision model of an account the calling key may use
// (#905): one of the provider it names and may use serves it; a provider
// the key names no account of, it asks as it always did.
func TestGatewayKeyAccountsSystemOne(t *testing.T) {
fresh(t)
var decided int
up := 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(up.Close)
if err := provider.Save(provider.Provider{ID: "jev", Name: "Jev", Key: "kj", Decide: up.URL + "/v1", Models: []string{"jev-latest"}}); err != nil {
t.Fatal(err)
}
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "sk-1", Chat: "http://127.0.0.1:1/v1", Models: []string{"m"}}); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Held")
h := New().Handler()
ask := func(secret string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", "/v1/systemone", strings.NewReader(`{"model":"jev/jev-latest","state":{"message":"hi"},"questions":{"intent":{"type":"choice"}}}`))
r.Header.Set("Authorization", "Bearer "+secret)
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
// an account of the provider it names: asked
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"jev/" + provider.KeyID("kj")}}); err != nil {
t.Fatal(err)
}
if w := ask(secrets[0]); w.Code != 200 || decided != 1 {
t.Fatalf("the key's account: %d %s, decided %d", w.Code, w.Body.String(), decided)
}
// a provider the key names no account of: asked as it always did
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"relay/" + provider.KeyID("sk-1")}}); err != nil {
t.Fatal(err)
}
if w := ask(secrets[0]); w.Code != 200 || decided != 2 {
t.Fatalf("an unnamed provider: %d %s, decided %d", w.Code, w.Body.String(), decided)
}
// the provider named, its account set not to serve the decision model
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"jev/" + provider.KeyID("kj")}}); err != nil {
t.Fatal(err)
}
if err := provider.SetAccountModels("jev", provider.KeyID("kj"), []string{"other"}); err != nil {
t.Fatal(err)
}
w := ask(secrets[0])
if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "is not allowed to use the accounts behind") || decided != 2 {
t.Fatalf("a barred account: %d %s, decided %d", w.Code, w.Body.String(), decided)
}
}
// A gateway key held to a later key of a decision provider is asked with
// that key alone (#905): the decision was sent on the provider's first
// key whatever the key may use, spending one it may not — here the
// second is the key's, and the first is never asked.
func TestGatewayKeyAccountsSystemOneOnAKey(t *testing.T) {
fresh(t)
var asked []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
asked = append(asked, strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"answers":{"intent":{"choice":"bug"}},"usage":{"input_tokens":10,"output_tokens":2}}`)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "jev", Name: "Jev", Key: "kA", Keys: []provider.KeyAccount{{Key: "kB"}},
Decide: up.URL + "/v1", Models: []string{"jev-latest"}}); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Held")
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"jev/" + provider.KeyID("kB")}}); err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("POST", "/v1/systemone", strings.NewReader(`{"model":"jev/jev-latest","state":{"message":"hi"},"questions":{"intent":{"type":"choice"}}}`))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
New().Handler().ServeHTTP(w, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "bug") {
t.Fatalf("the decision: %d %s", w.Code, w.Body.String())
}
if !slices.Equal(asked, []string{"kB"}) {
t.Fatalf("asked with %v, the key may use kB alone", asked)
}
}
// A gateway key held to a later key of a remote magpie makes videos with
// that key alone (#905): the videos API sent on the provider's first key,
// refusing a key held to a later one though it may use it.
func TestGatewayKeyAccountsVideoOnAnAllowedKey(t *testing.T) {
fresh(t)
var made []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
made = append(made, strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"vid-1"}`)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset,
Chat: up.URL + "/v1", Key: "kA", Keys: []provider.KeyAccount{{Key: "kB"}}, Models: []string{"grok-imagine-video"}}); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Held")
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"office/" + provider.KeyID("kB")}}); err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("POST", "/v1/videos", strings.NewReader(`{"model":"office/grok-imagine-video","prompt":"a magpie"}`))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
New().Handler().ServeHTTP(w, r)
if w.Code != 200 {
t.Fatalf("the video: %d %s", w.Code, w.Body.String())
}
if !slices.Equal(made, []string{"kB"}) {
t.Fatalf("made with %v, the key may use kB alone", made)
}
}
// A gateway key held to a later key of a keyed provider draws with that
// key alone (#905): the images API's keyed path refused a key held to a
// later one though it may use it.
func TestGatewayKeyAccountsDrawOnAnAllowedKey(t *testing.T) {
fresh(t)
var drew []string
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
drew = append(drew, strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
w.Header().Set("Content-Type", "application/json")
b64 := base64.StdEncoding.EncodeToString(pngBytes)
if strings.HasSuffix(r.URL.Path, "/chat/completions") {
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"Here it is.","images":[{"type":"image_url","image_url":{"url":"data:image/png;base64,`+b64+`"}}]}}],"usage":{"prompt_tokens":3,"completion_tokens":50}}`)
return
}
io.WriteString(w, `{"created":1,"data":[{"b64_json":"`+b64+`"}]}`)
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: "art", Name: "Art", Chat: up.URL + "/v1", Key: "kA",
Keys: []provider.KeyAccount{{Key: "kB"}}, Models: []string{"gpt-image-1"}}); err != nil {
t.Fatal(err)
}
keys, secrets := newCaller(t, "Held")
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"art/" + provider.KeyID("kB")}}); err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("POST", "/v1/images/generations", strings.NewReader(`{"model":"art/gpt-image-1","prompt":"a magpie"}`))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
New().Handler().ServeHTTP(w, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "b64_json") {
t.Fatalf("the drawing: %d %s", w.Code, w.Body.String())
}
if !slices.Equal(drew, []string{"kB"}) {
t.Fatalf("drew with %v, the key may use kB alone", drew)
}
}
// A key held to some accounts of one provider uses another's as it always
// did (#905): the list holds it to some accounts of the providers it
// names, not to the providers themselves.
func TestGatewayKeyAccountsOfANamedProvider(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, "Held")
if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{"plan/" + provider.KeyID("k")}}); err != nil {
t.Fatal(err)
}
h := New().Handler()
// plan is named: only its key may serve; spare, named nowhere, serves
// as it always did
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"spare/m2","messages":[{"role":"user","content":"hi"}]}`))
r.Header.Set("Authorization", "Bearer "+secrets[0])
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "from-spare") {
t.Fatalf("a provider the key names no account of: %d %s", w.Code, w.Body.String())
}
if spare.calls != 1 || plan.calls != 0 {
t.Fatalf("spare %d, plan %d", spare.calls, plan.calls)
}
}
+134 -10
View File
@@ -41,6 +41,16 @@ func keyHolds(r *http.Request) (access.Identity, bool) {
return who, true
}
// accountHolds is the calling key's accounts, when they hold this
// request: magpie's own calls for the key — a web search, a picture
// described, a Codex title — are of the models the user picked, so the
// models don't hold them, but their spend lands on an account or key all
// the same, and the accounts hold them too.
func accountHolds(r *http.Request) (access.Identity, bool) {
who := access.Caller(r.Context())
return who, len(who.Accounts) > 0
}
// modelAllowed says the key may use provider p's model.
func modelAllowed(who access.Identity, p provider.Provider, model string) bool {
return who.Allows(p.ID + "/" + model)
@@ -90,16 +100,60 @@ func membersAllowed(who access.Identity, ms []provider.Member) bool {
return true
}
// entryAllowed says the key is shown a model of the catalog.
// entryAllowed says the key is shown a model of the catalog — and some
// account or key it may use serves it (#905): one the provider's
// accounts are set not to serve (#474) is none of the key's.
func entryAllowed(who access.Identity, e provider.Entry) bool {
if !who.Restricted() {
return true
}
if e.Group != "" {
g, ms, ok := provider.FindGroup(e.ID)
return ok && groupAllowed(who, g, ms)
if !ok || !groupAllowed(who, g, ms) {
return false
}
for _, m := range ms {
if accountServes(who, m.Provider, m.Model) {
return true
}
}
return false
}
return modelAllowed(who, e.Provider, e.Model)
if !modelAllowed(who, e.Provider, e.Model) {
return false
}
return accountServes(who, e.Provider, e.Model)
}
// accountServes says some account or key the key may use serves the provider's
// model: an account of several set to serve other models only (#474) is
// one the key may use, and none of the key's.
func accountServes(who access.Identity, p provider.Provider, model string) bool {
if len(who.Accounts) == 0 {
return true
}
refs := p.AccountIDs()
if len(refs) == 0 {
// a provider with no account and no key (a local ollama): the
// list holds a key to some accounts of the providers it names
// (AllowsAccount's rule), so one it names none of serves as it
// always did; one it names — an entry kept after its last account
// or key went — serves none, holding the key closer
return who.AllowsAccount(p.ID, "")
}
for _, r := range refs {
if !who.AllowsAccount(p.ID, r.ID) {
continue
}
ref := r.User
if r.Key {
ref = r.ID // a key's own list is keyed by its fingerprint
}
if p.AccountServes(ref, model) {
return true
}
}
return false
}
// keyAllowed filters the catalog to what the calling key may use.
@@ -118,16 +172,70 @@ func keyAllowed(r *http.Request, es []provider.Entry) []provider.Entry {
}
// allowedCandidates leaves out of a plan the providers' models the key
// may not use: a model's fallbacks are other models. members are the
// group's the key may go to through it (groupKeeps), nil for a model.
func allowedCandidates(who access.Identity, cs []candidate, members map[string]bool) []candidate {
// may not use — a model's fallbacks are other models — and the accounts
// and keys it may not either, through a named group too: naming a group
// is not naming its accounts. The plan's order keeps step with what is
// left, and an account the key may not use is said on the plan's left,
// held. members are the group's the key may go to through it
// (groupKeeps), nil for a model. held says every candidate was an
// account or key the key may not use.
func allowedCandidates(who access.Identity, cs []candidate, pl planned, members map[string]bool) ([]candidate, planned, bool) {
out := cs[:0:0]
for _, c := range cs {
if members[c.p.ID+"/"+c.model] || modelAllowed(who, c.p, c.model) {
out = append(out, c)
order := pl.order[:0:0]
held := false
for i, c := range cs {
if !members[c.p.ID+"/"+c.model] && !modelAllowed(who, c.p, c.model) {
continue // a model the key may not use: skipped, as before
}
if !accountAllowed(who, c) {
held = true
if i < len(pl.order) {
w := pl.order[i]
w.Held = true
pl.left = append(pl.left, w)
}
continue
}
out = append(out, c)
if i < len(pl.order) {
order = append(order, pl.order[i])
}
}
return out
pl.order = order
return out, pl, held && len(out) == 0
}
// accountAllowed says the key may use a candidate's account or key: a
// signed-in account by its stable id, kept through renames, a key by its
// fingerprint — "<provider>/<ref>", told apart in lower case, as
// accounts are. A key that lists none uses every account, as keys
// always did.
func accountAllowed(who access.Identity, c candidate) bool {
if len(who.Accounts) == 0 {
return true
}
return who.AllowsAccount(c.p.ID, c.p.AccountID())
}
// allowedKey is p sent on the first of its keys in use the calling key
// may use (#905), for the paths that send on one key of the provider
// rather than over its candidates — a video, a drawing — in place of the
// first, which may be one the key may not: a key held to a later one is
// sent on it, and refused only when it may use none. A provider of an
// account keeps its one account, checked as it is; one with no account
// and no key (a local ollama) has nothing to hold. A key's own list of
// models (#474) is not weighed here; the decision path, which gates on
// one, picks its key itself.
func allowedKey(who access.Identity, p provider.Provider, model string) (provider.Provider, bool) {
if p.Key == "" {
return p, p.Account == nil || accountAllowed(who, candidate{p: p, model: model})
}
for _, k := range p.KeysOn() {
if q := p.WithKey(k); accountAllowed(who, candidate{p: q, model: model}) {
return q, true
}
}
return p, false
}
// keyModelError is what a request for a model its key may not use is told.
@@ -136,6 +244,22 @@ func keyModelError(who access.Identity, model string) string {
who.KeyName, model, strings.Join(who.Models, ", "))
}
// keyAccountsError is what a request every candidate of which was an
// account or key its key may not use is told.
func keyAccountsError(who access.Identity, model string) string {
names := provider.AccountNames()
shown := make([]string, len(who.Accounts))
for i, a := range who.Accounts {
if n, ok := names[a]; ok {
shown[i] = n
} else {
shown[i] = a
}
}
return fmt.Sprintf("The gateway key %q is not allowed to use the accounts behind %s: no account or key behind it is one the key may use; it may use %s. Change the key's accounts in magpie's Gateway page, or use an account it has.",
who.KeyName, model, strings.Join(shown, ", "))
}
// countHeld answers the 403 a gateway key held to some models (#882) gets
// 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
+3
View File
@@ -194,6 +194,9 @@ type Weighed struct {
// Barred: left out as the user set it not to serve the model, its
// own list of models leaving it out (#474)
Barred bool `json:"barred,omitempty"`
// Held: left out as the gateway key asking may not use its account or
// key (#905)
Held bool `json:"held,omitempty"`
// Capped: left out as held at the usage cap the user set on the
// account, this cap in percent; Used is then its fullest window's
// share, CapBack when the last window at or past it renews
+10
View File
@@ -524,6 +524,16 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
fail(403, keyModelError(keyWho, f.Model))
return
}
// held to some accounts (#905): sent on a key the calling key may use,
// of those in use — not the provider's first alone, which a key held
// to a later one was refused by — or none, refused
if keyWho, held := accountHolds(r); held {
var ok bool
if p, ok = allowedKey(keyWho, p, model); !ok {
fail(403, keyAccountsError(keyWho, f.Model))
return
}
}
call.Provider, call.To = p.ID, provider.Chat
remote := p.IsRemoteMagpie()
// any grok-imagine-video*, not only those listed: the vendor's newer ones work before magpie names them
+45 -15
View File
@@ -1,5 +1,8 @@
// Caller keys use the same account list and edit controls as provider keys.
let gatewayKeys = null, gatewayKeyDraft = null, gatewayKeysBusy = false;
// gatewayAccountNames maps a key's stored account entry ("<provider>/<id>",
// #905) to how it is shown; what no provider has now is shown as it is kept
let gatewayAccountNames = {};
let gatewayKeysRead = 0;
// gatewayLimit is the key whose limit editor is open, and its draft
// (#585): what is picked in it is sent only by its Save.
@@ -58,6 +61,7 @@ async function gatewayKeyAction(action, body) {
gatewayKeysRead++;
connectSecret = null;
gatewayKeys = out.keys || [];
gatewayAccountNames = out.accountNames || gatewayAccountNames;
gatewayKeyDraft = null;
if (action === "limit-key" || !gatewayKeys.some((k) => k.id === gatewayLimit?.id)) gatewayLimit = null;
renderGatewayKeys();
@@ -192,17 +196,25 @@ function askGatewayKey(k, rotate) {
cancel.focus({ preventScroll: true });
}
// ---- the models a gateway key may use (#882) ----
// ---- the models a gateway key may use (#882), and the accounts (#905) ----
// gatewayModelsBadge picks the models a key may use, in the app's menu:
// "All models" on hover when it may use any, else which it may, always
// shown. A pick is sent when the menu closes.
// accountShown is a stored account entry ("<provider>/<id>", #905) as the
// badge says it: by who is signed in, the id itself when no provider has it.
const accountShown = (a) => gatewayAccountNames[a] || a;
// gatewayModelsBadge picks the models and the accounts a key may use, in
// the app's menu: "All models" on hover when it may use any, else which
// it may, always shown. A pick is sent when the menu closes.
function gatewayModelsBadge(k) {
const ms = k.models || [];
const b = el("button", "amodels key-models" + (ms.length ? " set" : ""));
const as = k.accounts || [];
const b = el("button", "amodels key-models" + (ms.length || as.length ? " set" : ""));
b.type = "button";
b.textContent = !ms.length ? t("All models") : ms.length === 1 ? ms[0] : t("{n} models", { n: ms.length });
b.title = ms.length ? t("Only these models: {list}", { list: ms.join(", ") }) : t("Pick the models this key may use");
b.textContent = !ms.length && !as.length ? t("All models")
: ms.length ? (ms.length === 1 && !as.length ? ms[0] : t("{n} models", { n: ms.length }))
: (as.length === 1 ? accountShown(as[0]) : t("{n} accounts", { n: as.length }));
b.title = (ms.length ? t("Only these models: {list}", { list: ms.join(", ") }) : t("Pick the models this key may use"))
+ (as.length ? "\n" + t("Only these accounts: {list}", { list: as.map(accountShown).join(", ") }) : "");
b.setAttribute("aria-label", t("Models this key may use"));
b.setAttribute("aria-haspopup", "menu");
b.setAttribute("aria-expanded", "false");
@@ -210,10 +222,10 @@ function gatewayModelsBadge(k) {
e.preventDefault();
e.stopPropagation();
if (b.classList.contains("open")) return closeProtoMenu();
let models = [];
try { ({ models } = await api("caller-keys/models")); } catch (err) { status(t(err.message), "err"); return; }
let models = [], accounts = [];
try { ({ models, accounts } = await api("caller-keys/models")); } catch (err) { status(t(err.message), "err"); return; }
if (!b.isConnected) return;
const opts = [{ v: "", name: "All models", note: "Any model, now and later" }];
const opts = [{ v: "", name: "All models", note: "Any model and any account, now and later" }];
const seen = new Set();
for (const m of models || []) {
// a routing group the key names is its with every member in it
@@ -232,12 +244,30 @@ function gatewayModelsBadge(k) {
}
opts.push({ v: m.id, name: m.name, note: m.id, literalName: true });
}
// what the CLI kept that the list hasn't, a pattern or a model gone
// the accounts and keys the key may be held to (#905), after the
// models: an account by who is signed in, a key by its fingerprint
const accountsSet = new Set();
for (const a of accounts || []) {
accountsSet.add(a.id);
opts.push({ v: a.id, name: a.name, note: a.plan ? a.providerName + " · " + a.plan : a.providerName, literalName: true });
}
// what the CLI kept that the list hasn't, a pattern, a model gone or
// an account signed out
for (const v of ms) if (!opts.some((o) => o.v === v)) opts.push({ v, name: v, note: "Not served now", literalName: true });
openProtoMenu(b, opts, ms, (picked) => {
gatewayKeyAction("models-key", { key: k.id, models: picked }).then((out) => {
if (out) status(t(picked.length ? "{name} may use only the models picked" : "{name} may use every model", { name: k.name }), "ok");
});
for (const v of as) if (!accountsSet.has(v)) { accountsSet.add(v); opts.push({ v, name: v, note: "Not signed in now", literalName: true }); }
openProtoMenu(b, opts, [...ms, ...as], (picked) => {
// one action at a time: gatewayKeyAction is busy while one is sent.
// The accounts are sent only when they changed: a model picked says
// nothing of the key's accounts.
(async () => {
const pickedModels = picked.filter((v) => !accountsSet.has(v));
const pickedAccounts = picked.filter((v) => accountsSet.has(v));
const out = await gatewayKeyAction("models-key", { key: k.id, models: pickedModels });
if (out) status(t(pickedModels.length ? "{name} may use only the models picked" : "{name} may use every model", { name: k.name }), "ok");
if (pickedAccounts.length !== as.length || pickedAccounts.some((v) => !as.includes(v))) {
await gatewayKeyAction("accounts-key", { key: k.id, accounts: pickedAccounts });
}
})();
}, "Models this key may use", "sess-menu", "right");
};
return b;
+15
View File
@@ -74,6 +74,9 @@ const I18N = {
"Pick the models this key may use": "选择此密钥可用的模型",
"Only these models: {list}": "仅限这些模型:{list}",
"Any model, now and later": "任何模型,包括以后添加的",
"Any model and any account, now and later": "任何模型和任何账号,包括以后添加的",
"Only these accounts: {list}": "仅限这些账号:{list}",
"Not signed in now": "当前未登录",
"Every {provider} model": "{provider} 的全部模型",
"Every routing group": "全部路由组",
"Not served now": "当前未提供",
@@ -2760,6 +2763,8 @@ const I18N = {
"set to serve other models, not {model}": "已设为只用于其他模型,不含 {model}",
"{who} is left out: it is set to serve other models, not {model}.": "{who} 不参与:它已设为只用于其他模型,不含 {model}。",
"held at its {cap}% usage cap": "已达 {cap}% 用量上限",
"not an account the gateway key may use": "不是该网关密钥可用的账号",
"{who} is left out: the gateway key asking may not use its account.": "{who} 被排除:发起请求的网关密钥不能使用它的账号。",
"{who} is left out: a usage window is at {n}, past the {cap}% cap set on the account, so it counts as used up until that window renews.": "{who} 不参与:某个用量窗口已用 {n},超过该账号的 {cap}% 上限,窗口重置前视为已用完。",
"No cap": "不设上限",
"Cap {n}%": "上限 {n}%",
@@ -3493,6 +3498,9 @@ const I18N = {
"Pick the models this key may use": "このキーで使えるモデルを選ぶ",
"Only these models: {list}": "これらのモデルのみ:{list}",
"Any model, now and later": "今後追加されるものも含め、すべてのモデル",
"Any model and any account, now and later": "今後追加されるものも含め、すべてのモデルとアカウント",
"Only these accounts: {list}": "これらのアカウントのみ:{list}",
"Not signed in now": "今はサインインしていない",
"Every {provider} model": "{provider} のすべてのモデル",
"Every routing group": "すべてのルーティンググループ",
"Not served now": "現在は提供されていません",
@@ -6169,6 +6177,8 @@ const I18N = {
"set to serve other models, not {model}": "{model} ではなく他のモデル用に設定",
"{who} is left out: it is set to serve other models, not {model}.": "{who} は除外:{model} ではなく他のモデル用に設定されています。",
"held at its {cap}% usage cap": "使用量上限 {cap}% で停止中",
"not an account the gateway key may use": "ゲートウェイキーが使えるアカウントではありません",
"{who} is left out: the gateway key asking may not use its account.": "{who} は外されています:リクエストしたゲートウェイキーはそのアカウントを使えません。",
"{who} is left out: a usage window is at {n}, past the {cap}% cap set on the account, so it counts as used up until that window renews.": "{who} は除外:使用量ウィンドウの 1 つが {n} で、アカウントに設定された上限 {cap}% を超えているため、そのウィンドウが更新されるまで使い切ったものとみなします。",
"No cap": "上限なし",
"Cap {n}%": "上限 {n}%",
@@ -6907,6 +6917,9 @@ const I18N = {
"Pick the models this key may use": "Modelle wählen, die dieser Schlüssel nutzen darf",
"Only these models: {list}": "Nur diese Modelle: {list}",
"Any model, now and later": "Jedes Modell, auch künftige",
"Any model and any account, now and later": "Jedes Modell und jedes Konto, auch künftige",
"Only these accounts: {list}": "Nur diese Konten: {list}",
"Not signed in now": "Derzeit nicht angemeldet",
"Every {provider} model": "Alle Modelle von {provider}",
"Every routing group": "Alle Weiterleitungsgruppen",
"Not served now": "Derzeit nicht angeboten",
@@ -9585,6 +9598,8 @@ const I18N = {
"set to serve other models, not {model}": "nur für andere Modelle eingestellt, nicht für {model}",
"{who} is left out: it is set to serve other models, not {model}.": "{who} wird übergangen: nur für andere Modelle eingestellt, nicht für {model}.",
"held at its {cap}% usage cap": "am Nutzungslimit von {cap} % angehalten",
"not an account the gateway key may use": "kein Konto, das dieser Zugangsschlüssel nutzen darf",
"{who} is left out: the gateway key asking may not use its account.": "{who} wird übergangen: der fragende Zugangsschlüssel darf sein Konto nicht nutzen.",
"{who} is left out: a usage window is at {n}, past the {cap}% cap set on the account, so it counts as used up until that window renews.": "{who} wird übergangen: Ein Zeitfenster steht bei {n}, über dem für das Konto gesetzten Limit von {cap} %, und gilt daher bis zu seiner Erneuerung als aufgebraucht.",
"No cap": "Kein Limit",
"Cap {n}%": "Limit {n} %",
+4 -2
View File
@@ -298,7 +298,7 @@
// from its vendor does — relays list each key its own group's models
// or the user set the account or key to serve other models only (#474)
// or it is held at the usage cap the user set on the account
const unlistedWord = (w) => w.capped ? t("held at its {cap}% usage cap", { cap: w.capped }) : w.barred ? t("set to serve other models, not {model}", { model: w.model }) : w.kind === "key" ? t("{name}'s list for this key has no {model}", { name: w.name, model: w.model }) : t("its plan doesn't list {model}", { model: w.model });
const unlistedWord = (w) => w.held ? t("not an account the gateway key may use") : w.capped ? t("held at its {cap}% usage cap", { cap: w.capped }) : w.barred ? t("set to serve other models, not {model}", { model: w.model }) : w.kind === "key" ? t("{name}'s list for this key has no {model}", { name: w.name, model: w.model }) : t("its plan doesn't list {model}", { model: w.model });
const group = (w) => w.used >= 98 ? "spent" : w.used >= 90 ? "low" : "fine";
const renews = (w) => (w.renews || []).map((s) => known0(s) ? at(s) : 0);
// renewsBy is renews as Smart ranks them: an auto-used Codex reset that
@@ -435,7 +435,9 @@
}
const pooled = r.order.find((x) => !x.aside && x.kind === "key");
for (const x of r.order.filter((x) => x.aside)) out.push(t("{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.", { who: who(x), api: API[x.speaks] || x.speaks || t("any API"), other: API[pooled?.speaks] || pooled?.speaks || t("any API") }));
for (const x of r.left || []) out.push(x.capped
for (const x of r.left || []) out.push(x.held
? t("{who} is left out: the gateway key asking may not use its account.", { who: who(x) })
: x.capped
? t("{who} is left out: a usage window is at {n}, past the {cap}% cap set on the account, so it counts as used up until that window renews.", { who: who(x), n: pct(x.used), cap: x.capped })
: x.barred
? t("{who} is left out: it is set to serve other models, not {model}.", { who: who(x), model: x.model })
+51
View File
@@ -69,3 +69,54 @@ func TestCallerKeyModelsRoutes(t *testing.T) {
t.Fatal("every model", w.Code, w.Body)
}
}
// The Gateway page lists the accounts and keys a key can be held to
// (#905), and keeps what was picked for it. An account's stable id, shown
// by who is signed in, is exercised against a real sign-in in the
// gateway's tests; a key's fingerprint is one here.
func TestCallerKeyAccountsRoutes(t *testing.T) {
sandboxHome(t)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "http://127.0.0.1:1/v1", Keys: []provider.KeyAccount{{Key: "sk-1", Name: "First"}, {Key: "sk-2", Name: "Second"}}}); err != nil {
t.Fatal(err)
}
mux := http.NewServeMux()
callerKeyRoutes(mux)
request := func(method, path, body string) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
return w
}
k1, k2 := provider.KeyID("sk-1"), provider.KeyID("sk-2")
var l struct{ Accounts []keyModelJSON }
if w := request("GET", "/api/caller-keys/models", ""); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &l) != nil {
t.Fatal(w.Code, w.Body)
}
var ids []string
for i, a := range l.Accounts {
ids = append(ids, a.ID)
if !a.Key || a.Account || a.Provider != "relay" || a.ProviderName != "Relay" || a.Name != []string{"First", "Second"}[i] {
t.Fatalf("key %+v", a)
}
}
if !slices.Equal(ids, []string{"relay/" + k1, "relay/" + k2}) {
t.Fatal("accounts", ids)
}
var s struct{ Keys []access.Key }
if w := request("POST", "/api/caller-keys/add-key", `{"name":"Phone"}`); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &s) != nil {
t.Fatal(w.Code, w.Body)
}
id := s.Keys[0].ID
if w := request("POST", "/api/caller-keys/accounts-key", `{"key":"`+id+`","accounts":["relay/First","relay/`+k2+`"]}`); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &s) != nil {
t.Fatal(w.Code, w.Body)
}
if !slices.Equal(s.Keys[0].Accounts, []string{"relay/" + k1, "relay/" + k2}) {
t.Fatal("kept", s.Keys[0].Accounts)
}
if w := request("POST", "/api/caller-keys/accounts-key", `{"key":"`+id+`","accounts":["relay/`+provider.KeyID("sk-9")+`"]}`); w.Code != 400 || !strings.Contains(w.Body.String(), "has no key") {
t.Fatal("accepted a key the provider has not", w.Code, w.Body.String())
}
var free struct{ Keys []access.Key }
if w := request("POST", "/api/caller-keys/accounts-key", `{"key":"`+id+`","accounts":[]}`); w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &free) != nil || free.Keys[0].Accounts != nil {
t.Fatal("every account", w.Code, w.Body)
}
}
+21 -5
View File
@@ -26,6 +26,9 @@ type keyModelJSON struct {
Provider string `json:"provider,omitempty"`
ProviderName string `json:"providerName,omitempty"`
Group bool `json:"group,omitempty"` // a routing group (Magic_zero on Discord)
Account bool `json:"account,omitempty"` // a signed-in account the key may be held to (#905)
Key bool `json:"key,omitempty"` // one of a provider's keys, by its KeyID
Plan string `json:"plan,omitempty"` // the account's subscription, for the menu's note
}
func withLimits(keys []access.Key) []keyRow {
@@ -46,13 +49,15 @@ func callerKeyRoutes(mux *http.ServeMux) {
fail(w, err)
return
}
writeJSON(w, map[string]any{"keys": withLimits(keys)})
writeJSON(w, map[string]any{"keys": withLimits(keys), "accountNames": provider.AccountNames()})
})
// the models a key may be held to (#882): the routing groups, then
// each provider's; a group the key names is its with every member
// the models a key may be held to (#882), and the accounts and keys
// (#905): the routing groups, then each provider's models, then its
// accounts and keys; a group the key names is its with every member
mux.HandleFunc("GET /api/caller-keys/models", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
out := []keyModelJSON{}
accounts := []keyModelJSON{}
for _, e := range provider.Catalog() {
if e.Group != "" {
out = append(out, keyModelJSON{ID: e.ID, Name: cmp.Or(e.Name, e.Group), Group: true})
@@ -60,7 +65,18 @@ func callerKeyRoutes(mux *http.ServeMux) {
}
out = append(out, keyModelJSON{ID: e.Provider.ID + "/" + e.Model, Name: cmp.Or(e.Name, e.Model), Provider: e.Provider.ID, ProviderName: cmp.Or(e.Provider.Name, e.Provider.ID)})
}
writeJSON(w, map[string]any{"models": out})
for _, p := range provider.All() {
if !p.On() {
continue
}
name := cmp.Or(p.Name, p.ID)
// an account by its stable id, kept through renames, shown by who
// is signed in; a key by its fingerprint
for _, a := range p.AccountIDs() {
accounts = append(accounts, keyModelJSON{ID: p.ID + "/" + a.ID, Name: a.User, Provider: p.ID, ProviderName: name, Account: !a.Key, Key: a.Key, Plan: a.Plan})
}
}
writeJSON(w, map[string]any{"models": out, "accounts": accounts})
})
mux.HandleFunc("POST /api/caller-keys/{action}", func(w http.ResponseWriter, r *http.Request) {
var in access.Change
@@ -80,6 +96,6 @@ func callerKeyRoutes(mux *http.ServeMux) {
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, map[string]any{"keys": withLimits(keys), "secret": secret})
writeJSON(w, map[string]any{"keys": withLimits(keys), "accountNames": provider.AccountNames(), "secret": secret})
})
}
+10 -2
View File
@@ -14,7 +14,10 @@ function fixture(lang, theme, events, options = {}) {
{ id: "server", name: "Server", masked: "sk-magpie-key-…222222" },
{ id: "work", name: "Work", masked: "sk-magpie-key-…333333" },
];
for (const k of keys) if (options.limits?.[k.id]) Object.assign(k, options.limits[k.id]);
for (const k of keys) {
if (options.limits?.[k.id]) Object.assign(k, options.limits[k.id]);
if (options.keyHolds?.[k.id]) Object.assign(k, options.keyHolds[k.id]);
}
let serial = 0;
let lan = !!options.lan;
let lanKeyID = "", rotations = 0, lanSecret = "";
@@ -90,6 +93,10 @@ function fixture(lang, theme, events, options = {}) {
{ id: "relay/m", name: "Model", provider: "relay", providerName: "Relay" },
{ id: "relay/m-mini", name: "Model mini", provider: "relay", providerName: "Relay" },
{ id: "openai/gpt-5", name: "GPT-5", provider: "openai", providerName: "OpenAI" },
], accounts: options.accounts === false ? [] : [
{ id: "relay/me@example.com", name: "me@example.com", provider: "relay", providerName: "Relay", account: true, plan: "Pro" },
{ id: "relay/spare@example.com", name: "spare@example.com", provider: "relay", providerName: "Relay", account: true },
{ id: "openai/k-1a2b3c", name: "k-1a2b3c", provider: "openai", providerName: "OpenAI", key: true },
] });
if (url.pathname.startsWith("/api/caller-keys/")) {
const action = url.pathname.split("/").at(-1), body = req.postDataJSON();
@@ -118,7 +125,8 @@ function fixture(lang, theme, events, options = {}) {
k.used = body.limit ? { period: body.limit.period, start: new Date().toISOString(), reset: new Date(Date.now() + 864e5).toISOString(),
calls: 0, tokens: 0, cost: 0, tokenLimit: body.limit.tokens, costLimit: body.limit.cost, tokensLeft: body.limit.tokens, costLeft: body.limit.cost, spent: false } : undefined;
}
if (action === "models-key") k.models = body.models.length ? body.models : undefined;
if (action === "models-key") k.models = body.models?.length ? body.models : undefined;
if (action === "accounts-key") k.accounts = body.accounts?.length ? body.accounts : undefined;
if (action === "copy-key") secret = k.id === lanKeyID ? lanSecret : secrets.get(k.id);
return json({ keys, secret });
}
@@ -0,0 +1,92 @@
// A gateway key can be held to some accounts (#905): the key's models
// menu lists the accounts and keys after the models, a plan in their
// note, and what is picked is sent as "accounts-key" — "All models"
// takes them all off, a model picked alone leaves the accounts as they
// were.
const assert = require("node:assert/strict");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { fixture } = require("./fixtures/caller-keys.cjs");
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
test(`${engine} ${lang}: a gateway key is held to the accounts picked for it`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 1000, height: 600 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(6000);
const events = [], errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", fixture(lang, "light", events, { lan: true, keyHolds: { server: { accounts: ["relay/me@example.com"] } } }));
const zh = lang === "zh";
const w = zh
? { label: "此密钥可用的模型", all: "全部模型", off: "当前未登录" }
: { label: "Models this key may use", all: "All models", off: "Not signed in now" };
await page.goto("http://magpie.test/?view=gateway");
await page.locator("#gatewayKeys .acc[data-key]").last().waitFor();
const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`);
// what the menu sends on close is sent asynchronously: wait for it
const until = async (fn) => {
for (let i = 0; i < 150 && !fn(); i++) await new Promise((r) => setTimeout(r, 20));
};
const badge = (id) => row(id).getByRole("button", { name: w.label, exact: true });
// a key held to one account says which
assert.equal((await badge("server").textContent()).trim(), "relay/me@example.com");
assert.match(await badge("server").getAttribute("title"), /relay\/me@example\.com/);
const view = page.locator("#view-gateway");
const scrolled = async () => [await view.evaluate((v) => v.scrollTop), await page.evaluate(() => window.scrollY)];
await row("work").hover();
await badge("work").click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
assert.equal(await page.locator("select").count(), 0, "no native select");
// the accounts come after the models, an account by who is signed
// in with their plan in the note, a key by its fingerprint
const names = (await menu.locator(".pm-item").allTextContents()).map((s) => s.trim());
const at = (s) => names.findIndex((n) => n.includes(s));
assert(at("me@example.com") > at("GPT-5"), names.join(" | "));
assert.match(names[at("me@example.com")], /Pro/);
assert(at("spare@example.com") > at("me@example.com"), names.join(" | "));
assert(at("k-1a2b3c") > at("spare@example.com"), names.join(" | "));
await menu.locator(".pm-item", { hasText: "spare@example.com" }).click();
await page.keyboard.press("Escape");
await menu.waitFor({ state: "detached" });
await until(() => events.some((e) => e.action === "accounts-key"));
assert.deepEqual(events.filter((e) => e.action === "accounts-key").map((e) => e.body), [{ key: "work", accounts: ["relay/spare@example.com"] }]);
// a model picked alone leaves the key's accounts as they were
events.length = 0;
await row("work").hover();
await badge("work").click();
await menu.waitFor();
await menu.locator(".pm-item", { hasText: "GPT-5" }).click();
await page.keyboard.press("Escape");
await menu.waitFor({ state: "detached" });
await until(() => events.some((e) => e.action === "models-key"));
assert.deepEqual(events.filter((e) => e.action === "models-key").map((e) => e.body), [{ key: "work", models: ["openai/gpt-5"] }]);
assert.equal(events.filter((e) => e.action === "accounts-key").length, 0, "a model pick sent the accounts");
// a key held to an account has it ticked; All models takes them
// all off, models and accounts
await badge("server").click();
await menu.waitFor();
assert.deepEqual((await menu.locator(".pm-item.on").allTextContents()).map((s) => s.trim()), ["me@example.comRelay · Pro"]);
await menu.locator(".pm-item", { hasText: "me@example.com" }).click();
await menu.locator(".pm-item", { hasText: "k-1a2b3c" }).click();
await page.keyboard.press("Escape");
await menu.waitFor({ state: "detached" });
await until(() => events.filter((e) => e.action === "accounts-key").length > 0 && events.filter((e) => e.action === "accounts-key").at(-1).body.key === "server");
assert.deepEqual(events.filter((e) => e.action === "accounts-key").at(-1).body, { key: "server", accounts: ["openai/k-1a2b3c"] });
await badge("server").click();
await menu.waitFor();
await menu.locator(".pm-item", { hasText: w.all }).first().click();
await menu.waitFor({ state: "detached" });
await until(() => events.some((e) => e.action === "accounts-key" && e.body.key === "server" && !e.body.accounts.length));
assert.deepEqual(events.filter((e) => e.action === "models-key").at(-1).body, { key: "server", models: [] });
assert.deepEqual(events.filter((e) => e.action === "accounts-key").at(-1).body, { key: "server", accounts: [] });
assert.equal((await badge("server").textContent()).trim(), zh ? "全部模型" : "All models");
assert.deepEqual(await scrolled(), [await view.evaluate((v) => v.scrollTop), await page.evaluate(() => window.scrollY)], "a click moved the page");
const lefts = await page.locator("#gatewayKeys .key-models, .proto-menu .pm-item").evaluateAll((els) => els.map((e) => getComputedStyle(e).borderLeftStyle));
assert(lefts.every((s) => s === "none"), "a coloured left border");
assert.deepEqual(errors, []);
});
}
}
+65
View File
@@ -9,6 +9,7 @@ package provider
// (gateway/fallback.go).
import (
"cmp"
"fmt"
"slices"
"strings"
@@ -47,6 +48,70 @@ func (p Provider) AccountRefs() []string {
return out
}
// AccountRef is one of a provider's accounts or keys as a gateway key's
// account list knows it (#905): ID what the list keeps — an account's
// stable id, kept through renames, a key's fingerprint — User and Plan
// what it is shown as.
type AccountRef struct {
ID string
User string
Plan string
Key bool // one of the provider's keys, not a signed-in account
}
// AccountIDs are the provider's accounts and keys as a gateway key's
// account list knows them (#905): an account by its stable id, a key by
// its fingerprint, with the name and plan each is shown by.
func (p Provider) AccountIDs() []AccountRef {
var out []AccountRef
if p.Account == nil {
for _, k := range p.KeyList() {
out = append(out, AccountRef{ID: k.ID, User: cmp.Or(k.Name, k.Masked), Key: true})
}
return out
}
agent := p.Account.Agent
if p.IsPlugin() {
agent = p.ID
}
if p.Account.User != "" {
out = append(out, AccountRef{ID: LoginID(agent, p.Account.User), User: p.Account.User, Plan: p.Account.Plan})
}
for _, l := range Logins(agent) {
if !slices.ContainsFunc(out, func(r AccountRef) bool { return accountKey(r.User) == accountKey(l.User) }) {
out = append(out, AccountRef{ID: LoginID(agent, l.User), User: l.User, Plan: l.Plan})
}
}
return out
}
// AccountID is the stable id of p's account or key as a gateway key's
// account list knows it (#905): the account's, kept through renames, or
// a key's fingerprint.
func (p Provider) AccountID() string {
if a := p.Account; a != nil && a.User != "" {
agent := a.Agent
if p.IsPlugin() {
agent = p.ID
}
return LoginID(agent, a.User)
}
return KeyID(p.Key)
}
// AccountNames maps every account and key a gateway key may name (#905),
// "<provider>/<id>", to how it is shown, "<provider>/<user>"; what no
// provider has now maps to itself.
func AccountNames() map[string]string {
out := map[string]string{}
for _, p := range All() {
for _, a := range p.AccountIDs() {
out[p.ID+"/"+a.ID] = p.ID + "/" + a.User
}
}
return out
}
// accountRef is the account or key of p that ref names: a signed-in
// account by its name, a key by its KeyID or its name, in any case.
func (p Provider) accountRef(ref string) (string, bool) {
+37
View File
@@ -10,6 +10,8 @@ package provider
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -57,6 +59,12 @@ type Login struct {
}
type savedLogin struct {
// ID is the account's stable id (#905): set once it is written, and
// kept as it is when the account is renamed or its plan changes — a
// gateway key held to accounts names it by this, not by a name that
// moves. Until the logins are next written, one made of the name
// stands in, so an entry made before stands.
ID string `json:"id,omitempty"`
// Order is the user-arranged routing order within this agent. Zero keeps
// the original alphabetical order for accounts not arranged yet.
Order int `json:"order,omitempty"`
@@ -112,6 +120,30 @@ var (
// switchable agents: those whose sign-in magpie can save and put back.
var loginAgents = []string{"claude", "codex"}
// loginID is the account's stable id (#905): the one saved with it, or a
// stand-in made of its name until the logins are next written — set then,
// and kept through renames.
func loginID(l savedLogin) string {
if l.ID != "" {
return l.ID
}
sum := sha256.Sum256([]byte("magpie login\n" + l.Agent + "\n" + accountKey(l.User)))
return hex.EncodeToString(sum[:8])
}
// LoginID is the stable id of an agent's account known by its name
// (#905): the login's, kept through renames, or one made of the name
// for an account whose logins haven't been written since — and for an
// agent that keeps its accounts elsewhere, made of the name always.
func LoginID(agent, user string) string {
for _, l := range readLogins() {
if l.Agent == agent && accountKey(l.User) == accountKey(user) {
return loginID(l)
}
}
return loginID(savedLogin{Agent: agent, User: user})
}
func loginsPath() string { return filepath.Join(filepath.Dir(Path()), "logins.json") }
// lastLogins is the accounts last read from logins.json: a read that fails
@@ -169,6 +201,11 @@ func keepUnreadLogins(path string) {
}
func writeLogins(ls []savedLogin) error {
// every account gets its stable id before it is written (#905): the
// one it has, or the stand-in made of its name, there to stay
for i := range ls {
ls[i].ID = loginID(ls[i])
}
sort.SliceStable(ls, func(i, j int) bool {
if ls[i].Agent != ls[j].Agent {
return ls[i].Agent < ls[j].Agent
+34
View File
@@ -0,0 +1,34 @@
package provider
import (
"testing"
)
// An account's stable id (#905) is set once its login is written and kept
// through a rename: a gateway key held to accounts names it by that, not
// by a name that moves. Until the logins are written, one made of the
// name stands in.
func TestLoginIDStable(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
if err := writeLogins([]savedLogin{{Agent: "codex", User: "me@example.com"}, {Agent: "codex", User: "spare@example.com", On: true}}); err != nil {
t.Fatal(err)
}
ls := readLogins()
if ls[0].ID == "" || ls[1].ID == "" || ls[0].ID == ls[1].ID {
t.Fatalf("written without ids: %+v", ls)
}
id := ls[0].ID
ls[0].User = "renamed@example.com"
if err := writeLogins(ls); err != nil {
t.Fatal(err)
}
if got := LoginID("codex", "renamed@example.com"); got != id {
t.Fatalf("a rename moved the id: %s, was %s", got, id)
}
// a name no account has is one of no account's: another id, matching
// nothing a candidate carries
if got := LoginID("codex", "other@example.com"); got == id {
t.Fatal("another account had the same id")
}
}