Files
magpie/internal/access/accounts.go
T
yetone 85e37162e9 routing: a route group can be held to chosen accounts (duanckham on X)
duanckham has a personal and a company GPT account, one tool and one
gateway, and wants a group's GPT models to spend only the company
account (or only his own). A second gateway key doesn't fit: his tool
talks to one gateway, and a local agent needs no key at all.

Group.Accounts holds a group to some accounts or keys of the providers
it names, in a gateway key's form and by the key's rule (#905,
Identity.AllowsAccount). The asked group narrows the request's
identity (access.Identity.HeldToGroup: the strict intersection with
the key's own list; "<provider>/\x00" when they share none), so every
gate a key's accounts go through holds the group's too: chat,
responses, messages, count_tokens, embeddings, images and video,
streamed or not. A group reached inside another, as a member or a
fallback, is held in planLevel (hold, Member.Via): its candidates on
an excluded account are Held rows with Weighed.HeldBy, which the
Routing trace tells. Fallback stays within the group's entries; with
every allowed account resting or out the group's usual error comes
back, and a key and a group that share no account get a 403 naming
the group, nothing asked upstream. SaveGroup resolves each entry
(ResolveAccount, shared with the key's CleanAccounts); share and
import drop them. A group without accounts is as before.

GUI: the group editor's Accounts section, a row per member provider
with two or more accounts, "Any of its accounts" until some are ticked
in the app menu (openPicker multi). Every save sends accounts, since a
save replaces the group. Strings in all five languages.

Gateway keys stay as they are: Gateway › "Gateway keys are for other
computers … added here once Share on local network is on" already says
where, and this case needs none.

Run (mote, through mote-run), at cafed0067 on origin/main 9d08993c8:
- gofmt -l internal/: clean. go vet of access, gateway, provider,
  gui; GOOS=linux -tags nogui and GOOS=windows go vet ./internal/...:
  ok.
- go test -count=1 ./internal/access ./internal/provider
  ./internal/gateway ./internal/gui: access, provider, gateway ok; gui
  red only on TestMainWindowCorners/macOS_26_SDK, red on main too
  (#3949, mote's macOS 27).
- node --test group-*.test.cjs routing-group-*.test.cjs
  routing-save*.test.cjs i18n-keys.test.cjs: 433/434. The one red is
  group-found-skip "webkit de 390px: a provider left out of found
  groups" (the clicks moved the page), filed as #4617 from main; the
  file alone passes 20/20 here and on main 94f6f6092.
  group-accounts.test.cjs is 30/30 (Chromium and WebKit; en, zh,
  zh-TW, ja, de; 1100 and 420px; no scroll on the clicks, no sideways
  scroll, the save carries accounts).
- Earlier, at base 5a0c79ed9: go test -timeout 45m ./... all ok but
  TestVisionBridgePassesLines and TestSettingsSaveKeepsWhatItDoesNot-
  Send (fixed on main by 0b783b1dd and b646a9127; both pass after the
  rebase) and TestMainWindowCorners (#3949).
- The whole GUI suite was cut short twice (a wiped scratchpad, then a
  mote reboot). Its runs at load ~140-220 had about 35 reds, none in a
  file this change touches (account-mask, balance-fix, lan-*, the
  #4617 test among them); not chased here.
- Sandbox HOME on mote, the built binary (`magpie serve`, MAGPIE_ADDR
  on a free port) with a fake upstream answering with the key it got:
  group/work and Work -> sk-work (3 of 3), group/mine and relay/m ->
  sk-mine.

- Rebased again onto 8826a15ea (no file in common): go vet of gui,
  provider, gateway; go test -run 'TestGroupAccounts|TestHeldToGroup|
  TestCleanAccounts|Budget|TestGroup' of gateway, access, provider,
  gui: ok; group-accounts and i18n-keys GUI files: 34/34.

- Rebased onto ec104b862 (trace.go and gateway-routing.md in common,
  merged clean): gofmt clean; go vet of gateway for darwin, windows,
  linux nogui; go test -count=1 ./internal/gateway: ok (640s).

- Rebased onto 2b52302dc, then da275848b (no file in common): go vet ./internal/...,
  the TestGroupAccounts/TestHeldToGroup/Budget tests, group-accounts
  and i18n-keys GUI files: ok, 34/34.

Broken by hand, each red, then restored:
- serve's heldByGroup: three TestGroupAccounts* tests red (sk-mine spent).
- count_tokens' heldByGroupAt: the count_tokens route red.
- planLevel's hold: the nested "outer" group red.
- the editor save without accounts: group-accounts.test.cjs red.

Not tried: a real Codex or OpenAI account (the fake upstream stands
in); a CLI `magpie group set accounts=` (no CLI for it yet); a
provider's own fallback naming a held group has no test of its own
(planFallbackGroup passes the group as hold, the same path as nested).
2026-11-01 21:36:32 +08:00

157 lines
5.1 KiB
Go

package access
import (
"errors"
"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")
}
kept, err := provider.ResolveAccount(pid, ref)
if err != nil {
return nil, err
}
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
}
// heldToNone is the account an entry "<provider>/<heldToNone>" names: none
// a provider has, so the list names the provider and allows none of it.
const heldToNone = "\x00"
// HeldToGroup is who held to a routing group's accounts too (accounts,
// a Group's Accounts, in the key's form): a provider the group names is
// used only on the accounts the group names that the key may use as well,
// none when the two share none, never one either leaves out; a provider
// only the key names, on the key's; one neither names, on every account
// it has. Group is set to the group's name, for the error to say whose
// accounts held the request. A group naming no account is who as it is.
// Everything that holds a request to its key's accounts
// (AllowsAccount) holds it to the group's then, by the one rule.
func (who Identity) HeldToGroup(group string, accounts []string) Identity {
named := map[string][]string{} // a provider the group names, in lower case: its entries as written
var order []string
for _, a := range accounts {
a = strings.TrimSpace(a)
pid, ref, ok := strings.Cut(a, "/")
if pid = strings.ToLower(pid); !ok || pid == "" || ref == "" {
continue
}
if _, seen := named[pid]; !seen {
order = append(order, pid)
}
named[pid] = append(named[pid], a)
}
if len(order) == 0 {
return who
}
var out []string
for _, a := range who.Accounts {
if pid, _, _ := strings.Cut(strings.TrimSpace(a), "/"); named[strings.ToLower(pid)] == nil {
out = append(out, a)
}
}
for _, pid := range order {
some := false
for _, a := range named[pid] {
_, ref, _ := strings.Cut(a, "/")
if who.AllowsAccount(pid, ref) && !slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, a) }) {
out, some = append(out, a), true
}
}
if !some {
out = append(out, pid+"/"+heldToNone)
}
}
who.Accounts, who.Group = out, group
return who
}
// ShownAccounts is who's accounts as a message lists them: the entries
// HeldToGroup adds to name a provider with none of its accounts left out.
func (who Identity) ShownAccounts() []string {
return slices.DeleteFunc(slices.Clone(who.Accounts), func(a string) bool { return strings.HasSuffix(a, "/"+heldToNone) })
}
// ReplaceAccount moves every key's account list from one of provider
// pid's keys to the fingerprint it has now (#1869: the key's value
// replaced in place), so a key held to it is held to it still. It
// returns how many keys it moved.
func ReplaceAccount(pid, was, now string) (int, error) {
if was == now {
return 0, nil
}
mu.Lock()
defer mu.Unlock()
keys, err := load()
if err != nil {
return 0, err
}
old := strings.ToLower(pid + "/" + was)
moved := 0
for i := range keys {
for j, a := range keys[i].Accounts {
if strings.ToLower(strings.TrimSpace(a)) == old {
keys[i].Accounts[j] = pid + "/" + now
moved++
}
}
}
if moved == 0 {
return 0, nil
}
return moved, save(keys)
}