gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue

xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.

A gateway key can now expire (Key.Expires) and can be issued under
another key (Key.Issuer). It lives from 1m to 30d. It can be held to a
set of models, a set of accounts, tokens or cost over its whole life
(one "hours" limit as long as its life), and read-only.

- POST /v1/magpie/keys {"ttl":"1h"|3600, name, models, accounts, tokens,
  cost, readOnly} answers 201 with the secret once, no-store. GET lists
  the caller's keys, masked. DELETE /v1/magpie/keys/{id} revokes one.
- magpie gateway-key issue --ttl 1h [--name] [--models] [--accounts]
  [--tokens] [--cost] [--read-only] [--from <id>] [--json] prints the key
  alone. gateway-key issuer <id> on|off lets a key issue keys. list shows
  until/expired/issued by.

Who may issue:
- a key the user let issue (Issues), from wherever that key is let in,
  so a container or CI can;
- with no key, a request that profileRefused passes: loopback, no
  forwarding header, no Origin/Sec-Fetch/Mozilla marks, a loopback Host.
  Such a request can already use every model with no key and run the CLI,
  so it gains nothing.
Never: a page, another computer without such a key, a key not let issue,
an issued or expiring key, or a read-only key (readOnlyGuard).

An issued key never outlives or exceeds its issuer. IssueKey clamps its
expiry and refuses models and accounts the issuer can't use. On every
authentication (access.Check, under Authenticate and On), identityOf
folds the key into its issuer as the issuer is now: models, accounts,
read-only, quotas and expiry. An issuer that is off, removed or expired
refuses its keys. Spend counts against the issuer too: the new usage
field callerIssuerId, budget.read/Append counting both keys, and Reserve
reserving on both. /v1/magpie/limit answers expires and issuerLimits.

An expired or refused key gets 401 with why ("… expired at …: ask for a
new one") on every route, from loopback too. Otherwise a held sandbox
whose key ran out would be let in as no key. Expired keys are pruned
after an hour (every 10 minutes while serving, and on each issue).
rowText packs CallerIssuerID: without it, usage.Visit returned the field
empty and the issuer's limit counted none of its keys' calls.

Docs: gateway-routing.md has "Short-lived gateway keys" and the
/v1/magpie stats API table. site/public/docs remote has "Short-lived
keys" and "Stats API" in en, zh and ja. GitHub OIDC is filed as #4531.

Run at base 07a3312c5 (origin/main, fetched just before):
- mote: go test -count=1 -timeout 45m on access, budget, gwbudget,
  usage, cli, gateway, davsync, agent: ok.
- mote: internal/gui fails TestCoreScriptBudget (#4526),
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and ten AppKit window
  tests killed at their deadline (#4125, #2645). The first three fail the
  same at origin/main 07a3312c5 on mote. This change touches no GUI file.
- mote: gofmt -l clean; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; node --test site/*.test.mjs (49
  pass).
- win-run: access and budget ok. usage fails TestDesktopSessionAccountMetadata
  the same at origin/main (#1356). cli's TestLibraryMCPHub failed once on
  TempDir cleanup (#4140) and passed alone.
- Real binary on mote, sandbox HOME, port 47811: issued a 1m key with
  curl, read its limit, listed it, saw `gateway-key list` show "until",
  had a page's Origin refused 403, and after 62s /v1/models answered 401
  "the gateway key "sandbox-1" expired at …".

Broken by hand, each restored:
- no expiry check in Check: TestIssuedKeyExpires and
  TestIssuedKeyExpiresOnEveryRoute go red.
- no 401 for a refused key on loopback: TestIssuedKeyExpiresOnEveryRoute
  goes red (the expired key let in as no key).
- budget not counting CallerIssuerID: TestIssuedKeysSpendTheirIssuersLimit
  goes red (5 calls reached the upstream).

Not tried: a Responses WebSocket open across the expiry. The GUI shows
no expiry or issuer yet (issued keys look like plain keys until pruned).
A held issuer's /v1/magpie/usage shows its own rows, not its keys'. The
refused-key 401 doesn't count toward tooManyAuthFails. Issued keys sync
through davsync like other keys, with their expiry.
This commit is contained in:
yetone
2026-10-31 13:44:29 +08:00
parent 07a3312c53
commit 2eac916170
24 changed files with 1599 additions and 51 deletions
+83
View File
@@ -615,6 +615,89 @@ when nothing else makes videos. Covered by `TestMiniMaxKeysMakeH3Videos`,
`TestMiniMaxComesAfterOtherVideomakers` and
`TestMiniMaxVideoMovesPastATokenPlanKey`.
## Short-lived gateway keys
A gateway key may expire (`access.Key.Expires`), and one issued under another
key keeps that key's id (`Key.Issuer`). They are for an orchestrator that
gives each sandboxed agent a key of its own that stops working by itself
(xazaj on X, moving off an enterprise LLM gateway). `access.IssueKey` in
[`issue.go`](../../internal/access/issue.go) makes one, living 1 minute to
30 days (`MinTTL`, `MaxTTL`); `--tokens`/`--cost` cap it over its whole life,
as one `hours` limit as long as its life from the moment it is issued.
Where it is issued:
- `POST /v1/magpie/keys` with `{"ttl": "1h" | 3600, "name", "models",
"accounts", "tokens", "cost", "readOnly"}` answers 201 with the key's
`id`, `name`, `key` (the secret, told once, `Cache-Control: no-store`),
`expires` and what it is held to. `GET /v1/magpie/keys` lists the keys
the caller issued, masked; `DELETE /v1/magpie/keys/{id}` revokes one.
See [`issue_keys.go`](../../internal/gateway/issue_keys.go).
- `magpie gateway-key issue --ttl 1h [--name n] [--models a,b] [--accounts
a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] [--json]`
prints the secret alone; `gateway-key issuer <id> on|off` lets a key
issue; `gateway-key list` shows `until <time>`, `expired`, `issued by
<id>` and `issues keys`.
Who may call the endpoint (`keyIssuer`): a key the user let issue
(`Key.Issues`, `issuer-key` in `access.Update`), from wherever that key is
let in, so an orchestrator in a container or on another computer can; or a
request with no key that `profileRefused` passes: loopback, no proxy's
forwarding header, no browser's marks (`Origin`, `Sec-Fetch-*`, a
`Mozilla/` agent) and a loopback `Host`, so neither a page nor a rebound
name can. That request may already use every model with no key and could
run `magpie gateway-key` itself, so it gains nothing. A key not let issue,
a read-only key (`readOnlyGuard` refuses the route), an issued key and an
expiring key never may; the sharing key may only if the user lets it.
An issued key never outlives or exceeds its issuer. `IssueKey` clamps its
expiry to the issuer's and refuses a model or account the issuer may not
use. Then at every authentication (`access.Check`, which `Authenticate`,
`access.On` and so every route reach) `identityOf` folds it into its issuer
as the issuer is now: its models are those both allow (`foldModels`; none
in common is a refusal), its accounts are held to the issuer's
(`foldAccounts`), it is read-only if either is, told quotas only if both
are, and it expires when the first of them does. An issuer removed, turned
off or expired refuses it. What it spends counts against the issuer's
limits too: its usage rows carry `callerIssuerId` (`usage.Record.
CallerIssuerID`), `budget.read` and `budget.Append` count a row for both
keys, and `budget.Reserve` reserves on both (`Identity.Issuer`). `GET
/v1/magpie/limit` answers its `expires` and `issuerLimits`.
An expired key, or one its issuer no longer lets in, is answered 401 with
why (`access.Refused`, "the gateway key "sandbox-1" expired at …: ask for a
new one") on every route, from loopback too (`identifyCaller`): a sandbox on
this computer whose restricted key ran out would otherwise be let on as a
request with no key, which may use everything. Whether a connection already open
when the key expires (a Responses WebSocket) is refused at its next turn is
untested. An expired key is kept an hour for
that message, then `access.Prune` removes it (every 10 minutes while the
gateway serves, and on each issue), with the keys of an issuer that is
gone. A turned-off key on loopback is unchanged: it reads as no key.
`TestIssuedKeyExpiresOnEveryRoute`, `TestKeysEndpointWhoMayIssue` and
`TestIssuedKeysSpendTheirIssuersLimit` in
[`issue_keys_test.go`](../../internal/gateway/issue_keys_test.go), and
`TestIssuedKeyBoundedByIssuer` in
[`issue_test.go`](../../internal/access/issue_test.go).
### The stats and management API
Every route under `/v1/magpie/` answers a program on this computer, and
another computer only with an enabled gateway key while magpie is shared
(`sharedWith`). A key held to a budget, models or accounts (`heldKey`) is
told its own calls and limit alone:
| Route | What it answers |
| --- | --- |
| `GET /v1/magpie/usage?period=today\|7d\|30d\|all` | the usage summary: totals, by model, agent, provider, account and gateway key |
| `GET /v1/magpie/usage/requests?period=&offset=&limit=` | the request log, filtered by `day`, `model`, `agent`, `provider`, `account`, `callerKey` (a gateway key's id, an issued one's too), `failed=1`, `retried=1`, `q`, `computer`, `via` |
| `GET /v1/magpie/quotas[?kept=1]` | each subscription's windows; `kept=1` without asking a vendor |
| `GET /v1/magpie/quotas/history?days=&provider=&user=` | what was left of each window over time (45 days at most) |
| `GET /v1/magpie/limit` | the key's own limits, its `expires`, and `issuerLimits` |
| `GET /v1/magpie/concurrency` | requests in flight per account |
| `POST`/`GET /v1/magpie/keys`, `DELETE /v1/magpie/keys/{id}` | short-lived keys, above |
## Turning provider search off
[Settings](../../internal/settings/settings.go)' `searcher: "off"` disables magpie's provider-assisted search,
+39 -28
View File
@@ -140,6 +140,15 @@ type Key struct {
// readOnlyRoutes and refuses it every other, every model, MCP and
// write route among them. Off, the key may do what its other limits let it.
ReadOnly bool `json:"readOnly,omitempty"`
// Expires is when the key stops working (an issued key, IssueKey);
// zero for one that doesn't. Prune removes it a while after.
Expires time.Time `json:"expires,omitzero"`
// Issuer is the id of the key it was issued under, which bounds it
// (issue.go); "" for one the user made or issued themselves.
Issuer string `json:"issuer,omitempty"`
// Issues lets the key issue short-lived keys under itself
// (POST /v1/magpie/keys); an issued key never can.
Issues bool `json:"issues,omitempty"`
}
// Identity is the gateway key a request came with, its budget, the
@@ -152,6 +161,14 @@ type Identity struct {
Accounts []string
Quotas bool
ReadOnly bool
// Expires is when the key stops working, its issuer's expiry if
// sooner; zero for never.
Expires time.Time
// Issuer is the key it was issued under: its limits hold this key's
// requests too, and count what this key spends.
Issuer *Identity
// Issues: the key may issue keys under itself.
Issues bool
// Default: the key is the sharing key magpie made itself (Default),
// the one it writes into this computer's own agents that reach the
// gateway from beyond loopback, never one the user made for someone
@@ -316,6 +333,9 @@ type Change struct {
// ReadOnly is what "access-key" sets, and "add-key" gives the new key:
// it may read stats and use no model (Key.ReadOnly).
ReadOnly bool `json:"readOnly,omitempty"`
// Issues is what "issuer-key" sets: the key may issue short-lived
// keys under itself (Key.Issues).
Issues bool `json:"issues,omitempty"`
// Secret is the value "add-key" gives the new key, one its clients
// already send (love1sbug on X: keys handed out from another gateway);
// "" for one magpie makes.
@@ -457,6 +477,12 @@ func Update(action string, in Change) (string, error) {
keys[i].Accounts = as
case "quotas-key":
keys[i].Quotas = in.Quotas
case "issuer-key":
// may issue short-lived keys under itself (POST /v1/magpie/keys)
if in.Issues && (keys[i].Issuer != "" || !keys[i].Expires.IsZero()) {
return "", errors.New("An issued key can't issue keys of its own: let a key of yours issue them")
}
keys[i].Issues = in.Issues
case "access-key":
// the sharing key is the one magpie gives its own agents (a
// WSL distro's under NAT, LANSecret): read-only, they could
@@ -488,7 +514,7 @@ func Update(action string, in Change) (string, error) {
default:
return "", fmt.Errorf("unknown key action %q", action)
}
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "quotas-key" && action != "access-key" && action != "move-key" {
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "quotas-key" && action != "access-key" && action != "issuer-key" && action != "move-key" {
mirror = &keys[i]
}
}
@@ -522,33 +548,12 @@ func setLegacyMirror(s *settings.Settings, k Key) error {
return nil
}
// Authenticate reloads the store so revocation takes effect in running gateways.
// Authenticate reloads the store so revocation takes effect in running
// gateways. An expired key, or one whose issuer no longer lets it in, is
// refused as one turned off is; Check says why.
func Authenticate(secret string) (Identity, bool) {
mu.Lock()
defer mu.Unlock()
keys, err := load()
if err != nil || secret == "" {
return Identity{}, false
}
for _, k := range keys {
if subtle.ConstantTimeCompare([]byte(secret), []byte(k.Secret)) == 1 {
if k.Off {
return Identity{}, false
}
// the default key as Default tells it: marked LAN, or the id
// the settings name (settings read only for an unmarked key)
def := k.LAN || (settings.Load().LANKeyID == k.ID && k.ID != "")
return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Accounts: k.Accounts, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Default: def}, true
}
}
s := settings.Load()
// A read-only config directory may prevent the first store write. Never
// fall back after either durable marker exists, or to a revoked mirror.
if s.LAN && s.LANKeyID == "" && s.LANKey != "" && !strings.HasPrefix(s.LANKey, revokedLANPrefix) && !slices.ContainsFunc(keys, func(k Key) bool { return k.LAN }) && subtle.ConstantTimeCompare([]byte(secret), []byte(s.LANKey)) == 1 {
k := legacyLANKey(s.LANKey)
return Identity{KeyID: k.ID, KeyName: k.Name, Default: true}, true
}
return Identity{}, false
who, err := Check(secret)
return who, err == nil
}
// On: the key with this id is one Authenticate takes, in the store and not
@@ -563,7 +568,13 @@ func On(id string) bool {
}
for _, k := range keys {
if k.ID == id {
return !k.Off && k.Secret != ""
// an issued key is on while it hasn't expired and its issuer
// lets it in, as Check takes it
if k.Off || k.Secret == "" || k.expired(Now()) {
return false
}
_, err := identityOf(k, keys, Now())
return err == nil
}
}
s := settings.Load()
+374
View File
@@ -0,0 +1,374 @@
package access
import (
"crypto/subtle"
"errors"
"fmt"
"math"
"slices"
"strings"
"time"
"unicode/utf8"
"github.com/yetone/magpie/internal/settings"
)
// Short-lived keys (xazaj on X, moving off an enterprise LLM gateway: an
// orchestrator gives each sandboxed agent a key of its own that stops
// working by itself). A key may expire (Key.Expires), and an issued one
// may be issued under another key (Key.Issuer), which bounds it: it is
// refused once its issuer is removed, turned off or expired, it uses only
// what its issuer may use (foldIssuer, at every authentication, so a
// change to the issuer reaches its keys at once), and what it spends
// counts against its issuer's limits too (budget, Identity.Issuer).
// MinTTL and MaxTTL bound how long an issued key lives.
const (
MinTTL = time.Minute
MaxTTL = 30 * 24 * time.Hour
)
// expiredKept is how long an expired key stays in the store after it
// expires, so a client still sending it is told it expired rather than
// that magpie doesn't know it; Prune removes it after that.
const expiredKept = time.Hour
// Refused is why Check turned away a key it knows: expired, or bounded by
// an issuer that no longer lets it in. The gateway says it with a 401 on
// every route, from this computer too.
type Refused struct{ Why string }
func (r *Refused) Error() string { return r.Why }
// errUnknown: the secret is no enabled key, or the store can't be read.
var errUnknown = errors.New("not an enabled gateway key")
// expired: k has an expiry and it has come.
func (k Key) expired(now time.Time) bool { return !k.Expires.IsZero() && !now.Before(k.Expires) }
// Issue is what IssueKey makes.
type Issue struct {
Name string
TTL time.Duration
// Models and Accounts hold the key as Key's do; with an issuer, each
// must be one the issuer may use, and none takes the issuer's.
Models []string
Accounts []string
// Tokens and Cost cap what the key may spend over its whole life.
Tokens int64
Cost float64
ReadOnly bool
// Issuer is the id of the key it is issued under; "" for one the
// user issues themselves (the command line, or loopback with no key).
Issuer string
}
// Issued is a key IssueKey made, its secret told once.
type Issued struct {
ID string `json:"id"`
Name string `json:"name"`
Key string `json:"key"`
Expires time.Time `json:"expires"`
Issuer string `json:"issuer,omitempty"`
Models []string `json:"models,omitempty"`
Accounts []string `json:"accounts,omitempty"`
Limit *Limit `json:"limit,omitempty"`
ReadOnly bool `json:"readOnly,omitempty"`
}
// IssueKey makes a short-lived key. It never outlives its issuer, nor
// is let use a model or account its issuer may not.
func IssueKey(in Issue) (Issued, error) {
mu.Lock()
defer mu.Unlock()
keys, err := load()
if err != nil {
return Issued{}, err
}
now := Now().Round(0)
keys, _ = prune(keys, now)
name := strings.TrimSpace(in.Name)
if name == "" {
name = "Issued " + now.Format("2006-01-02 15:04")
}
if utf8.RuneCountInString(name) > 120 {
return Issued{}, errors.New("Use a name between 1 and 120 characters")
}
if in.TTL < MinTTL || in.TTL > MaxTTL {
return Issued{}, fmt.Errorf("An issued key lives from %s to %d days: give a ttl such as 1h", MinTTL, int(MaxTTL.Hours()/24))
}
expires := now.Add(in.TTL)
models, err := CleanModels(in.Models)
if err != nil {
return Issued{}, err
}
var accounts []string
if len(in.Accounts) > 0 {
if accounts, err = CleanAccounts(in.Accounts); err != nil {
return Issued{}, err
}
}
readOnly := in.ReadOnly
if in.Issuer != "" {
i := slices.IndexFunc(keys, func(k Key) bool { return k.ID == in.Issuer })
if i < 0 || keys[i].Off || keys[i].Secret == "" || keys[i].expired(now) {
return Issued{}, errors.New("The key issuing is no longer an enabled gateway key")
}
p := keys[i]
if !p.Issues || p.Issuer != "" {
return Issued{}, errors.New("This gateway key can't issue keys: turn it on with magpie gateway-key issuer <id> on")
}
if !p.Expires.IsZero() && expires.After(p.Expires) {
expires = p.Expires // never outlives its issuer
}
held := HeldModels(p.Models, p.Accounts)
for _, m := range models {
if !covered(held, m) {
return Issued{}, fmt.Errorf("The key issuing may not use %s, so the key it issues can't either", m)
}
}
for _, a := range accounts {
if !(Identity{Accounts: p.Accounts}).allowsEntry(a) {
return Issued{}, fmt.Errorf("The key issuing may not use the account %s, so the key it issues can't either", a)
}
}
readOnly = readOnly || p.ReadOnly
}
if in.Tokens < 0 || in.Cost < 0 || math.IsNaN(in.Cost) || math.IsInf(in.Cost, 0) {
return Issued{}, errors.New("A limit can't be negative")
}
var lim *Limit
if in.Tokens > 0 || in.Cost > 0 {
// one cycle as long as the key's life, from now: a cap on all it spends
hours := int(math.Ceil(expires.Sub(now).Hours()))
if lim, err = (&Limit{Period: "hours", Hours: max(hours, 1), Tokens: in.Tokens, Cost: in.Cost}).Valid(); err != nil {
return Issued{}, err
}
lim.Since = now
}
id, err := random(12)
if err != nil {
return Issued{}, err
}
token, err := random(24)
if err != nil {
return Issued{}, err
}
k := Key{ID: id, Name: name, Secret: Prefix + token, Limit: lim, Models: models, Accounts: accounts,
ReadOnly: readOnly, Expires: expires, Issuer: in.Issuer}
keys = append(keys, k)
if err := save(keys); err != nil {
return Issued{}, err
}
return Issued{ID: k.ID, Name: k.Name, Key: k.Secret, Expires: k.Expires, Issuer: k.Issuer, Models: models, Accounts: accounts, Limit: lim, ReadOnly: readOnly}, nil
}
// RevokeIssued removes the issued key id. by is the key asking: it may
// remove only a key issued under it; "" is the user, who may remove any
// issued key (a key of their own they remove with remove-key).
func RevokeIssued(id, by string) error {
mu.Lock()
defer mu.Unlock()
keys, err := load()
if err != nil {
return err
}
i := slices.IndexFunc(keys, func(k Key) bool { return k.ID == id })
if i < 0 || keys[i].Expires.IsZero() || (by != "" && keys[i].Issuer != by) {
return errors.New("Key not found")
}
return save(slices.Delete(keys, i, i+1))
}
// IssuedBy lists the keys issued under the key by ("" for those the user
// issued themselves), without their secrets.
func IssuedBy(by string) ([]Key, error) {
keys, err := List()
if err != nil {
return nil, err
}
var out []Key
for _, k := range keys {
if !k.Expires.IsZero() && k.Issuer == by {
out = append(out, k)
}
}
return out, nil
}
// Prune removes the keys that expired over expiredKept ago and those
// issued under a key no longer in the store, and says how many.
func Prune() (int, error) {
mu.Lock()
defer mu.Unlock()
keys, err := load()
if err != nil {
return 0, err
}
kept, n := prune(keys, Now())
if n == 0 {
return 0, nil
}
return n, save(kept)
}
func prune(keys []Key, now time.Time) ([]Key, int) {
ids := map[string]bool{}
for _, k := range keys {
ids[k.ID] = true
}
kept := slices.DeleteFunc(slices.Clone(keys), func(k Key) bool {
return k.expired(now.Add(-expiredKept)) || (k.Issuer != "" && !ids[k.Issuer])
})
return kept, len(keys) - len(kept)
}
// Check is Authenticate with why a key it knows is turned away: a
// *Refused for one expired or whose issuer no longer lets it in.
func Check(secret string) (Identity, error) {
mu.Lock()
defer mu.Unlock()
keys, err := load()
if err != nil || secret == "" {
return Identity{}, errUnknown
}
i := slices.IndexFunc(keys, func(k Key) bool { return subtle.ConstantTimeCompare([]byte(secret), []byte(k.Secret)) == 1 })
if i < 0 {
s := settings.Load()
// A read-only config directory may prevent the first store write. Never
// fall back after either durable marker exists, or to a revoked mirror.
if s.LAN && s.LANKeyID == "" && s.LANKey != "" && !strings.HasPrefix(s.LANKey, revokedLANPrefix) && !slices.ContainsFunc(keys, func(k Key) bool { return k.LAN }) && subtle.ConstantTimeCompare([]byte(secret), []byte(s.LANKey)) == 1 {
k := legacyLANKey(s.LANKey)
return Identity{KeyID: k.ID, KeyName: k.Name, Default: true}, nil
}
return Identity{}, errUnknown
}
k := keys[i]
if k.Off {
return Identity{}, errUnknown
}
now := Now()
if k.expired(now) {
return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q expired at %s: ask for a new one", k.Name, k.Expires.UTC().Format(time.RFC3339))}
}
return identityOf(k, keys, now)
}
// identityOf is who k is, folded into its issuer when it has one.
func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Accounts: k.Accounts, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Expires: k.Expires, Issues: k.Issues && k.Issuer == ""}
// the default key as Default tells it: marked LAN, or the id the
// settings name (settings read only for an unmarked key)
who.Default = k.LAN || (k.ID != "" && settings.Load().LANKeyID == k.ID)
if k.Issuer == "" {
return who, nil
}
j := slices.IndexFunc(keys, func(p Key) bool { return p.ID == k.Issuer })
if j < 0 || keys[j].Off || keys[j].Secret == "" || keys[j].expired(now) {
return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q was issued under a key that is no longer enabled, so it no longer works", k.Name)}
}
p := keys[j]
pModels := HeldModels(p.Models, p.Accounts)
if len(pModels) > 0 {
if who.Models = foldModels(who.Models, pModels); len(who.Models) == 0 {
return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q may use none of its models now: the key it was issued under no longer lets it", k.Name)}
}
}
who.Accounts = foldAccounts(who.Accounts, p.Accounts)
who.ReadOnly = who.ReadOnly || p.ReadOnly
who.Quotas = who.Quotas && p.Quotas
if !p.Expires.IsZero() && (who.Expires.IsZero() || p.Expires.Before(who.Expires)) {
who.Expires = p.Expires
}
who.Issuer = &Identity{KeyID: p.ID, KeyName: p.Name, Limit: p.Limit, More: p.More}
return who, nil
}
// covered: every model the pattern m names is one of patterns' (none:
// every model). A '*' in m is taken as written: a pattern that matches
// it so matches whatever it stands for, as a pattern's '*' takes any run.
func covered(patterns []string, m string) bool {
return ModelAllowed(patterns, m)
}
// foldModels is what both lists allow, as patterns: a child's pattern the
// issuer's cover, and an issuer's pattern a child's cover. Empty when they
// share none.
func foldModels(child, issuer []string) []string {
if len(child) == 0 {
return issuer
}
var out []string
add := func(m string) {
if !slices.ContainsFunc(out, func(o string) bool { return strings.EqualFold(o, m) }) {
out = append(out, m)
}
}
for _, c := range child {
if covered(issuer, c) {
add(c)
}
}
for _, p := range issuer {
if covered(child, p) {
add(p)
}
}
return out
}
// foldAccounts holds a child to the issuer's accounts too: of each
// provider the issuer names accounts of, the child's own of them that the
// issuer has, else the issuer's; the child's of other providers as given.
func foldAccounts(child, issuer []string) []string {
if len(issuer) == 0 {
return child
}
byProvider := func(as []string) map[string][]string {
m := map[string][]string{}
for _, a := range as {
if p, _, ok := strings.Cut(strings.ToLower(strings.TrimSpace(a)), "/"); ok {
m[p] = append(m[p], a)
}
}
return m
}
cs, ps := byProvider(child), byProvider(issuer)
var out []string
for _, a := range child {
p, _, _ := strings.Cut(strings.ToLower(strings.TrimSpace(a)), "/")
if _, named := ps[p]; !named || slices.ContainsFunc(ps[p], func(x string) bool { return strings.EqualFold(x, a) }) {
out = append(out, a)
}
}
for _, a := range issuer {
p, _, _ := strings.Cut(strings.ToLower(strings.TrimSpace(a)), "/")
mine := slices.ContainsFunc(cs[p], func(x string) bool {
return slices.ContainsFunc(ps[p], func(y string) bool { return strings.EqualFold(x, y) })
})
if !mine {
out = append(out, a)
}
}
return out
}
// allowsEntry: the account entry "<provider>/<ref>" is one who may use.
func (who Identity) allowsEntry(a string) bool {
p, ref, _ := strings.Cut(a, "/")
return who.AllowsAccount(p, ref)
}
// IssuerID is the id of the key who was issued under, "" for none.
func (who Identity) IssuerID() string {
if who.Issuer == nil {
return ""
}
return who.Issuer.KeyID
}
// Limited: a request of who's is held to a limit, its own key's or the
// key it was issued under's.
func (who Identity) Limited() bool {
return who.KeyID != "" && (len(who.Limits()) > 0 || (who.Issuer != nil && len(who.Issuer.Limits()) > 0))
}
+272
View File
@@ -0,0 +1,272 @@
package access
import (
"errors"
"slices"
"strings"
"testing"
"time"
)
// clockAt holds Now at t for the test; the returned func moves it.
func clockAt(t *testing.T, at time.Time) func(time.Duration) {
t.Helper()
old := Now
t.Cleanup(func() { Now = old })
Now = func() time.Time { return at }
return func(d time.Duration) { at = at.Add(d) }
}
func addKey(t *testing.T, name string) (id, secret string) {
t.Helper()
secret, err := Update("add-key", Change{Name: name})
if err != nil {
t.Fatal(err)
}
keys, err := List()
if err != nil {
t.Fatal(err)
}
return keys[len(keys)-1].ID, secret
}
// xazaj on X: an orchestrator gives each sandboxed agent a key that stops
// working by itself. Before its expiry it is let in; at it, every
// authentication refuses it with why, and an hour later it is gone.
func TestIssuedKeyExpires(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
advance := clockAt(t, time.Date(2026, 10, 31, 9, 0, 0, 0, time.UTC))
k, err := IssueKey(Issue{Name: "sandbox-1", TTL: time.Hour, Models: []string{"openai/gpt-5"}})
if err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(k.Key, Prefix) || !k.Expires.Equal(Now().Add(time.Hour)) {
t.Fatal(k)
}
who, ok := Authenticate(k.Key)
if !ok || who.KeyID != k.ID || !who.Expires.Equal(k.Expires) || !slices.Equal(who.Models, []string{"openai/gpt-5"}) {
t.Fatal(who, ok)
}
if !On(k.ID) {
t.Fatal("an unexpired key is not on")
}
advance(time.Hour)
if _, ok := Authenticate(k.Key); ok {
t.Fatal("an expired key was let in")
}
_, err = Check(k.Key)
var refused *Refused
if !errors.As(err, &refused) || !strings.Contains(refused.Why, "expired at 2026-10-31T10:00:00Z") {
t.Fatal(err)
}
if On(k.ID) {
t.Fatal("an expired key is on")
}
// kept an hour for the message, then removed
if n, err := Prune(); n != 0 || err != nil {
t.Fatal(n, err)
}
advance(expiredKept + time.Second)
if n, err := Prune(); n != 1 || err != nil {
t.Fatal(n, err)
}
if _, err := Check(k.Key); !errors.Is(err, errUnknown) {
t.Fatal(err)
}
}
func TestIssueKeyRefusesBadTTL(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
for _, ttl := range []time.Duration{0, -time.Hour, time.Second, MaxTTL + time.Hour} {
if _, err := IssueKey(Issue{TTL: ttl}); err == nil {
t.Error("issued with ttl", ttl)
}
}
if _, err := IssueKey(Issue{TTL: time.Hour, Tokens: -1}); err == nil {
t.Error("issued with a negative limit")
}
}
// Never let an issued key outlive or exceed its issuer.
func TestIssuedKeyBoundedByIssuer(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
advance := clockAt(t, time.Date(2026, 10, 31, 9, 0, 0, 0, time.UTC))
pid, psecret := addKey(t, "Orchestrator")
if _, err := IssueKey(Issue{TTL: time.Hour, Issuer: pid}); err == nil {
t.Fatal("a key not let issue issued one")
}
if _, err := Update("models-key", Change{Key: pid, Models: []string{"openai/*"}}); err != nil {
t.Fatal(err)
}
if _, err := Update("issuer-key", Change{Key: pid, Issues: true}); err != nil {
t.Fatal(err)
}
if who, ok := Authenticate(psecret); !ok || !who.Issues {
t.Fatal(who, ok)
}
if _, err := IssueKey(Issue{TTL: time.Hour, Issuer: pid, Models: []string{"anthropic/claude-opus-4"}}); err == nil {
t.Fatal("issued a model the issuer may not use")
}
if _, err := IssueKey(Issue{TTL: time.Hour, Issuer: pid, Models: []string{"*"}}); err == nil {
t.Fatal("issued every model under a key held to openai")
}
// none named: the issuer's
all, err := IssueKey(Issue{TTL: time.Hour, Issuer: pid})
if err != nil {
t.Fatal(err)
}
if who, ok := Authenticate(all.Key); !ok || !slices.Equal(who.Models, []string{"openai/*"}) || who.IssuerID() != pid || who.Issues {
t.Fatal(who, ok)
}
one, err := IssueKey(Issue{TTL: time.Hour, Issuer: pid, Models: []string{"openai/gpt-5"}})
if err != nil {
t.Fatal(err)
}
// an issued key never issues
if _, err := Update("issuer-key", Change{Key: one.ID, Issues: true}); err == nil {
t.Fatal("an issued key was let issue")
}
// widening the child after it was issued doesn't widen what it may use
if _, err := Update("models-key", Change{Key: one.ID, Models: []string{"anthropic/*", "openai/gpt-5"}}); err != nil {
t.Fatal(err)
}
if who, ok := Authenticate(one.Key); !ok || !slices.Equal(who.Models, []string{"openai/gpt-5"}) {
t.Fatal(who, ok)
}
// narrowing the issuer reaches its keys at once
if _, err := Update("models-key", Change{Key: pid, Models: []string{"openai/gpt-5-mini"}}); err != nil {
t.Fatal(err)
}
var refused *Refused
if _, err := Check(one.Key); !errors.As(err, &refused) {
t.Fatal("a key its issuer no longer covers was let in:", err)
}
if _, err := Update("models-key", Change{Key: pid, Models: []string{"openai/*"}}); err != nil {
t.Fatal(err)
}
// read-only and turned-off issuers hold their keys too
if _, err := Update("access-key", Change{Key: pid, ReadOnly: true}); err != nil {
t.Fatal(err)
}
if who, ok := Authenticate(one.Key); !ok || !who.ReadOnly {
t.Fatal("a read-only issuer's key may use models:", who, ok)
}
if _, err := Update("access-key", Change{Key: pid, ReadOnly: false}); err != nil {
t.Fatal(err)
}
if _, err := Update("off-key", Change{Key: pid}); err != nil {
t.Fatal(err)
}
if _, err := Check(one.Key); !errors.As(err, &refused) {
t.Fatal("a turned-off issuer's key was let in:", err)
}
if _, err := IssueKey(Issue{TTL: time.Hour, Issuer: pid}); err == nil {
t.Fatal("a turned-off key issued one")
}
if _, err := Update("on-key", Change{Key: pid}); err != nil {
t.Fatal(err)
}
if _, ok := Authenticate(one.Key); !ok {
t.Fatal("not let in again")
}
// removed: its keys are refused, then pruned
if _, err := Update("remove-key", Change{Key: pid}); err != nil {
t.Fatal(err)
}
if _, err := Check(one.Key); !errors.As(err, &refused) {
t.Fatal("a removed issuer's key was let in:", err)
}
advance(time.Minute)
if n, err := Prune(); n != 2 || err != nil {
t.Fatal(n, err)
}
}
// An issued key under an expiring issuer expires with it.
func TestIssuedKeyNeverOutlivesIssuer(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
clockAt(t, time.Date(2026, 10, 31, 9, 0, 0, 0, time.UTC))
pid, _ := addKey(t, "Orchestrator")
if _, err := Update("issuer-key", Change{Key: pid, Issues: true}); err != nil {
t.Fatal(err)
}
// the user's own expiring key (made from the command line or the
// store) can't be let issue
short, err := IssueKey(Issue{TTL: time.Hour})
if err != nil {
t.Fatal(err)
}
if _, err := Update("issuer-key", Change{Key: short.ID, Issues: true}); err == nil {
t.Fatal("an expiring key was let issue")
}
// clamp: an issuer that itself expires, set in the store by hand
keys, _ := load()
for i := range keys {
if keys[i].ID == pid {
keys[i].Expires = Now().Add(30 * time.Minute)
}
}
if err := save(keys); err != nil {
t.Fatal(err)
}
k, err := IssueKey(Issue{TTL: 2 * time.Hour, Issuer: pid})
if err != nil {
t.Fatal(err)
}
if !k.Expires.Equal(Now().Add(30 * time.Minute)) {
t.Fatal("outlives its issuer:", k.Expires)
}
}
// Tokens and Cost cap an issued key over its whole life, not per day.
func TestIssuedKeyLifeLimit(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
clockAt(t, time.Date(2026, 10, 31, 9, 0, 0, 0, time.UTC))
k, err := IssueKey(Issue{TTL: 90 * time.Minute, Tokens: 100000, Cost: 2})
if err != nil {
t.Fatal(err)
}
if k.Limit == nil || k.Limit.Period != "hours" || k.Limit.Hours != 2 || k.Limit.Tokens != 100000 || k.Limit.Cost != 2 || !k.Limit.Since.Equal(Now()) {
t.Fatal(k.Limit)
}
who, ok := Authenticate(k.Key)
if !ok || !who.Limited() {
t.Fatal(who, ok)
}
}
// An issuer may revoke only the keys issued under it; the user any
// issued key, and no key of their own through RevokeIssued.
func TestRevokeIssued(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
clockAt(t, time.Date(2026, 10, 31, 9, 0, 0, 0, time.UTC))
a, _ := addKey(t, "A")
b, _ := addKey(t, "B")
for _, id := range []string{a, b} {
if _, err := Update("issuer-key", Change{Key: id, Issues: true}); err != nil {
t.Fatal(err)
}
}
ka, err := IssueKey(Issue{TTL: time.Hour, Issuer: a})
if err != nil {
t.Fatal(err)
}
if err := RevokeIssued(ka.ID, b); err == nil {
t.Fatal("B revoked A's key")
}
if got, _ := IssuedBy(b); len(got) != 0 {
t.Fatal("B lists A's keys:", got)
}
if got, _ := IssuedBy(a); len(got) != 1 || got[0].ID != ka.ID || got[0].Secret != "" {
t.Fatal(got)
}
if err := RevokeIssued(b, ""); err == nil {
t.Fatal("revoked a key of the user's own")
}
if err := RevokeIssued(ka.ID, a); err != nil {
t.Fatal(err)
}
if _, ok := Authenticate(ka.Key); ok {
t.Fatal("a revoked key was let in")
}
}
+36 -7
View File
@@ -136,7 +136,8 @@ func read(keyID string, start time.Time) *sums {
s := &sums{start: start}
cost := usage.NewCoster()
usage.Visit(start, func(r usage.Record) {
if r.CallerKeyID == keyID && counts(r) && !r.Time.Before(start) {
// a key issued under keyID spends from its limits too
if (r.CallerKeyID == keyID || r.CallerIssuerID == keyID) && counts(r) && !r.Time.Before(start) {
c, ok := cost(r)
s.add(r, c, ok)
}
@@ -166,14 +167,24 @@ func Append(rec usage.Record) {
rec.Time = time.Now()
}
usage.Append(rec)
kept := state.sums[slot(rec.CallerKeyID)]
if len(kept) == 0 || !counts(rec) {
if !counts(rec) {
return
}
c, ok := usage.NewCoster()(rec)
for _, s := range kept {
if !rec.Time.Before(s.start) {
s.add(rec, c, ok)
var cost func(usage.Record) (float64, bool)
// the call counts for its key, and for the key that one was issued under
for _, id := range []string{rec.CallerKeyID, rec.CallerIssuerID} {
kept := state.sums[slot(id)]
if id == "" || len(kept) == 0 {
continue
}
if cost == nil {
cost = usage.NewCoster()
}
c, ok := cost(rec)
for _, s := range kept {
if !rec.Time.Before(s.start) {
s.add(rec, c, ok)
}
}
}
}
@@ -342,6 +353,24 @@ func (Limiter) Reserve(who access.Identity, body int64, model string, now time.T
// size in bytes (-1 unknown) and model the model it named, for a cost cap
// before the key has a price of its own this window.
func Reserve(who access.Identity, body int64, model string, now time.Time) (release func(), refused *Refusal) {
if who.Issuer == nil {
return reserve(who, body, model, now)
}
// an issued key's request is held to its own limits and to its
// issuer's, which count what every key issued under it spends
own, refused := reserve(who, body, model, now)
if refused != nil {
return nil, refused
}
up, refused := reserve(*who.Issuer, body, model, now)
if refused != nil {
own()
return nil, refused
}
return func() { own(); up() }, nil
}
func reserve(who access.Identity, body int64, model string, now time.Time) (release func(), refused *Refusal) {
ls := who.Limits()
if who.KeyID == "" || len(ls) == 0 {
return func() {}, nil
+77
View File
@@ -0,0 +1,77 @@
package cli
import (
"bytes"
"encoding/json"
"os"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/settings"
)
// magpie gateway-key issue prints a short-lived key alone, for a script
// that hands it to a sandbox; --from holds it to a key let issue keys.
func TestGatewayKeyIssueCLI(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)
}
call := func(args ...string) (string, error) {
var out bytes.Buffer
err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...))
return strings.TrimSpace(out.String()), err
}
secret, err := call("issue", "--ttl", "1h", "--name", "sandbox-1", "--models", "openai/gpt-5, openai/gpt-5-mini", "--tokens", "50000")
if err != nil || !strings.HasPrefix(secret, access.Prefix) || strings.Contains(secret, "\n") {
t.Fatal(secret, err)
}
who, ok := access.Authenticate(secret)
if !ok || who.KeyName != "sandbox-1" || len(who.Models) != 2 || who.Limit == nil || who.Limit.Tokens != 50000 || time.Until(who.Expires) > time.Hour {
t.Fatal(who, ok)
}
if got, _ := call("list"); !strings.Contains(got, "until ") {
t.Fatal("list:", got)
}
for _, bad := range [][]string{{"issue"}, {"issue", "--ttl"}, {"issue", "--ttl", "soon"}, {"issue", "--ttl", "10s"}, {"issue", "--ttl", "1h", "--tokens", "-3"},
{"issue", "--ttl", "1h", "--what"}, {"issue", "--help"}, {"issuer"}, {"issuer", "x", "maybe"}} {
if _, err := call(bad...); err == nil {
t.Error("accepted", bad)
}
}
parent, _ := call("add", "Orchestrator")
keys, _ := access.List()
var pid string
for _, k := range keys {
if k.Name == "Orchestrator" {
pid = k.ID
}
}
if _, err := call("issue", "--ttl", "1h", "--from", pid); err == nil {
t.Fatal("issued under a key not let issue")
}
if got, err := call("issuer", pid, "on"); err != nil || !strings.Contains(got, "may issue") {
t.Fatal(got, err)
}
if who, _ := access.Authenticate(parent); !who.Issues {
t.Fatal("not let issue:", who)
}
out, err := call("issue", "--ttl", "30m", "--from", pid, "--read-only", "--json")
var k access.Issued
if err != nil || json.Unmarshal([]byte(out), &k) != nil || k.Issuer != pid || !k.ReadOnly || k.Key == "" {
t.Fatal(out, err)
}
if got, _ := call("list"); !strings.Contains(got, "issued by "+pid) || !strings.Contains(got, "issues keys") {
t.Fatal("list:", got)
}
if got, err := call("issuer", pid, "off"); err != nil || !strings.Contains(got, "issues no keys") {
t.Fatal(got, err)
}
if help := helpFor([]string{"gateway-key", "--help"}); !strings.Contains(help, "gateway-key issue --ttl") || !strings.Contains(help, "gateway-key issuer <id>") {
t.Fatal("help:", help)
}
}
+138 -2
View File
@@ -2,6 +2,7 @@ package cli
import (
"cmp"
"encoding/json"
"fmt"
"io"
"os"
@@ -48,6 +49,14 @@ func gatewayKeysTo(out io.Writer, args []string) error {
access.MigrateLegacyLANKeyBestEffort()
return gatewayKeyMove(out, args[1:])
}
if action == "issue" {
access.MigrateLegacyLANKeyBestEffort()
return gatewayKeyIssue(out, args[1:])
}
if action == "issuer" {
access.MigrateLegacyLANKeyBestEffort()
return gatewayKeyIssuer(out, args[1:])
}
// add <name> --read-only: a key that reads stats and uses no model
// (Steven on Discord: a desk display)
readOnly := false
@@ -76,7 +85,7 @@ func gatewayKeysTo(out io.Writer, args []string) error {
args = args[:2]
}
if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) {
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] [--read-only] | rotate <id> | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off] | access <id> [read-only | full] | move <id> <place>")
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] [--read-only] | rotate <id> | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off] | access <id> [read-only | full] | move <id> <place> | issue --ttl <duration> [--name <name>] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] | issuer <id> [on | off]")
}
switch action {
case "list", "add", "rotate", "remove":
@@ -96,8 +105,18 @@ func gatewayKeysTo(out io.Writer, args []string) error {
names := provider.AccountNames()
for _, k := range keys {
state := "enabled"
if k.Off {
switch {
case k.Off:
state = "disabled"
case !k.Expires.IsZero() && !now.Before(k.Expires):
state = "expired"
case !k.Expires.IsZero():
state = "until " + k.Expires.Local().Format("01-02 15:04")
}
if k.Issuer != "" {
state += " (issued by " + k.Issuer + ")"
} else if k.Issues {
state += ", issues keys"
}
// a key that names accounts and no model may use only its
// accounts' providers' models (access.HeldModels)
@@ -588,3 +607,120 @@ func gatewayKeyMove(out io.Writer, args []string) error {
_, err = fmt.Fprintf(out, "Gateway key moved to place %d\n", n+1)
return err
}
// gatewayKeyIssue makes a short-lived key (xazaj on X: one per sandboxed
// agent, that stops working by itself), and prints its secret alone so a
// script can take it:
//
// magpie gateway-key issue --ttl 1h [--name n] [--models a,b] [--accounts a,b]
// [--tokens N] [--cost USD] [--read-only] [--from <id>]
//
// --from issues it under a key that may issue keys (issuer <id> on), held
// to that key as POST /v1/magpie/keys with it would be.
func gatewayKeyIssue(out io.Writer, args []string) error {
usage := fmt.Errorf("usage: magpie gateway-key issue --ttl <duration, e.g. 1h> [--name <name>] [--models <provider>/<model>,...] [--accounts <provider>/<account>,...] [--tokens N] [--cost USD] [--read-only] [--from <id>] [--json]")
var in access.Issue
asJSON := false
list := func(v string) []string {
var out []string
for _, f := range strings.Split(v, ",") {
if f = strings.TrimSpace(f); f != "" {
out = append(out, f)
}
}
return out
}
for i := 0; i < len(args); i++ {
flag := args[i]
switch flag {
case "--read-only":
in.ReadOnly = true
continue
case "--json":
asJSON = true
continue
case "--ttl", "--name", "--models", "--accounts", "--tokens", "--cost", "--from":
default:
return usage
}
if i+1 >= len(args) || strings.HasPrefix(args[i+1], "--") {
return usage
}
i++
v := args[i]
var err error
switch flag {
case "--ttl":
if in.TTL, err = time.ParseDuration(v); err != nil {
return fmt.Errorf("--ttl is a duration such as 30m, 1h or 24h")
}
case "--name":
in.Name = v
case "--models":
in.Models = list(v)
case "--accounts":
in.Accounts = list(v)
case "--tokens":
if in.Tokens, err = strconv.ParseInt(v, 10, 64); err != nil || in.Tokens <= 0 {
return fmt.Errorf("--tokens is a whole number above 0")
}
case "--cost":
if in.Cost, err = strconv.ParseFloat(v, 64); err != nil || in.Cost <= 0 {
return fmt.Errorf("--cost is an amount in USD above 0")
}
case "--from":
in.Issuer = v
}
}
if in.TTL == 0 {
return usage
}
k, err := access.IssueKey(in)
if err != nil {
return err
}
if asJSON {
b, err := json.MarshalIndent(k, "", " ")
if err != nil {
return err
}
_, err = fmt.Fprintln(out, string(b))
return err
}
_, err = fmt.Fprintln(out, k.Key)
return err
}
// gatewayKeyIssuer shows or sets whether a key may issue short-lived keys
// under itself (POST /v1/magpie/keys with it), each held to it:
//
// magpie gateway-key issuer <id> [on | off]
func gatewayKeyIssuer(out io.Writer, args []string) error {
usage := fmt.Errorf("usage: magpie gateway-key issuer <id> [on | off]")
if len(args) == 0 || len(args) > 2 {
return usage
}
id := args[0]
if len(args) == 2 {
if args[1] != "on" && args[1] != "off" {
return usage
}
if _, err := access.Update("issuer-key", access.Change{Key: id, Issues: args[1] == "on"}); 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")
}
if keys[i].Issues {
_, err = fmt.Fprintf(out, "%s: may issue short-lived keys, each held to its own models, accounts, limits and life\n", keys[i].Name)
} else {
_, err = fmt.Fprintf(out, "%s: issues no keys\n", keys[i].Name)
}
return err
}
+3
View File
@@ -127,6 +127,9 @@ const usage = `magpie — one place to pick every agent's model
magpie gateway-key quotas <id> [on|off] whether a key held to a budget, models or accounts is told the quotas of what it may use
magpie gateway-key access <id> [read-only|full] read-only: the key reads quotas and usage (GET /, /v1/magpie/quotas, /v1/magpie/usage) and uses no model, MCP server or write
magpie gateway-key move <id> <place> put a key at a place in the list (from 1), the order list and the app show them in
magpie gateway-key issue --ttl 1h [--name n] [--models a,b] [--accounts a,b] [--tokens N] [--cost USD] [--read-only] [--from <id>] [--json]
a short-lived key (1m to 30 days) that stops working by itself; --from holds it to a key that issues keys; prints the key
magpie gateway-key issuer <id> [on|off] let a key issue short-lived keys under itself (POST /v1/magpie/keys with it), each held to its models, accounts, limits and life
magpie mcp image the image and video generation MCP server an agent is given from the library (stdio)
magpie tools [<name>] the tools magpie's MCP servers give agents (images, vision, web search, plugins'), with their parameters
magpie tool <name> [--<param> <value>…] [<words>] [-o <file|folder>] [--json] call one through the running magpie; an image or video it makes is saved
+5
View File
@@ -807,6 +807,11 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc("GET /v1/magpie/trace", s.gatewayTrace)
mux.HandleFunc("GET /v1/magpie/concurrency", s.concurrency)
mux.HandleFunc("GET /v1/magpie/limit", s.keyLimit)
// short-lived keys, issued by a key let issue them or from loopback
// (issue_keys.go)
mux.HandleFunc("POST "+KeysPath, s.issueKey)
mux.HandleFunc("GET "+KeysPath, s.issuedKeys)
mux.HandleFunc("DELETE "+KeysPath+"/{id}", s.revokeIssuedKey)
mux.HandleFunc("GET "+KeyPagePath, s.keyPage)
mux.HandleFunc("GET "+keyPageData, s.keyInfo)
// the Claude Code processes the Claude subscription runs, for magpie
+175
View File
@@ -0,0 +1,175 @@
package gateway
import (
"context"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
// KeysPath issues short-lived gateway keys (xazaj on X: an orchestrator
// gives each sandboxed agent a key of its own that stops working by
// itself). POST issues one, GET lists those the caller issued, DELETE
// KeysPath/{id} revokes one early.
//
// Who may issue: a gateway key the user let issue keys (Key.Issues,
// magpie gateway-key issuer <id> on), from wherever it is let in, every
// key it issues bounded by it (access.IssueKey); or, with no key, a
// program on this computer over loopback that carries no browser's marks
// (profileRefused's rule), which may already use every model and could
// run magpie gateway-key itself. A page in a browser, another machine
// without such a key, a held or read-only key and an issued key never
// may.
const KeysPath = "/v1/magpie/keys"
// issuedKeyBody is a POST's body.
type issuedKeyBody struct {
Name string `json:"name"`
// TTL is a Go duration ("1h", "30m") or a number of seconds.
TTL json.RawMessage `json:"ttl"`
Models []string `json:"models"`
Accounts []string `json:"accounts"`
Tokens int64 `json:"tokens"`
Cost float64 `json:"cost"`
ReadOnly bool `json:"readOnly"`
}
// keyIssuer is the id of the key r issues under ("" for the user, over
// loopback), or why it may not issue, with the status to say it with.
func keyIssuer(r *http.Request) (string, int, string) {
who := access.Caller(r.Context())
if who.KeyID != "" {
if who.Issuer != nil {
return "", http.StatusForbidden, "this gateway key was issued itself, so it can't issue keys"
}
if !who.Issues {
return "", http.StatusForbidden, "this gateway key can't issue keys: let it with magpie gateway-key issuer " + who.KeyID + " on"
}
return who.KeyID, 0, ""
}
if why := profileRefused(r, "keys", "magpie gateway-key issue"); why != "" {
return "", http.StatusForbidden, why + ", or send a gateway key that may issue keys (magpie gateway-key issuer <id> on)"
}
return "", 0, ""
}
func (s *Server) issueKey(w http.ResponseWriter, r *http.Request) {
by, status, why := keyIssuer(r)
if why != "" {
log.Printf("refused %s %s: %s", r.Method, r.URL.Path, why)
writeError(w, provider.Chat, status, why)
return
}
var in issuedKeyBody
if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&in); err != nil {
writeError(w, provider.Chat, http.StatusBadRequest, "the body is a JSON object: {\"ttl\": \"1h\", \"name\": …, \"models\": […]}")
return
}
ttl, err := parseTTL(in.TTL)
if err != nil {
writeError(w, provider.Chat, http.StatusBadRequest, err.Error())
return
}
k, err := access.IssueKey(access.Issue{Name: in.Name, TTL: ttl, Models: in.Models, Accounts: in.Accounts,
Tokens: in.Tokens, Cost: in.Cost, ReadOnly: in.ReadOnly, Issuer: by})
if err != nil {
writeError(w, provider.Chat, http.StatusBadRequest, err.Error())
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusCreated, k)
}
func (s *Server) issuedKeys(w http.ResponseWriter, r *http.Request) {
by, status, why := keyIssuer(r)
if why != "" {
writeError(w, provider.Chat, status, why)
return
}
keys, err := access.IssuedBy(by)
if err != nil {
writeError(w, provider.Chat, http.StatusInternalServerError, err.Error())
return
}
out := make([]map[string]any, 0, len(keys))
for _, k := range keys {
e := map[string]any{"id": k.ID, "name": k.Name, "key": k.Masked, "expires": k.Expires, "expired": !time.Now().Before(k.Expires)}
if len(k.Models) > 0 {
e["models"] = k.Models
}
if len(k.Accounts) > 0 {
e["accounts"] = k.Accounts
}
if k.Limit != nil {
e["limit"] = k.Limit
}
if k.ReadOnly {
e["readOnly"] = true
}
out = append(out, e)
}
writeJSON(w, http.StatusOK, map[string]any{"keys": out})
}
func (s *Server) revokeIssuedKey(w http.ResponseWriter, r *http.Request) {
by, status, why := keyIssuer(r)
if why != "" {
writeError(w, provider.Chat, status, why)
return
}
if err := access.RevokeIssued(r.PathValue("id"), by); err != nil {
writeError(w, provider.Chat, http.StatusNotFound, "no key issued here has the id "+strconv.Quote(r.PathValue("id")))
return
}
writeJSON(w, http.StatusOK, map[string]any{"revoked": r.PathValue("id")})
}
// parseTTL reads a ttl given as a duration ("1h") or seconds (3600).
func parseTTL(raw json.RawMessage) (time.Duration, error) {
bad := errors.New("ttl is how long the key lives, such as \"1h\", \"30m\" or 3600 (seconds), from 1m to 720h")
if len(raw) == 0 {
return 0, bad
}
var s string
if json.Unmarshal(raw, &s) == nil {
d, err := time.ParseDuration(strings.TrimSpace(s))
if err != nil {
return 0, bad
}
return d, nil
}
var n float64
if json.Unmarshal(raw, &n) != nil || n <= 0 || n > access.MaxTTL.Seconds() {
return 0, bad
}
return time.Duration(n * float64(time.Second)), nil
}
// keys issued are removed a while after they expire (access.Prune)
// while the gateway serves; issuing one removes them too.
func init() {
WhileServing = append(WhileServing, func(ctx context.Context) {
tick := time.NewTicker(10 * time.Minute)
defer tick.Stop()
for {
if n, err := access.Prune(); err != nil {
log.Printf("issued gateway key cleanup failed: %v", err)
} else if n > 0 {
log.Printf("removed %d expired gateway keys", n)
}
select {
case <-ctx.Done():
return
case <-tick.C:
}
}
})
}
+218
View File
@@ -0,0 +1,218 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
)
// keysCall is a request to h from from ("127.0.0.1:5000" or another
// computer's address), with secret as its key when it has one.
func keysCall(h http.Handler, method, path, from, secret, body string, hdr ...string) *httptest.ResponseRecorder {
var rd io.Reader
if body != "" {
rd = strings.NewReader(body)
}
r := httptest.NewRequest(method, path, rd)
r.RemoteAddr = from
r.Host = "127.0.0.1:3425"
if !strings.HasPrefix(from, "127.") {
r.Host = "192.168.1.2:3425"
}
if secret != "" {
r.Header.Set("Authorization", "Bearer "+secret)
}
r.Header.Set("Content-Type", "application/json")
for i := 0; i+1 < len(hdr); i += 2 {
if hdr[i] == "Host" {
r.Host = hdr[i+1]
continue
}
r.Header.Set(hdr[i], hdr[i+1])
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
func issuedFrom(t *testing.T, w *httptest.ResponseRecorder) access.Issued {
t.Helper()
var k access.Issued
if w.Code != http.StatusCreated || json.Unmarshal(w.Body.Bytes(), &k) != nil || k.Key == "" {
t.Fatalf("not issued: %d %s", w.Code, w.Body.String())
}
return k
}
const (
fromHere = "127.0.0.1:5000"
fromThere = "192.168.1.9:5000"
)
// xazaj on X: an orchestrator issues each sandboxed agent a key that stops
// working by itself. Once it has expired it is refused with a 401 that says
// so on every route, from another computer and from this one too, where a
// request with no key is let in: an agent held to a few models would
// otherwise get every one by its key expiring.
func TestIssuedKeyExpiresOnEveryRoute(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
budget.Forget()
calls := limitedUpstream(t, 0)
newCaller(t, "Laptop")
h := lanGuard(New().Handler())
k := issuedFrom(t, keysCall(h, "POST", KeysPath, fromHere, "", `{"name":"sandbox-1","ttl":"1h","models":["plan/m1"]}`))
if k.Name != "sandbox-1" || len(k.Models) != 1 || time.Until(k.Expires) > time.Hour || time.Until(k.Expires) < 59*time.Minute {
t.Fatalf("%+v", k)
}
for _, from := range []string{fromThere, fromHere} {
if w := keysCall(h, "POST", "/v1/chat/completions", from, k.Key, chatReq); w.Code != 200 {
t.Fatal("an issued key's request from", from, w.Code, w.Body.String())
}
}
if w := keysCall(h, "POST", "/v1/chat/completions", fromThere, k.Key, `{"model":"other/m2","messages":[{"role":"user","content":"hi"}]}`); w.Code == 200 {
t.Fatal("an issued key used a model it wasn't issued")
}
before := calls.Load()
old := access.Now
t.Cleanup(func() { access.Now = old })
access.Now = func() time.Time { return old().Add(61 * time.Minute) }
for _, from := range []string{fromThere, fromHere} {
for _, rq := range [][2]string{{"POST", "/v1/chat/completions"}, {"POST", "/v1/messages"}, {"POST", "/v1/responses"}, {"GET", "/v1/models"},
{"GET", "/v1/magpie/usage"}, {"GET", "/v1/magpie/quotas"}, {"GET", "/v1/magpie/limit"}, {"GET", "/"}, {"POST", KeysPath}} {
body := ""
if rq[0] == "POST" {
body = chatReq
}
w := keysCall(h, rq[0], rq[1], from, k.Key, body)
if w.Code != http.StatusUnauthorized || !strings.Contains(w.Body.String(), "expired at") {
t.Errorf("an expired key from %s: %s %s: %d %.200s", from, rq[0], rq[1], w.Code, w.Body.String())
}
}
}
if calls.Load() != before {
t.Fatal("an expired key's request reached the provider")
}
// a request from this computer with no key goes on as before
if w := keysCall(h, "POST", "/v1/chat/completions", fromHere, "", chatReq); w.Code != 200 {
t.Fatal("no key from here:", w.Code, w.Body.String())
}
}
// Who may issue: a program fromHere over loopback with no browser's marks,
// or a key let issue them, never a page, another computer without such a
// key, a key not let, or an issued key; and what a key issues is held to
// it.
func TestKeysEndpointWhoMayIssue(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
budget.Forget()
limitedUpstream(t, 0)
keys, secrets := newCaller(t, "Orchestrator")
h := lanGuard(New().Handler())
body := `{"ttl":"1h"}`
for name, w := range map[string]*httptest.ResponseRecorder{
"a page here": keysCall(h, "POST", KeysPath, fromHere, "", body, "Origin", "https://evil.example"),
"a page fromHere, no Origin": keysCall(h, "POST", KeysPath, fromHere, "", body, "Sec-Fetch-Site", "cross-site", "User-Agent", "Mozilla/5.0"),
"a rebound name": keysCall(h, "POST", KeysPath, fromHere, "", body, "Host", "evil.example"),
"another computer": keysCall(h, "POST", KeysPath, fromThere, "", body),
"a key not let": keysCall(h, "POST", KeysPath, fromThere, secrets[0], body),
"a key not let, here": keysCall(h, "POST", KeysPath, fromHere, secrets[0], body),
"a list, not let": keysCall(h, "GET", KeysPath, fromThere, secrets[0], ""),
} {
if w.Code == http.StatusCreated || w.Code == http.StatusOK || strings.Contains(w.Body.String(), access.Prefix) {
t.Errorf("%s issued: %d %.200s", name, w.Code, w.Body.String())
}
}
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"plan/m1"}}); err != nil {
t.Fatal(err)
}
if _, err := access.Update("issuer-key", access.Change{Key: keys[0].ID, Issues: true}); err != nil {
t.Fatal(err)
}
if w := keysCall(h, "POST", KeysPath, fromThere, secrets[0], `{"ttl":"1h","models":["other/m2"]}`); w.Code != http.StatusBadRequest {
t.Fatal("issued a model its issuer may not use:", w.Code, w.Body.String())
}
for _, bad := range []string{`{"ttl":"1s"}`, `{"ttl":"forever"}`, `{}`, `{"ttl":-5}`, `not json`} {
if w := keysCall(h, "POST", KeysPath, fromThere, secrets[0], bad); w.Code != http.StatusBadRequest {
t.Error("issued with", bad, w.Code, w.Body.String())
}
}
child := issuedFrom(t, keysCall(h, "POST", KeysPath, fromThere, secrets[0], `{"name":"agent-7","ttl":600,"readOnly":false}`))
if child.Issuer != keys[0].ID || len(child.Models) != 0 {
t.Fatalf("%+v", child)
}
if w := keysCall(h, "POST", "/v1/chat/completions", fromThere, child.Key, chatReq); w.Code != 200 {
t.Fatal("the issued key:", w.Code, w.Body.String())
}
if w := keysCall(h, "POST", KeysPath, fromThere, child.Key, body); w.Code != http.StatusForbidden {
t.Fatal("an issued key issued one:", w.Code, w.Body.String())
}
w := keysCall(h, "GET", KeysPath, fromThere, secrets[0], "")
if w.Code != 200 || !strings.Contains(w.Body.String(), child.ID) || strings.Contains(w.Body.String(), child.Key) {
t.Fatal("list:", w.Code, w.Body.String())
}
// the user's own list (loopback, no key) holds what they issued alone
if w := keysCall(h, "GET", KeysPath, fromHere, "", ""); w.Code != 200 || strings.Contains(w.Body.String(), child.ID) {
t.Fatal("the user's list:", w.Code, w.Body.String())
}
if w := keysCall(h, "DELETE", KeysPath+"/"+keys[0].ID, fromThere, secrets[0], ""); w.Code != http.StatusNotFound {
t.Fatal("an issuer revoked itself:", w.Code, w.Body.String())
}
if w := keysCall(h, "DELETE", KeysPath+"/"+child.ID, fromThere, secrets[0], ""); w.Code != 200 {
t.Fatal("revoke:", w.Code, w.Body.String())
}
if w := keysCall(h, "POST", "/v1/chat/completions", fromThere, child.Key, chatReq); w.Code != http.StatusUnauthorized {
t.Fatal("a revoked key:", w.Code, w.Body.String())
}
}
// What an issued key spends counts against its issuer's limit: a hundred
// sandboxes each with a key of its own can't spend more than the one key
// they were issued under may.
func TestIssuedKeysSpendTheirIssuersLimit(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
budget.Forget()
pinLimitClock(t)
calls := limitedUpstream(t, 0) // 350 tokens a call
keys, secrets := newCaller(t, "Orchestrator")
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 700})
if _, err := access.Update("issuer-key", access.Change{Key: keys[0].ID, Issues: true}); err != nil {
t.Fatal(err)
}
h := New().Handler()
a := issuedFrom(t, keysCall(h, "POST", KeysPath, fromThere, secrets[0], `{"ttl":"1h"}`))
b := issuedFrom(t, keysCall(h, "POST", KeysPath, fromThere, secrets[0], `{"ttl":"1h"}`))
for _, k := range []string{a.Key, b.Key} {
if w := keysCall(h, "POST", "/v1/chat/completions", fromThere, k, chatReq); w.Code != 200 {
t.Fatal("within the issuer's limit:", w.Code, w.Body.String())
}
}
for name, k := range map[string]string{"a": a.Key, "b": b.Key, "the issuer": secrets[0]} {
if w := keysCall(h, "POST", "/v1/chat/completions", fromThere, k, chatReq); w.Code != http.StatusTooManyRequests || !strings.Contains(w.Body.String(), "Orchestrator") {
t.Errorf("%s past the issuer's limit: %d %.200s", name, w.Code, w.Body.String())
}
}
if calls.Load() != 2 {
t.Fatal("calls past the issuer's limit reached the provider:", calls.Load())
}
w := keysCall(h, "GET", "/v1/magpie/limit", fromThere, a.Key, "")
var lim struct {
Expires time.Time
IssuerLimits []budget.Status
}
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &lim) != nil || lim.Expires.IsZero() || len(lim.IssuerLimits) != 1 || lim.IssuerLimits[0].Calls != 2 {
t.Fatal("limit:", w.Code, w.Body.String())
}
}
+16 -3
View File
@@ -37,7 +37,10 @@ func keyLimited(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
who := access.Caller(r.Context())
limits := who.Limits()
if len(limits) == 0 || r.Method != http.MethodPost || strings.HasPrefix(r.URL.Path, "/_magpie/") || strings.HasPrefix(r.URL.Path, "/mcp/") || strings.HasSuffix(r.URL.Path, "/count_tokens") {
if who.Issuer != nil {
limits = append(slices.Clone(limits), who.Issuer.Limits()...)
}
if !who.Limited() || r.Method != http.MethodPost || strings.HasPrefix(r.URL.Path, "/_magpie/") || strings.HasPrefix(r.URL.Path, "/mcp/") || strings.HasSuffix(r.URL.Path, "/count_tokens") || r.URL.Path == KeysPath {
next.ServeHTTP(w, r)
return
}
@@ -115,10 +118,20 @@ func protoOfPath(path string) provider.Protocol {
// what a magpie from before them reads.
func (s *Server) keyLimit(w http.ResponseWriter, r *http.Request) {
who := access.Caller(r.Context())
out := map[string]any{"limited": false, "key": who.KeyName}
// an issued key is held to the limits of the key it was issued under
// too, which count every key issued under it: "issuerLimits"
if who.KeyID != "" && who.Issuer != nil && len(who.Issuer.Limits()) > 0 {
out["issuerLimits"] = budget.All(access.Key{ID: who.Issuer.KeyID, Name: who.Issuer.KeyName, Limit: who.Issuer.Limit, More: who.Issuer.More}, limitClock())
}
if !who.Expires.IsZero() {
out["expires"] = who.Expires
}
if who.KeyID == "" || len(who.Limits()) == 0 {
writeJSON(w, 200, map[string]any{"limited": false, "key": who.KeyName})
writeJSON(w, 200, out)
return
}
all := budget.All(access.Key{ID: who.KeyID, Name: who.KeyName, Limit: who.Limit, More: who.More}, limitClock())
writeJSON(w, 200, map[string]any{"limited": true, "key": who.KeyName, "limit": budget.Binding(all), "limits": all})
out["limited"], out["limit"], out["limits"] = true, budget.Binding(all), all
writeJSON(w, 200, out)
}
+18 -2
View File
@@ -3,6 +3,7 @@ package gateway
import (
"context"
"crypto/subtle"
"errors"
"log"
"net"
"net/http"
@@ -525,10 +526,25 @@ func callerGuard(next http.Handler) http.Handler {
func identifyCaller(w http.ResponseWriter, r *http.Request) (*http.Request, bool) {
var who access.Identity
ok := false
var refused *access.Refused
for _, k := range callerKeys(r) {
if who, ok = access.Authenticate(k); ok {
var err error
if who, err = access.Check(k); err == nil {
ok = true
break
}
if refused == nil {
errors.As(err, &refused)
}
}
if !ok && refused != nil {
// an expired key, or one its issuer no longer lets in, is told so
// on every route, from this computer too: a sandbox's agent on
// loopback holding a key that has run out is not let on as one
// with no key, which would hand it everything its key held it from
log.Printf("refused %s %s from %s: %s", r.Method, r.URL.Path, r.RemoteAddr, refused.Why)
writeError(w, provider.Chat, http.StatusUnauthorized, refused.Why)
return r, false
}
if !ok && !local(r) {
if over, retry := tooManyAuthFails(); over {
@@ -581,7 +597,7 @@ func appendUsage(r *http.Request, rec usage.Record) {
rec.Subagent, rec.ParentAgent = subagentOf(r.Header)
}
who := access.Caller(r.Context())
rec.CallerKeyID, rec.CallerKeyName = who.KeyID, who.KeyName
rec.CallerKeyID, rec.CallerKeyName, rec.CallerIssuerID = who.KeyID, who.KeyName, who.IssuerID()
rec.Local = local(r)
if r.Context().Value(observedKey{}) != nil {
rec.Watched = true
+1
View File
@@ -28,6 +28,7 @@ var readOnlyRefused = []string{
"GET /v1/magpie/route", "GET /v1/magpie/trace",
"GET " + ClaudeRunsPath, "GET " + HeapPath, "GET " + CPUPath, "GET " + GoroutinesPath,
"POST " + RestartPath,
"POST " + KeysPath, "GET " + KeysPath, "DELETE " + KeysPath + "/{id}",
"GET /v1/magpie/omarchy", "OPTIONS /v1/magpie/omarchy",
// models, a WebSocket's upgrade and count_tokens among them
"POST /v1/chat/completions", "POST /chat/completions",
+1 -1
View File
@@ -193,7 +193,7 @@ func logSearch(ctx context.Context, rec usage.Record, query string, start time.T
rec.Agent = f.Agent
}
who := access.Caller(ctx)
rec.CallerKeyID, rec.CallerKeyName = who.KeyID, who.KeyName
rec.CallerKeyID, rec.CallerKeyName, rec.CallerIssuerID = who.KeyID, who.KeyName, who.IssuerID()
switch {
case err != nil && found == 0 && errors.Is(err, errFoundNothing):
rec.Error = "found nothing"
+1 -1
View File
@@ -107,6 +107,6 @@ func logNativeSearches(ctx context.Context, n int, at time.Time, agent, provider
for range min(n, maxNativeSearchRows) {
budget.Append(usage.Record{Time: at, Agent: cmp.Or(agent, "magpie"), Kind: "web_search", Source: usage.SourceSearch,
Provider: providerID, Host: host, Requested: model, Model: model, Status: http.StatusOK,
CallerKeyID: who.KeyID, CallerKeyName: who.KeyName})
CallerKeyID: who.KeyID, CallerKeyName: who.KeyName, CallerIssuerID: who.IssuerID()})
}
}
+1 -1
View File
@@ -27,7 +27,7 @@ const usageRefused = "magpie's usage is told to another machine only when magpie
// heldKey: the request's gateway key is held to a budget, models or
// accounts, and so sees only its own usage.
func heldKey(who access.Identity) bool {
return who.KeyID != "" && (len(who.Limits()) > 0 || len(who.Models) > 0 || len(who.Accounts) > 0)
return who.KeyID != "" && (who.Limited() || len(who.Models) > 0 || len(who.Accounts) > 0)
}
// heldRefused is what a held key is told where this magpie's own accounts
+1 -1
View File
@@ -104,7 +104,7 @@ var ErrUnlimited = errors.New("this gateway key is held to a limit, but magpie's
// so a limit set a moment ago turns the plugin on for the request that
// needs it. Fail closed.
func Limiting(who access.Identity) (Limiter, error) {
if who.KeyID == "" || len(who.Limits()) == 0 {
if !who.Limited() {
return nil, nil
}
l, f := served()
+1 -1
View File
@@ -109,7 +109,7 @@ func IngestReported(recs []Record) ([]bool, error) {
continue
}
r.Source = SourceReported
r.CallerKeyID, r.CallerKeyName = "", ""
r.CallerKeyID, r.CallerKeyName, r.CallerIssuerID = "", "", ""
b, err := json.Marshal(r)
if err != nil {
return nil, err
+4 -4
View File
@@ -179,13 +179,13 @@ type rowChunk struct {
// rowMsg is the Text of a row's Claude message id, after rowText's, and
// rowError its error's
const (
rowMsg = 34
rowMsg = 35
rowError = 9
// rowClient is the Text of the client's own name, when the user counts
// it as another agent (Row.Client, #1958)
rowClient = 33
// rowTexts is how many strings a row has: rowText's and the message id
rowTexts = 35
rowTexts = 36
)
// rowVaried are the strings that differ call by call: the error, the
@@ -251,8 +251,8 @@ func (c *rowChunk) shape(t [rowTexts]uint32) uint32 {
// reason ("Upstream stop reason", #1927) and the service tiers (#1784)
// among them: a string left out comes back empty from the cache, in the
// page and in /v1/magpie/usage/requests (TestRowTextHoldsEveryString)
func rowText(r *Row) [34]*string {
return [34]*string{&r.Agent, &r.Provider, &r.Host, &r.SessionProvider, &r.SessionAccount, &r.Model, &r.Requested, &r.Served, &r.Effort, &r.Error, &r.ErrType, &r.RequestID, &r.Endpoint, &r.Session, &r.NativeSession, &r.Kind, &r.Source, &r.Via, &r.ProviderKeyID, &r.ProviderKeyName, &r.CallerKeyID, &r.CallerKeyName, &r.Archive, &r.Operation, &r.ProviderAccount, &r.ResponseID, &r.Upstream, &r.Subagent, &r.ParentAgent, &r.Stop, &r.TierAsked, &r.TierSent, &r.TierServed, &r.Client}
func rowText(r *Row) [35]*string {
return [35]*string{&r.Agent, &r.Provider, &r.Host, &r.SessionProvider, &r.SessionAccount, &r.Model, &r.Requested, &r.Served, &r.Effort, &r.Error, &r.ErrType, &r.RequestID, &r.Endpoint, &r.Session, &r.NativeSession, &r.Kind, &r.Source, &r.Via, &r.ProviderKeyID, &r.ProviderKeyName, &r.CallerKeyID, &r.CallerKeyName, &r.Archive, &r.Operation, &r.ProviderAccount, &r.ResponseID, &r.Upstream, &r.Subagent, &r.ParentAgent, &r.Stop, &r.TierAsked, &r.TierSent, &r.TierServed, &r.Client, &r.CallerIssuerID}
}
func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
if c.dict == nil {
+3
View File
@@ -44,6 +44,9 @@ type Record struct {
ProviderAccount string `json:"providerAccount,omitempty"`
CallerKeyID string `json:"callerKeyId,omitempty"`
CallerKeyName string `json:"callerKeyName,omitempty"`
// CallerIssuerID is the key CallerKeyID was issued under (an issued,
// short-lived key: access.IssueKey), whose limits count this call too.
CallerIssuerID string `json:"callerIssuerId,omitempty"`
// SessionProvider is the provider ID recorded by the agent. SessionAccount
// identifies the session's creator, not the account used for an API request.
// Neither field establishes an upstream route from today's configuration.
+44
View File
@@ -77,6 +77,8 @@
<a href="#add">2. ほかのコンピューターで追加する</a>
<a href="#models">使えるもの</a>
<a href="#quotas">クォータと使用量</a>
<a href="#keys">短期キー</a>
<a href="#api">統計 API</a>
<a href="#trouble">うまくいかないとき</a>
</aside>
@@ -132,6 +134,48 @@ magpie provider refresh office <span class="c"># 一覧を再取得</span></pr
<p>使用量ページ、メニューバー、<code>magpie quota</code> には、共有する magpie のサブスクリプションカードがその名前付きで(<code>Codex · office</code>、id <code>office/codex</code>)、向こうが最後に読んだ内容で表示されます。ベンダーに問い合わせるのはサインインを持つコンピューターだけです。このコンピューターでカードを更新すると、向こうがもう一度読みます(最大で 30 秒に 1 回)。Codex のリセットや WorkBuddy のチェックインは、向こうのコンピューターのアプリ、TUI、CLI で行います。向こうが予算・モデル・アカウントで制限したキーにはカードは一切渡されず、ここにはそのキー自身のカードと上限だけが表示されます。</p>
<p>共有する magpie は、このコンピューターのリクエストを、送ってきたゲートウェイキーの名前と応答したアカウントで記録します。</p>
<h2 id="keys"><a class="anchor" href="#keys">短期キー</a></h2>
<p>サンドボックスでエージェントを起動するプログラムは、エージェントごとに自動で失効するゲートウェイキーを渡せます。有効期間は 1 分から 30 日で、一部のモデル、一部のアカウント、有効期間全体のトークン数やコスト、または読み取り専用に制限できます。キー本体は応答に一度だけ含まれます。</p>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-keys">コピー</button>
<pre id="ex-keys">curl -s -X POST http://127.0.0.1:3425/v1/magpie/keys \
-d '{"name":"sandbox-1","ttl":"1h","models":["office/codex/gpt-5"],"tokens":200000}'
<span class="c"># {"id":"k…","name":"sandbox-1","key":"sk-magpie-…","expires":"…","models":[…],"limit":{…}}</span>
curl -s http://127.0.0.1:3425/v1/magpie/keys <span class="c"># 発行したキー(伏せ字)</span>
curl -s -X DELETE http://127.0.0.1:3425/v1/magpie/keys/k… <span class="c"># 早めに失効させる</span></pre>
</div>
<p>このコンピューター上のプログラムはキーなしで呼べますが、ブラウザーのページは呼べません。ほかのコンピューター、コンテナー、CI は、キーの発行を許可したゲートウェイキーを付けて呼びます。そのキーが発行したキーはすべてそのキーに縛られます。使えないモデルやアカウントは使えず、そのキーより後まで有効にはならず、使った分はそのキーの上限に数えられます。オフにするか削除すると、発行したキーもすぐに使えなくなります。コマンドラインでも同じで、キーだけを出力します。</p>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-keys-cli">コピー</button>
<pre id="ex-keys-cli">magpie gateway-key issue --ttl 1h --name sandbox-1 --models office/codex/gpt-5 --tokens 200000
magpie gateway-key issuer &lt;id&gt; on <span class="c"># このキーにキーの発行を許可</span>
magpie gateway-key issue --ttl 30m --from &lt;id&gt; --read-only --json
magpie gateway-key list <span class="c"># until 10-31 14:00、expired、issued by …</span></pre>
</div>
<p>期限切れのキーは、どの API でも理由付きの <code>401</code>(“the gateway key "sandbox-1" expired at …: ask for a new one”)で断られます。このコンピューターからでも同じです。1 時間後に削除されます。</p>
<h2 id="api"><a class="anchor" href="#api">統計 API</a></h2>
<p>使用量ページの内容は JSON でも、このコンピューターに、また magpie を共有している間はゲートウェイキー付きのリクエストに提供されます。予算、モデル、アカウントで制限されたキーには、自分のリクエストと上限だけが返ります。</p>
<ul>
<li><code>/v1/magpie/usage?period=today|7d|30d|all</code>:合計と、モデル、エージェント、プロバイダー、アカウント、ゲートウェイキーごとの内訳。</li>
<li><code>/v1/magpie/usage/requests</code>:リクエストログ。<code>period</code>、<code>day</code>、<code>offset</code>、<code>limit</code> と、絞り込みの <code>model</code>、<code>agent</code>、<code>provider</code>、<code>account</code>、<code>callerKey</code>、<code>failed=1</code>、<code>retried=1</code>、<code>q</code>。</li>
<li><code>/v1/magpie/quotas</code>:各サブスクリプションのウィンドウ(<code>?kept=1</code> でベンダーに問い合わせない)。<code>/v1/magpie/quotas/history?days=</code>:残量の履歴、最大 45 日。</li>
<li><code>/v1/magpie/limit</code>:キー自身の上限、有効期限、発行元キーの上限。</li>
<li><code>/v1/magpie/concurrency</code>:アカウントごとの実行中のリクエスト。</li>
</ul>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-api">コピー</button>
<pre id="ex-api">curl -s 'http://127.0.0.1:3425/v1/magpie/usage?period=7d'
curl -s 'http://127.0.0.1:3425/v1/magpie/usage/requests?period=today&amp;callerKey=k…&amp;failed=1&amp;limit=50'
curl -s 'http://127.0.0.1:3425/v1/magpie/quotas?kept=1'
curl -s 'http://127.0.0.1:3425/v1/magpie/quotas/history?days=14'
curl -s http://127.0.0.1:3425/v1/magpie/limit -H 'Authorization: Bearer sk-magpie-…'
curl -s http://127.0.0.1:3425/v1/magpie/concurrency</pre>
</div>
<h2 id="trouble"><a class="anchor" href="#trouble">うまくいかないとき</a></h2>
<div class="table-wrap"><table>
<tr><th>表示</th><th>対処</th></tr>
+44
View File
@@ -77,6 +77,8 @@
<a href="#add">2. Add it on the other computer</a>
<a href="#models">What you get</a>
<a href="#quotas">Quotas and usage</a>
<a href="#keys">Short-lived keys</a>
<a href="#api">Stats API</a>
<a href="#trouble">When it doesn’t work</a>
</aside>
@@ -132,6 +134,48 @@ magpie provider refresh office <span class="c"># fetch its list again</span></
<p>The Usage page, the menu bar and <code>magpie quota</code> show the shared magpie’s subscription cards, named with it (<code>Codex · office</code>, id <code>office/codex</code>), as that magpie last read them: only the computer with the sign-ins asks the vendors. A card’s refresh here has it read that card once more, at most once every 30 seconds. A Codex reset or a WorkBuddy check-in is pressed on that computer, from its own app, TUI or CLI. A key that magpie holds to a budget, some models or some accounts is told none of its cards: only that key’s own card shows here, with its limit.</p>
<p>The shared magpie counts this computer’s requests under the name of the gateway key it sends, with the account that answered.</p>
<h2 id="keys"><a class="anchor" href="#keys">Short-lived keys</a></h2>
<p>A program that starts agents in sandboxes can give each one a gateway key of its own that stops working by itself. The key lives 1 minute to 30 days, and may be held to some models, some accounts, a number of tokens or a cost over its whole life, or to read-only use. Its secret is told once, in the answer.</p>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-keys">Copy</button>
<pre id="ex-keys">curl -s -X POST http://127.0.0.1:3425/v1/magpie/keys \
-d '{"name":"sandbox-1","ttl":"1h","models":["office/codex/gpt-5"],"tokens":200000}'
<span class="c"># {"id":"k…","name":"sandbox-1","key":"sk-magpie-…","expires":"…","models":[…],"limit":{…}}</span>
curl -s http://127.0.0.1:3425/v1/magpie/keys <span class="c"># the keys you issued, masked</span>
curl -s -X DELETE http://127.0.0.1:3425/v1/magpie/keys/k… <span class="c"># revoke one early</span></pre>
</div>
<p>A program on this computer may call it with no key; a page in a browser may not. Another computer, a container or CI calls it with a gateway key you let issue keys, and every key it issues is held to that key: never a model or account it may not use, never past its own expiry, and what they spend counts against its limit. Turning it off or removing it stops its keys at once. The same from the command line, which prints the key alone:</p>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-keys-cli">Copy</button>
<pre id="ex-keys-cli">magpie gateway-key issue --ttl 1h --name sandbox-1 --models office/codex/gpt-5 --tokens 200000
magpie gateway-key issuer &lt;id&gt; on <span class="c"># let a key issue keys</span>
magpie gateway-key issue --ttl 30m --from &lt;id&gt; --read-only --json
magpie gateway-key list <span class="c"># until 10-31 14:00, expired, issued by …</span></pre>
</div>
<p>An expired key is refused with <code>401</code> and why (“the gateway key "sandbox-1" expired at …: ask for a new one”) on every API, from this computer too. It is removed an hour later.</p>
<h2 id="api"><a class="anchor" href="#api">Stats API</a></h2>
<p>What the Usage page shows is also served as JSON, to this computer and, while magpie is shared, to a request with a gateway key. A key held to a budget, models or accounts is told only its own calls and limit.</p>
<ul>
<li><code>/v1/magpie/usage?period=today|7d|30d|all</code>: totals, by model, agent, provider, account and gateway key.</li>
<li><code>/v1/magpie/usage/requests</code>: the request log, with <code>period</code>, <code>day</code>, <code>offset</code>, <code>limit</code>, and filters <code>model</code>, <code>agent</code>, <code>provider</code>, <code>account</code>, <code>callerKey</code>, <code>failed=1</code>, <code>retried=1</code> and <code>q</code>.</li>
<li><code>/v1/magpie/quotas</code>: each subscription’s windows (<code>?kept=1</code> without asking the vendors); <code>/v1/magpie/quotas/history?days=</code>: what was left over time, 45 days at most.</li>
<li><code>/v1/magpie/limit</code>: the key’s own limits, its expiry, and its issuer’s limits.</li>
<li><code>/v1/magpie/concurrency</code>: requests in flight, per account.</li>
</ul>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-api">Copy</button>
<pre id="ex-api">curl -s 'http://127.0.0.1:3425/v1/magpie/usage?period=7d'
curl -s 'http://127.0.0.1:3425/v1/magpie/usage/requests?period=today&amp;callerKey=k…&amp;failed=1&amp;limit=50'
curl -s 'http://127.0.0.1:3425/v1/magpie/quotas?kept=1'
curl -s 'http://127.0.0.1:3425/v1/magpie/quotas/history?days=14'
curl -s http://127.0.0.1:3425/v1/magpie/limit -H 'Authorization: Bearer sk-magpie-…'
curl -s http://127.0.0.1:3425/v1/magpie/concurrency</pre>
</div>
<h2 id="trouble"><a class="anchor" href="#trouble">When it doesn’t work</a></h2>
<div class="table-wrap"><table>
<tr><th>You see</th><th>What to do</th></tr>
+44
View File
@@ -77,6 +77,8 @@
<a href="#add">2. 在其他电脑上添加</a>
<a href="#models">能用到什么</a>
<a href="#quotas">额度与用量</a>
<a href="#keys">短期密钥</a>
<a href="#api">统计 API</a>
<a href="#trouble">出问题时</a>
</aside>
@@ -132,6 +134,48 @@ magpie provider refresh office <span class="c"># 重新获取列表</span></pr
<p>用量页、菜单栏和 <code>magpie quota</code> 会显示共享 magpie 的订阅卡片,带上它的名字(<code>Codex · office</code>,id <code>office/codex</code>),内容是那边最近一次读取的结果:只有保存登录的电脑去问厂商。在本机刷新卡片会让那边再读一次,最多每 30 秒一次。Codex 重置或 WorkBuddy 签到要在那台电脑上,用它自己的应用、TUI 或 CLI 来做。那边限了额度、模型或账号的密钥看不到它的任何卡片:本机只显示这把密钥自己的卡片和它的限额。</p>
<p>共享的 magpie 把本机的请求记在本机所用网关密钥的名字下,并记下应答的账号。</p>
<h2 id="keys"><a class="anchor" href="#keys">短期密钥</a></h2>
<p>在沙箱里启动 agent 的程序,可以给每个 agent 发一把自己的网关密钥,到期自动失效。密钥有效期 1 分钟到 30 天,可以限定部分模型、部分账号、整个有效期内的 token 数或花费,或只读。密钥本身只在返回里出现一次。</p>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-keys">复制</button>
<pre id="ex-keys">curl -s -X POST http://127.0.0.1:3425/v1/magpie/keys \
-d '{"name":"sandbox-1","ttl":"1h","models":["office/codex/gpt-5"],"tokens":200000}'
<span class="c"># {"id":"k…","name":"sandbox-1","key":"sk-magpie-…","expires":"…","models":[…],"limit":{…}}</span>
curl -s http://127.0.0.1:3425/v1/magpie/keys <span class="c"># 你签发的密钥(已遮盖)</span>
curl -s -X DELETE http://127.0.0.1:3425/v1/magpie/keys/k… <span class="c"># 提前吊销</span></pre>
</div>
<p>本机上的程序不带密钥即可调用;浏览器里的网页不行。其他电脑、容器或 CI 要带一把你允许签发的网关密钥来调用,它签发的每把密钥都受它约束:用不了它不能用的模型和账号,不会比它晚过期,花费也计入它的限额。关掉或删掉它,它签发的密钥立刻失效。命令行里也一样,只输出密钥本身:</p>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-keys-cli">复制</button>
<pre id="ex-keys-cli">magpie gateway-key issue --ttl 1h --name sandbox-1 --models office/codex/gpt-5 --tokens 200000
magpie gateway-key issuer &lt;id&gt; on <span class="c"># 允许这个密钥签发密钥</span>
magpie gateway-key issue --ttl 30m --from &lt;id&gt; --read-only --json
magpie gateway-key list <span class="c"># until 10-31 14:00、expired、issued by …</span></pre>
</div>
<p>过期的密钥在每个 API 上都返回 <code>401</code> 并说明原因(“the gateway key "sandbox-1" expired at …: ask for a new one”),本机请求也一样。一小时后它会被删掉。</p>
<h2 id="api"><a class="anchor" href="#api">统计 API</a></h2>
<p>用量页上的内容也以 JSON 提供给本机;共享 magpie 时,也提供给带网关密钥的请求。受预算、模型或账号限制的密钥只能看到自己的请求和限额。</p>
<ul>
<li><code>/v1/magpie/usage?period=today|7d|30d|all</code>:总量,以及按模型、agent、提供商、账号和网关密钥的分项。</li>
<li><code>/v1/magpie/usage/requests</code>:请求记录,支持 <code>period</code>、<code>day</code>、<code>offset</code>、<code>limit</code>,以及筛选 <code>model</code>、<code>agent</code>、<code>provider</code>、<code>account</code>、<code>callerKey</code>、<code>failed=1</code>、<code>retried=1</code> 和 <code>q</code>。</li>
<li><code>/v1/magpie/quotas</code>:每个订阅的额度窗口(<code>?kept=1</code> 不去问厂商);<code>/v1/magpie/quotas/history?days=</code>:剩余额度的历史,最多 45 天。</li>
<li><code>/v1/magpie/limit</code>:这把密钥自己的限额、过期时间,以及签发它的密钥的限额。</li>
<li><code>/v1/magpie/concurrency</code>:每个账号正在进行的请求。</li>
</ul>
<div class="code">
<span class="lang">Shell</span>
<button class="copy" data-copy="ex-api">复制</button>
<pre id="ex-api">curl -s 'http://127.0.0.1:3425/v1/magpie/usage?period=7d'
curl -s 'http://127.0.0.1:3425/v1/magpie/usage/requests?period=today&amp;callerKey=k…&amp;failed=1&amp;limit=50'
curl -s 'http://127.0.0.1:3425/v1/magpie/quotas?kept=1'
curl -s 'http://127.0.0.1:3425/v1/magpie/quotas/history?days=14'
curl -s http://127.0.0.1:3425/v1/magpie/limit -H 'Authorization: Bearer sk-magpie-…'
curl -s http://127.0.0.1:3425/v1/magpie/concurrency</pre>
</div>
<h2 id="trouble"><a class="anchor" href="#trouble">出问题时</a></h2>
<div class="table-wrap"><table>
<tr><th>看到的提示</th><th>怎么做</th></tr>