Files
magpie/internal/gateway/issue_keys.go
T
yetone 2eac916170 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.
2026-10-31 13:44:29 +08:00

176 lines
5.5 KiB
Go

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:
}
}
})
}