gateway: a management API for providers, accounts and gateway keys, for a key set to manage (ljayic on X)
ljayic asked for a complete, stable management API so nothing needs a hand-edited file. /v1/magpie/admin/ now serves the app's own /api handlers (providers and their keys and accounts, OAuth sign-in start/poll/cancel, gateway keys, account groups) to a gateway key set with `magpie gateway-key admin <id> local|any`. Routes and actions not in gui/admin.go's adminRoutes are 404, so a provider's saved key, a gateway key's secret, sign-in export and actions on this computer's apps are not served; "admin-key" is not served either, so the API can't raise its own caller. Sign-in returns the vendor's page and code, opens nothing, takes no password. Guard (gateway/admin.go), in order: any Origin or Sec-Fetch-Site/-Mode is 403 with or without a key (Origin null, foreign, listed, *.localhost, an app scheme); no key 401; a key without Key.Admin 403; from loopback the Host must be ownHost (a rebound page's GET has no Origin); from the network the key must be "any"; a proxied request counts as remote. Key.Admin is dropped (adminOf) for a read-only, Browser, issued, expiring or default key, and setting read-only clears it. The route is in readOnlyRefused and keySlotFree. Docs: docs/reference.md "Management API", gateway-routing.md, and the remote page in en, zh and ja. Routing Groups, sign-in export and a GUI switch for the level are left to #6307. Run (mica, the worktree before the rebase onto 9 newer commits): go vet of access, cli, gateway, gui (darwin), GOOS=windows vet of the same four, GOOS=linux -tags nogui vet of access, cli, gateway; gofmt -l empty; go test -count=1 -timeout 45m ./internal/access ./internal/cli ./internal/gateway ./internal/gui: all ok but TestKeySlotEveryRoute, which named the new route and is fixed here, then it and the read-only, admin and guard tests pass again. After the rebase the same tests ran again. Broken by hand, each red in TestAdminAPIGuards: browser check off (a browser case served), Admin check off (a key without it served), Host check off (a rebound name served), the "any" requirement off (a local-only key from the network served, and a proxied request). Tests: TestAdminAPIGuards (no key, unknown key, non-admin, read-only, local/any, x-api-key, 8 browser headers x 3 callers, rebound Host, proxy, no handler), TestAdminKey (access: levels, read-only, Browser, issued), TestGatewayKeyCLIAdmin, TestAdminAPIGatewayKeys / Providers (a canary key is never told) / SignIn, TestAdminRoutesEveryAPIRoute. Not tried: a real sign-in against a vendor through the API, a request from a second computer on the LAN, the GUI suite (no page or app.js changed), a Linux/Windows run of the new tests.
This commit is contained in:
@@ -690,6 +690,7 @@ magpie gateway-key groups set Work codex/me@example.com # every key naming Wor
|
||||
magpie gateway-key mcp <id> github fs/read_file # only these MCP servers and tools
|
||||
magpie gateway-key mcp <id> none # no MCP server (all: every one)
|
||||
magpie gateway-key quotas <id> on # told the quotas of what it may use
|
||||
magpie gateway-key admin <id> local # may manage magpie through /v1/magpie/admin/, from this computer (any: from the network too; off)
|
||||
```
|
||||
|
||||
Each gateway key can have its own **limit**: a token total, an estimated
|
||||
@@ -1118,6 +1119,41 @@ default, `us-east-1`, `eu-central-1`, `ap-northeast-1`, `cn-hongkong` and
|
||||
Completions at `/compatible-mode/v1` and Anthropic Messages at
|
||||
`/apps/anthropic`.
|
||||
|
||||
### Management API
|
||||
|
||||
A script or a provisioning tool manages providers, accounts, gateway keys and
|
||||
account groups with no hand-edited file (ljayic on X). The routes are under
|
||||
`/v1/magpie/admin/` and are the app's own handlers, so a page and a script
|
||||
can't drift:
|
||||
|
||||
| Route | What it does |
|
||||
| --- | --- |
|
||||
| `GET providers` | the Providers list, as the app shows it (keys masked) |
|
||||
| `POST provider/{action}` | `save`, `delete`, `on`, `off`, `name`, `efforts`, `images`, `arrange`, `route`, `affinity`, `sink`, `usefirst`, `test`, `models`, `list`, and each key's or account's setting (`accountcap`, `accountname`, `windowcap`, `accountweight`, `keyspendcap`, `keyexpiring`, …) |
|
||||
| `POST keys/{action}`, `POST login/{action}`, `GET login/usage` | a provider's keys, and its signed-in accounts |
|
||||
| `POST signin` `{"agent": …}`, `GET signin/{id}`, `POST signin/{id}/cancel`, `POST signin/{id}/callback` | OAuth sign-in: the answer holds the vendor's page and the code to type there. Nothing is opened on this computer and no password is taken |
|
||||
| `GET gateway-keys[/models\|/mcp]`, `POST gateway-keys/{action}` | gateway keys: `add-key`, `rename-key`, `rotate-key`, `limit-key`, `models-key`, `accounts-key`, `mcp-key`, `access-key`, `on-key`, `off-key`, `remove-key`, … |
|
||||
| `GET account-groups`, `POST account-groups/{action}` | named account groups |
|
||||
|
||||
Bodies are the app's own JSON. A route or action not listed is a 404. Never
|
||||
served: a provider's saved key, a gateway key's secret after its `add-key` or
|
||||
`rotate-key` answer, exporting sign-ins, and what changes this computer's
|
||||
other apps (moving, showing, restarting).
|
||||
|
||||
Who may call it: a gateway key set with `magpie gateway-key admin <id>
|
||||
local|any`. `local` is from this computer only; `any` also from the network
|
||||
when sharing is on. Only a key the user made can have it: a read-only,
|
||||
Magpie Browser, issued or expiring key, and the default sharing key, can't,
|
||||
and the API can't set the level on any key, so it can't raise its own
|
||||
caller. A request with no key is 401, a key without the level 403
|
||||
(`gateway_key_not_admin`). Browsers never call it, with or without a key:
|
||||
any request with `Origin` (`null`, a foreign page, a listed page or
|
||||
`*.localhost` among them) or `Sec-Fetch-*` is 403, and so is one that
|
||||
reached loopback under another name (a rebound page's GET has neither).
|
||||
Answers are `Cache-Control: no-store`. This first part leaves out Routing
|
||||
Groups (the Routing page) and the import and export of sign-ins; they are
|
||||
tracked in [#6307](https://github.com/yetone/magpie/issues/6307).
|
||||
|
||||
### Embeddings and rerank
|
||||
|
||||
The gateway serves two retrieval APIs beside chat, at `/v1/embeddings` and
|
||||
|
||||
@@ -1452,6 +1452,26 @@ told its own calls and limit alone:
|
||||
| `GET /v1/magpie/concurrency` | requests in flight per account |
|
||||
| `POST`/`GET /v1/magpie/keys`, `DELETE /v1/magpie/keys/{id}` | short-lived keys, above |
|
||||
| `POST /v1/magpie/keys/oidc` | an OIDC token traded for a short-lived key, above |
|
||||
| `/v1/magpie/admin/…` | the management API: the app's provider, account, gateway-key and account-group handlers for a key with `Key.Admin`, below |
|
||||
|
||||
### The management API
|
||||
|
||||
`/v1/magpie/admin/` (ljayic on X) serves the GUI's own `/api` handlers to a
|
||||
script. [`admin.go`](../../internal/gateway/admin.go) is the guard and
|
||||
[`internal/gui/admin.go`](../../internal/gui/admin.go) the route list
|
||||
(`adminRoutes`: what is served, to which `/api` route; anything else is a
|
||||
404, and `TestAdminRoutesEveryAPIRoute` fails when a listed route is not the
|
||||
app's). The guard, in order: a request carrying `Origin` or `Sec-Fetch-Site`
|
||||
or `-Mode` is refused with a key or without (a page can't leave them off, so
|
||||
`Origin: null`, a foreign or listed page and `*.localhost` need no case of
|
||||
their own); no key is 401; `Identity.Admin == ""` is 403; from loopback the
|
||||
Host must be `ownHost` (a rebound page's GET has no Origin), and from
|
||||
anywhere else the key must be `AdminAny`. `Key.Admin` is set only by
|
||||
`magpie gateway-key admin` and the app, never through the API, and
|
||||
`adminOf` drops it for a read-only, Browser, issued, expiring or default
|
||||
key. The route is in `readOnlyRefused`, so a read-only key never reaches
|
||||
it. The handlers are built with no window, so a sign-in opens no browser.
|
||||
Routing Groups and sign-in export are not in it yet (#6307).
|
||||
|
||||
### Route events for a display
|
||||
|
||||
|
||||
@@ -178,6 +178,12 @@ type Key struct {
|
||||
// this field, which reads it as any other key, holds it to reading
|
||||
// stats rather than handing it every model.
|
||||
Browser bool `json:"browser,omitempty"`
|
||||
// Admin lets the key use the management API (/v1/magpie/admin/, ljayic
|
||||
// on X): AdminLocal from this computer only, AdminAny from the network
|
||||
// too; "" for none. Only a key the user made themselves can have it:
|
||||
// not a read-only, browser, issued or expiring key, nor the default
|
||||
// sharing key, which magpie hands to agents.
|
||||
Admin string `json:"admin,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"`
|
||||
@@ -271,6 +277,8 @@ type Identity struct {
|
||||
// Browser: the key may connect the Magpie Browser extension and do
|
||||
// nothing else (Key.Browser).
|
||||
Browser bool
|
||||
// Admin is Key.Admin, "" for a key that can't have it (adminOf).
|
||||
Admin string
|
||||
// sum is the SHA-256 of the secret the request came with, so a
|
||||
// connection kept open can tell the key was rotated since (Current).
|
||||
sum [32]byte
|
||||
@@ -493,6 +501,8 @@ type Change struct {
|
||||
// Browser is what "add-key" gives the new key: it may connect the
|
||||
// Magpie Browser extension alone (Key.Browser).
|
||||
Browser bool `json:"browser,omitempty"`
|
||||
// Admin is what "admin-key" sets (CleanAdmin's AdminLocal, AdminAny or "").
|
||||
Admin string `json:"admin,omitempty"`
|
||||
// Issues is what "issuer-key" sets: the key may issue short-lived
|
||||
// keys under itself (Key.Issues).
|
||||
Issues bool `json:"issues,omitempty"`
|
||||
@@ -714,6 +724,27 @@ func Update(action string, in Change) (string, error) {
|
||||
return "", errors.New("This key is the Magpie Browser extension's: it connects the extension and nothing else. Add another key for models or stats")
|
||||
}
|
||||
keys[i].ReadOnly = in.ReadOnly
|
||||
if in.ReadOnly {
|
||||
keys[i].Admin = ""
|
||||
}
|
||||
case "admin-key":
|
||||
// the management API changes providers, accounts and keys, so
|
||||
// only a key the user made for it can hold it
|
||||
level, err := CleanAdmin(in.Admin)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if level != "" {
|
||||
switch {
|
||||
case defaultKey:
|
||||
return "", errors.New("The sharing key is the one magpie gives agents that reach it from elsewhere, so it can't manage magpie: add a key of its own for that")
|
||||
case keys[i].Browser || keys[i].ReadOnly:
|
||||
return "", errors.New("A read-only key, or the Magpie Browser extension's, can't manage magpie: add another key for that")
|
||||
case keys[i].Issuer != "" || !keys[i].Expires.IsZero():
|
||||
return "", errors.New("An issued key can't manage magpie: let a key of yours do it")
|
||||
}
|
||||
}
|
||||
keys[i].Admin = level
|
||||
case "on-key", "off-key":
|
||||
keys[i].Off = action == "off-key"
|
||||
case "remove-key":
|
||||
@@ -737,7 +768,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 != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "tier-key" && action != "redact-key" && action != "access-key" && action != "issuer-key" && action != "move-key" {
|
||||
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "aliases-key" && action != "accounts-key" && action != "mcp-key" && action != "quotas-key" && action != "concurrency-key" && action != "tier-key" && action != "redact-key" && action != "access-key" && action != "issuer-key" && action != "admin-key" && action != "move-key" {
|
||||
mirror = &keys[i]
|
||||
}
|
||||
}
|
||||
@@ -988,3 +1019,31 @@ func save(keys []Key) error {
|
||||
}
|
||||
return edit.WriteAtomic(Path(), append(b, '\n'))
|
||||
}
|
||||
|
||||
// The levels of Key.Admin.
|
||||
const (
|
||||
AdminLocal = "local"
|
||||
AdminAny = "any"
|
||||
)
|
||||
|
||||
// CleanAdmin reads a management level: "" (off), AdminLocal or AdminAny.
|
||||
func CleanAdmin(v string) (string, error) {
|
||||
switch strings.ToLower(strings.TrimSpace(v)) {
|
||||
case "", "off", "none", "no", "false":
|
||||
return "", nil
|
||||
case "local", "this-computer", "loopback":
|
||||
return AdminLocal, nil
|
||||
case "any", "remote", "on", "all":
|
||||
return AdminAny, nil
|
||||
}
|
||||
return "", fmt.Errorf("unknown management level %q: use off, local or any", v)
|
||||
}
|
||||
|
||||
// adminOf is the management level a key really has: none for a key that
|
||||
// can't hold it, whatever the file says.
|
||||
func adminOf(k Key) string {
|
||||
if k.Issuer != "" || k.ReadOnly || k.Browser || !k.Expires.IsZero() || k.LAN {
|
||||
return ""
|
||||
}
|
||||
return k.Admin
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ljayic on X: a key can be given the management API, but only a key the
|
||||
// user made for it, and only by the user.
|
||||
func TestAdminKey(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
plainID, plain := addKey(t, "plain")
|
||||
if who, ok := Authenticate(plain); !ok || who.Admin != "" {
|
||||
t.Fatalf("a new key has Admin %q", who.Admin)
|
||||
}
|
||||
if _, err := Update("admin-key", Change{Key: plainID, Admin: "sometimes"}); err == nil {
|
||||
t.Fatal("an unknown level was taken")
|
||||
}
|
||||
for in, want := range map[string]string{"local": AdminLocal, "any": AdminAny, "off": ""} {
|
||||
if _, err := Update("admin-key", Change{Key: plainID, Admin: in}); err != nil {
|
||||
t.Fatal(in, err)
|
||||
}
|
||||
if who, _ := Authenticate(plain); who.Admin != want {
|
||||
t.Errorf("admin %s: Admin %q, want %q", in, who.Admin, want)
|
||||
}
|
||||
}
|
||||
|
||||
// read-only: refused, and read-only takes the level away
|
||||
if _, err := Update("admin-key", Change{Key: plainID, Admin: "any"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Update("access-key", Change{Key: plainID, ReadOnly: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if who, _ := Authenticate(plain); who.Admin != "" {
|
||||
t.Error("a key made read-only kept Admin")
|
||||
}
|
||||
if _, err := Update("admin-key", Change{Key: plainID, Admin: "local"}); err == nil {
|
||||
t.Error("a read-only key was given Admin")
|
||||
}
|
||||
|
||||
// the extension's key
|
||||
if _, err := Update("add-key", Change{Name: "ext", Browser: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys, _ := List()
|
||||
if _, err := Update("admin-key", Change{Key: keys[len(keys)-1].ID, Admin: "local"}); err == nil {
|
||||
t.Error("the extension's key was given Admin")
|
||||
}
|
||||
|
||||
// an issued key, even when the file says otherwise
|
||||
issuerID, _ := addKey(t, "issuer")
|
||||
if _, err := Update("admin-key", Change{Key: issuerID, Admin: "any"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Update("issuer-key", Change{Key: issuerID, Issues: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
k, err := IssueKey(Issue{Name: "sandbox", TTL: time.Hour, Issuer: issuerID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if who, ok := Authenticate(k.Key); !ok || who.Admin != "" {
|
||||
t.Errorf("an issued key has Admin %q", who.Admin)
|
||||
}
|
||||
keys, _ = List()
|
||||
for _, key := range keys {
|
||||
if key.Issuer != "" {
|
||||
if _, err := Update("admin-key", Change{Key: key.ID, Admin: "any"}); err == nil || !strings.Contains(err.Error(), "issued") {
|
||||
t.Errorf("an issued key was given Admin: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -353,10 +353,13 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
|
||||
return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q names an account group, and magpie can't read its account groups now: %v", k.Name, err)}
|
||||
}
|
||||
k.Accounts = accounts
|
||||
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency, ServiceTier: k.ServiceTier, Redact: k.Redact}
|
||||
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Aliases: k.Aliases, AccountModels: len(k.Models) == 0 && picksAccounts(k.Accounts), Accounts: k.Accounts, MCP: k.MCP, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Admin: adminOf(k), Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser, MaxConcurrency: k.MaxConcurrency, ServiceTier: k.ServiceTier, Redact: k.Redact}
|
||||
// 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 who.Default {
|
||||
who.Admin = ""
|
||||
}
|
||||
if k.Issuer == "" {
|
||||
return who, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// gateway-key admin (ljayic on X): the one way to give a key the
|
||||
// management API besides the app.
|
||||
func TestGatewayKeyCLIAdmin(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)
|
||||
}
|
||||
run := 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 := run("add", "Automation")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys, _ := access.List()
|
||||
id := keys[len(keys)-1].ID
|
||||
if got, err := run("admin", id); err != nil || !strings.Contains(strings.ToLower(got), "off") && !strings.Contains(strings.ToLower(got), "no") {
|
||||
t.Fatalf("admin (show): %q %v", got, err)
|
||||
}
|
||||
if _, err := run("admin", id, "local"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if who, _ := access.Authenticate(secret); who.Admin != access.AdminLocal {
|
||||
t.Fatalf("after local: %q", who.Admin)
|
||||
}
|
||||
if _, err := run("admin", id, "any"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if who, _ := access.Authenticate(secret); who.Admin != access.AdminAny {
|
||||
t.Fatalf("after any: %q", who.Admin)
|
||||
}
|
||||
if _, err := run("admin", id, "--help"); err == nil {
|
||||
t.Error("a flag was taken as a level")
|
||||
}
|
||||
if _, err := run("admin", id, "banana"); err == nil {
|
||||
t.Error("an unknown level was taken")
|
||||
}
|
||||
if who, _ := access.Authenticate(secret); who.Admin != access.AdminAny {
|
||||
t.Errorf("a refused level changed the key: %q", who.Admin)
|
||||
}
|
||||
if _, err := run("admin", id, "off"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if who, _ := access.Authenticate(secret); who.Admin != "" {
|
||||
t.Errorf("after off: %q", who.Admin)
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,10 @@ func gatewayKeysTo(out io.Writer, args []string) error {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
return gatewayKeyAccess(out, args[1:])
|
||||
}
|
||||
if action == "admin" {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
return gatewayKeyAdmin(out, args[1:])
|
||||
}
|
||||
if action == "move" {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
return gatewayKeyMove(out, args[1:])
|
||||
@@ -941,6 +945,47 @@ func gatewayKeyAccess(out io.Writer, args []string) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// gatewayKeyAdmin shows or sets whether a key may call the management API
|
||||
// (/v1/magpie/admin/), which adds, changes and removes providers, accounts
|
||||
// and gateway keys:
|
||||
//
|
||||
// magpie gateway-key admin <id> [off | local | any]
|
||||
//
|
||||
// Only here and in the app: the API itself never sets it.
|
||||
func gatewayKeyAdmin(out io.Writer, args []string) error {
|
||||
usage := fmt.Errorf("usage: magpie gateway-key admin <id> [off | local | any]")
|
||||
if len(args) == 0 || len(args) > 2 {
|
||||
return usage
|
||||
}
|
||||
id := args[0]
|
||||
if len(args) == 2 {
|
||||
if _, err := access.CleanAdmin(args[1]); err != nil {
|
||||
return usage
|
||||
}
|
||||
if _, err := access.Update("admin-key", access.Change{Key: id, Admin: args[1]}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
keys, err := access.List()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i := slices.IndexFunc(keys, func(k access.Key) bool { return k.ID == id })
|
||||
if i < 0 {
|
||||
return fmt.Errorf("Key not found")
|
||||
}
|
||||
k := keys[i]
|
||||
switch k.Admin {
|
||||
case access.AdminLocal:
|
||||
_, err = fmt.Fprintf(out, "%s: may manage magpie (/v1/magpie/admin/) from this computer\n", k.Name)
|
||||
case access.AdminAny:
|
||||
_, err = fmt.Fprintf(out, "%s: may manage magpie (/v1/magpie/admin/) from this computer and, while magpie is shared, from other machines\n", k.Name)
|
||||
default:
|
||||
_, err = fmt.Fprintf(out, "%s: may not manage magpie\n", k.Name)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// gatewayKeyMove puts a key at a place in the list, counted from 1 as
|
||||
// `magpie gateway-key list` shows them, the order the app's Gateway page
|
||||
// lists them in too, where a key is dragged to its place (alextjy on
|
||||
|
||||
@@ -155,6 +155,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie gateway-key concurrency <id> [<n>|off] at most n of a key's requests at once; the rest wait their turn
|
||||
magpie gateway-key mcp <id> [all|none|<server>|<server>/<tool> ...] the MCP servers and tools a key 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 admin <id> [off|local|any] let the key manage providers, accounts and gateway keys through /v1/magpie/admin/ (local: from this computer only)
|
||||
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
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
)
|
||||
|
||||
// AdminPath is the management API: add, change and remove the providers,
|
||||
// accounts and gateway keys the app's pages manage, for automation
|
||||
// (ljayic on X). The routes under it are the app's own (internal/gui,
|
||||
// adminAPI), so the two can't drift; this file decides who may call them.
|
||||
//
|
||||
// Unlike every model route, no call is let in as "from this computer": it
|
||||
// needs an enabled gateway key that carries Admin (access.Key.Admin, set by
|
||||
// `magpie gateway-key admin` and the app, never through the API), from
|
||||
// loopback and from anywhere. A key the gateway doesn't know, and a call
|
||||
// with none, are 401; any other key is 403. From another machine the key
|
||||
// must be AdminAny, and the gateway is shared (lanGuard) as for any call
|
||||
// from there.
|
||||
//
|
||||
// And no browser calls it, with a key or without: a page sends Origin, or
|
||||
// the Sec-Fetch headers, and a script can't take them off, so one is
|
||||
// refused whatever its Origin says (null, a foreign page, a listed page,
|
||||
// localhost). A request that names this computer by a name that isn't its
|
||||
// own (DNS rebinding) is refused too, with its key or without.
|
||||
const AdminPath = "/v1/magpie/admin/"
|
||||
|
||||
// adminHandler is what serves the routes under AdminPath, set by the app's
|
||||
// package (gui) at start; nil serves 503.
|
||||
var adminHandler atomic.Pointer[http.Handler]
|
||||
|
||||
// SetAdminHandler sets the handler for the routes under AdminPath. The path
|
||||
// it sees has AdminPath's prefix taken off, with its leading slash kept.
|
||||
func SetAdminHandler(h http.Handler) { adminHandler.Store(&h) }
|
||||
|
||||
// AdminCode is the error code a key without Admin is refused with.
|
||||
const AdminCode = "gateway_key_not_admin"
|
||||
|
||||
func adminRefuse(w http.ResponseWriter, status int, code, msg string) {
|
||||
writeJSON(w, status, map[string]any{"error": map[string]any{"message": msg, "type": "permission_error", "code": code}})
|
||||
}
|
||||
|
||||
func (s *Server) admin(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
// a page, whatever it says it is: its headers aren't its script's to drop
|
||||
if r.Header.Get("Origin") != "" || r.Header.Get("Sec-Fetch-Site") != "" || r.Header.Get("Sec-Fetch-Mode") != "" {
|
||||
log.Printf("refused %s %s: the management API answers no web page (Origin %q)", r.Method, r.URL.Path, r.Header.Get("Origin"))
|
||||
adminRefuse(w, http.StatusForbidden, "admin_browser_refused", "magpie's management API is for scripts, not web pages: a request that carries Origin or Sec-Fetch headers is refused, with a key or without")
|
||||
return
|
||||
}
|
||||
who := access.Caller(r.Context())
|
||||
if who.KeyID == "" {
|
||||
adminRefuse(w, http.StatusUnauthorized, "admin_key_required", "the management API needs a gateway key that may manage magpie, even from this computer: send it as Authorization: Bearer <key>, after `magpie gateway-key admin <id> local`")
|
||||
return
|
||||
}
|
||||
if who.Admin == "" {
|
||||
log.Printf("refused %s %s: gateway key %q may not manage magpie", r.Method, r.URL.Path, who.KeyName)
|
||||
adminRefuse(w, http.StatusForbidden, AdminCode, "this gateway key may not manage magpie: allow it with `magpie gateway-key admin <id> local` (or `any` for other machines)")
|
||||
return
|
||||
}
|
||||
if local(r) {
|
||||
if !ownHost(r.Host) {
|
||||
log.Printf("refused %s %s: reached loopback as %q", r.Method, r.URL.Path, r.Host)
|
||||
adminRefuse(w, http.StatusForbidden, "admin_host_refused", "magpie's management API doesn't answer a request that reached this computer under the name "+r.Host+": call it as localhost or 127.0.0.1")
|
||||
return
|
||||
}
|
||||
} else if who.Admin != access.AdminAny {
|
||||
log.Printf("refused %s %s from another machine: gateway key %q may manage magpie from this computer only", r.Method, r.URL.Path, who.KeyName)
|
||||
adminRefuse(w, http.StatusForbidden, AdminCode, "this gateway key may manage magpie from this computer only: allow other machines with `magpie gateway-key admin <id> any`")
|
||||
return
|
||||
}
|
||||
hp := adminHandler.Load()
|
||||
if hp == nil {
|
||||
adminRefuse(w, http.StatusServiceUnavailable, "admin_unavailable", "this magpie serves no management API")
|
||||
return
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4<<20)
|
||||
rest := "/" + strings.TrimPrefix(r.URL.Path, AdminPath)
|
||||
log.Printf("management API: %s %s by gateway key %q", r.Method, rest, who.KeyName)
|
||||
r2 := r.Clone(r.Context())
|
||||
r2.URL.Path, r2.URL.RawPath = rest, ""
|
||||
// the app's own handlers answer a key in the request as they would a
|
||||
// page's; none of the headers are theirs to see
|
||||
for _, h := range []string{"Authorization", "X-Api-Key", "X-Goog-Api-Key"} {
|
||||
r2.Header.Del(h)
|
||||
}
|
||||
(*hp).ServeHTTP(w, r2)
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
)
|
||||
|
||||
// adminCall sends one request to the gateway as lanGuard serves it.
|
||||
func adminCall(h http.Handler, method, path, from, host, key string, hdr map[string]string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, strings.NewReader("{}"))
|
||||
r.RemoteAddr = from
|
||||
r.Host = "127.0.0.1:3425"
|
||||
if host != "" {
|
||||
r.Host = host
|
||||
}
|
||||
if key != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+key)
|
||||
}
|
||||
for k, v := range hdr {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestAdminAPIGuards(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
var seen *http.Request
|
||||
SetAdminHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
seen = r
|
||||
w.Write([]byte("managed " + r.URL.Path))
|
||||
}))
|
||||
t.Cleanup(func() { adminHandler.Store(nil) })
|
||||
keys, secrets := newCaller(t, "plain", "local admin", "any admin", "reader")
|
||||
for i, level := range map[int]string{1: access.AdminLocal, 2: access.AdminAny} {
|
||||
if _, err := access.Update("admin-key", access.Change{Key: keys[i].ID, Admin: level}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := access.Update("access-key", access.Change{Key: keys[3].ID, ReadOnly: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plain, local, anyKey, reader := secrets[0], secrets[1], secrets[2], secrets[3]
|
||||
h := lanGuard(New().Handler())
|
||||
const path = AdminPath + "providers"
|
||||
const loop, lan = "127.0.0.1:50000", "192.0.2.7:50000"
|
||||
|
||||
t.Run("no key", func(t *testing.T) {
|
||||
if w := adminCall(h, "GET", path, loop, "", "", nil); w.Code != 401 {
|
||||
t.Errorf("from this computer with no key: %d, want 401", w.Code)
|
||||
}
|
||||
if w := adminCall(h, "GET", path, loop, "", "not-a-key", nil); w.Code != 401 {
|
||||
t.Errorf("with a key magpie doesn't know: %d, want 401", w.Code)
|
||||
}
|
||||
if w := adminCall(h, "GET", path, lan, "", "", nil); w.Code != 401 {
|
||||
t.Errorf("from the network with no key: %d, want 401", w.Code)
|
||||
}
|
||||
})
|
||||
t.Run("a key without Admin", func(t *testing.T) {
|
||||
for _, from := range []string{loop, lan} {
|
||||
w := adminCall(h, "GET", path, from, "", plain, nil)
|
||||
if w.Code != 403 || !strings.Contains(w.Body.String(), AdminCode) {
|
||||
t.Errorf("from %s: %d %s, want 403 %s", from, w.Code, w.Body, AdminCode)
|
||||
}
|
||||
}
|
||||
if w := adminCall(h, "GET", path, loop, "", reader, nil); w.Code != 403 {
|
||||
t.Errorf("read-only key: %d, want 403", w.Code)
|
||||
}
|
||||
})
|
||||
t.Run("a key with Admin", func(t *testing.T) {
|
||||
seen = nil
|
||||
w := adminCall(h, "GET", path, loop, "", local, nil)
|
||||
if w.Code != 200 || w.Body.String() != "managed /providers" {
|
||||
t.Fatalf("local admin from this computer: %d %q", w.Code, w.Body)
|
||||
}
|
||||
if seen.Header.Get("Authorization") != "" {
|
||||
t.Error("the key was passed on to the handler")
|
||||
}
|
||||
if w := adminCall(h, "GET", path, lan, "", local, nil); w.Code != 403 {
|
||||
t.Errorf("a local-only admin key from the network: %d, want 403", w.Code)
|
||||
}
|
||||
if w := adminCall(h, "GET", path, lan, "", anyKey, nil); w.Code != 200 {
|
||||
t.Errorf("an any admin key from the network: %d, want 200", w.Code)
|
||||
}
|
||||
// the key may be in x-api-key too
|
||||
r := httptest.NewRequest("GET", path, nil)
|
||||
r.Host = "127.0.0.1:3425"
|
||||
r.RemoteAddr = loop
|
||||
r.Header.Set("x-api-key", local)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
if rec.Code != 200 {
|
||||
t.Errorf("x-api-key: %d", rec.Code)
|
||||
}
|
||||
})
|
||||
t.Run("a browser", func(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
hdr map[string]string
|
||||
}{
|
||||
{"Origin null", map[string]string{"Origin": "null"}},
|
||||
{"a foreign page", map[string]string{"Origin": "https://evil.example"}},
|
||||
{"a page on localhost", map[string]string{"Origin": "http://localhost:3000"}},
|
||||
{"a localhost subdomain", map[string]string{"Origin": "http://a.localhost"}},
|
||||
{"its own origin", map[string]string{"Origin": "http://127.0.0.1:3425"}},
|
||||
{"an app's scheme", map[string]string{"Origin": "app://obsidian.md"}},
|
||||
{"Sec-Fetch-Site alone", map[string]string{"Sec-Fetch-Site": "same-origin"}},
|
||||
{"Sec-Fetch-Mode alone", map[string]string{"Sec-Fetch-Mode": "cors"}},
|
||||
} {
|
||||
// no key, a key without Admin, and a key with it: none gets in
|
||||
for who, key := range map[string]string{"no key": "", "plain key": plain, "admin key": local} {
|
||||
w := adminCall(h, "POST", AdminPath+"provider/save", loop, "", key, tc.hdr)
|
||||
if w.Code == 200 {
|
||||
t.Errorf("%s with %s: served", tc.name, who)
|
||||
}
|
||||
if key == local && w.Code != 403 {
|
||||
t.Errorf("%s with the admin key: %d, want 403", tc.name, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("a rebound name", func(t *testing.T) {
|
||||
for who, key := range map[string]string{"no key": "", "plain key": plain, "admin key": local} {
|
||||
w := adminCall(h, "GET", path, loop, "attacker.example:3425", key, nil)
|
||||
if w.Code == 200 {
|
||||
t.Errorf("Host attacker.example with %s: served", who)
|
||||
}
|
||||
if key == local && w.Code != 403 {
|
||||
t.Errorf("Host attacker.example with the admin key: %d, want 403", w.Code)
|
||||
}
|
||||
}
|
||||
if w := adminCall(h, "GET", path, loop, "localhost:3425", local, nil); w.Code != 200 {
|
||||
t.Errorf("Host localhost: %d", w.Code)
|
||||
}
|
||||
})
|
||||
t.Run("through a proxy", func(t *testing.T) {
|
||||
w := adminCall(h, "GET", path, loop, "", local, map[string]string{"X-Forwarded-For": "203.0.113.9"})
|
||||
if w.Code != 403 {
|
||||
t.Errorf("a local-only admin key through a proxy: %d, want 403", w.Code)
|
||||
}
|
||||
})
|
||||
t.Run("no handler", func(t *testing.T) {
|
||||
adminHandler.Store(nil)
|
||||
if w := adminCall(h, "GET", path, loop, "", local, nil); w.Code != 503 {
|
||||
t.Errorf("no handler set: %d, want 503", w.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1045,6 +1045,8 @@ func (s *Server) routes() *routeMux {
|
||||
mux.HandleFunc("GET "+routeEventsPath, s.routeEvents)
|
||||
mux.HandleFunc("GET /v1/magpie/concurrency", s.concurrency)
|
||||
mux.HandleFunc("GET /v1/magpie/limit", s.keyLimit)
|
||||
// the management API, for a key that may manage magpie (admin.go)
|
||||
mux.HandleFunc(AdminPath, s.admin)
|
||||
mux.HandleFunc("GET "+OwnMCPPath, s.ownMCPList)
|
||||
// short-lived keys, issued by a key let issue them or from loopback
|
||||
// (issue_keys.go)
|
||||
|
||||
@@ -29,7 +29,7 @@ var keySlotFree = []string{
|
||||
"POST " + RestartPath, "POST " + provider.RemoteUpdatePath, "POST /v1/messages/count_tokens",
|
||||
"POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}", SearchMCPPath, VisionMCPPath,
|
||||
ImageMCPPath, BrowserMCPPath, MemoryMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, ToolsMCPOne + "{plugin}",
|
||||
HubMCPPath + "{agent}", HubMCPAll, "/", "POST " + joinData,
|
||||
HubMCPPath + "{agent}", HubMCPAll, "/", "POST " + joinData, AdminPath,
|
||||
}
|
||||
|
||||
// Every route is judged for a key's MaxConcurrency: held (keySlotRoutes)
|
||||
|
||||
@@ -34,7 +34,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}", "POST " + OIDCKeysPath,
|
||||
AdminPath, "POST " + KeysPath, "GET " + KeysPath, "DELETE " + KeysPath + "/{id}", "POST " + OIDCKeysPath,
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// The management API (gateway.AdminPath, ljayic on X) serves the app's own
|
||||
// handlers for providers, accounts and gateway keys, so that what a script
|
||||
// does and what the pages do can't drift. adminRoutes lists, by the path
|
||||
// under /v1/magpie/admin/, what is served and which of the app's /api route
|
||||
// answers it; a route not listed is a 404, whatever the app has, and
|
||||
// TestAdminRoutesEveryAPIRoute fails when the list holds a route that is
|
||||
// not the app's.
|
||||
//
|
||||
// Left out on purpose, because they tell a secret or act on this
|
||||
// computer's apps and not on magpie's own objects: a provider's saved key
|
||||
// ("key"), a gateway key's secret ("copy-key"), exporting sign-ins, and
|
||||
// the actions that move, restart or rewrite an agent. Setting a key's
|
||||
// Admin ("admin-key") is left out so that a key can't give another more
|
||||
// than it was given: only the command line and the app do.
|
||||
type adminRoute struct {
|
||||
pattern string // "GET /providers": the method, and the path under AdminPath
|
||||
to string // the app's route under /api it is served by, "" for the same path
|
||||
// actions, when set, are the {action}s the route takes; any other is 404
|
||||
actions []string
|
||||
}
|
||||
|
||||
var adminRoutes = []adminRoute{
|
||||
{pattern: "GET /providers"},
|
||||
{pattern: "POST /provider/{action}", actions: adminProviderActions},
|
||||
{pattern: "POST /keys/{action}"},
|
||||
{pattern: "POST /login/{action}"},
|
||||
{pattern: "GET /login/usage"},
|
||||
{pattern: "GET /signin/{id}"},
|
||||
{pattern: "POST /signin/{id}/cancel"},
|
||||
{pattern: "POST /signin/{id}/callback"},
|
||||
{pattern: "GET /gateway-keys", to: "/caller-keys"},
|
||||
{pattern: "GET /gateway-keys/models", to: "/caller-keys/models"},
|
||||
{pattern: "GET /gateway-keys/mcp", to: "/caller-keys/mcp"},
|
||||
{pattern: "POST /gateway-keys/{action}", to: "/caller-keys/{action}", actions: adminKeyActions},
|
||||
{pattern: "GET /account-groups"},
|
||||
{pattern: "POST /account-groups/{action}"},
|
||||
}
|
||||
|
||||
// adminProviderActions are the provider actions the API takes: saving and
|
||||
// removing a provider, switching it, and the settings of its keys and
|
||||
// accounts, and trying it. Not "key" (it tells the saved key), nor the
|
||||
// actions on this computer's apps (show, move, adopt, restartapp, …).
|
||||
var adminProviderActions = []string{
|
||||
"save", "delete", "on", "off", "name", "efforts", "images", "arrange",
|
||||
"accountmodels", "keylisted", "accountcap", "accountname", "windowcap",
|
||||
"accountconcurrency", "keyspendcap", "keyownbalance", "keybalancerefill",
|
||||
"keyexpiring", "accountweight", "route", "affinity", "sink", "usefirst",
|
||||
"test", "teststop", "detect", "balance", "models", "list",
|
||||
}
|
||||
|
||||
// adminKeyActions are access.Update's actions but "admin-key" and "copy-key".
|
||||
var adminKeyActions = []string{
|
||||
"add-key", "rotate-key", "rename-key", "limit-key", "reset-limit-key",
|
||||
"models-key", "aliases-key", "accounts-key", "mcp-key", "quotas-key",
|
||||
"concurrency-key", "tier-key", "redact-key", "issuer-key", "access-key",
|
||||
"on-key", "off-key", "remove-key", "move-key",
|
||||
}
|
||||
|
||||
var (
|
||||
adminOnce sync.Once
|
||||
adminMux http.Handler
|
||||
)
|
||||
|
||||
func init() { gateway.SetAdminHandler(http.HandlerFunc(serveAdmin)) }
|
||||
|
||||
func serveAdmin(w http.ResponseWriter, r *http.Request) {
|
||||
adminOnce.Do(func() { adminMux = adminAPI() })
|
||||
adminMux.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// adminAPI is the management API's routes. The app's handlers are built
|
||||
// with no window (nil Windows), so none opens a browser or a folder here.
|
||||
func adminAPI() http.Handler {
|
||||
app := http.NewServeMux()
|
||||
providerRoutes(app, nil)
|
||||
callerKeyRoutes(app)
|
||||
mux := http.NewServeMux()
|
||||
for _, ar := range adminRoutes {
|
||||
mux.HandleFunc(ar.pattern, func(w http.ResponseWriter, r *http.Request) {
|
||||
if ar.actions != nil && !slices.Contains(ar.actions, r.PathValue("action")) {
|
||||
adminError(w, http.StatusNotFound, "this action is not in the management API")
|
||||
return
|
||||
}
|
||||
to := r.URL.Path
|
||||
if ar.to != "" {
|
||||
to = strings.ReplaceAll(ar.to, "{action}", r.PathValue("action"))
|
||||
}
|
||||
r2 := r.Clone(r.Context())
|
||||
r2.URL.Path, r2.URL.RawPath = "/api"+to, ""
|
||||
app.ServeHTTP(w, r2)
|
||||
})
|
||||
}
|
||||
// Signing in: the vendor's page and the code to type there are the
|
||||
// answer, for the caller to open on a computer with a browser. Never
|
||||
// opened here, and never given a password: the vendor's page takes it.
|
||||
mux.HandleFunc("POST /signin", func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Agent, Site string
|
||||
Proxy *string
|
||||
User string
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
adminError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
st, err := provider.StartSignInWith(in.Agent, provider.SignInOptions{Site: in.Site, Proxy: in.Proxy, User: in.User})
|
||||
if err != nil {
|
||||
adminError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, st)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
func adminError(w http.ResponseWriter, status int, msg string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"error": msg})
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
)
|
||||
|
||||
func adminDo(t *testing.T, method, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
serveAdmin(w, httptest.NewRequest(method, path, strings.NewReader(body)))
|
||||
return w
|
||||
}
|
||||
|
||||
// ljayic on X: gateway keys are managed through the API by the app's own
|
||||
// handlers, and what tells a secret is not served.
|
||||
func TestAdminAPIGatewayKeys(t *testing.T) {
|
||||
sandboxHome(t)
|
||||
w := adminDo(t, "POST", "/gateway-keys/add-key", `{"name":"Laptop"}`)
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
var added struct {
|
||||
Secret string
|
||||
Keys []access.Key
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &added); err != nil || added.Secret == "" || len(added.Keys) != 1 {
|
||||
t.Fatalf("add-key: %v %s", err, w.Body)
|
||||
}
|
||||
id := added.Keys[0].ID
|
||||
if w := adminDo(t, "POST", "/gateway-keys/rename-key", `{"key":"`+id+`","name":"Main"}`); w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
list := adminDo(t, "GET", "/gateway-keys", "")
|
||||
if list.Code != 200 || !strings.Contains(list.Body.String(), "Main") {
|
||||
t.Fatalf("list: %d %s", list.Code, list.Body)
|
||||
}
|
||||
if strings.Contains(list.Body.String(), added.Secret) {
|
||||
t.Fatal("the list tells a key's secret")
|
||||
}
|
||||
// what is left out is a 404, whatever the app has
|
||||
for _, c := range []struct{ method, path string }{
|
||||
{"POST", "/gateway-keys/copy-key"},
|
||||
{"POST", "/gateway-keys/admin-key"},
|
||||
{"POST", "/provider/key"},
|
||||
{"POST", "/provider/show"},
|
||||
{"POST", "/provider/restartapp"},
|
||||
{"GET", "/usage"},
|
||||
{"GET", "/caller-keys"},
|
||||
{"POST", "/api/provider/save"},
|
||||
} {
|
||||
if w := adminDo(t, c.method, c.path, `{"key":"`+id+`","admin":"any"}`); w.Code != http.StatusNotFound {
|
||||
t.Errorf("%s %s: %d, want 404", c.method, c.path, w.Code)
|
||||
}
|
||||
}
|
||||
// and a key can't be given the API through it
|
||||
if who, _ := access.Authenticate(added.Secret); who.Admin != "" {
|
||||
t.Errorf("the API gave a key Admin: %q", who.Admin)
|
||||
}
|
||||
if w := adminDo(t, "POST", "/gateway-keys/remove-key", `{"key":"`+id+`"}`); w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body)
|
||||
}
|
||||
if keys, _ := access.List(); len(keys) != 0 {
|
||||
t.Errorf("remove-key left %d keys", len(keys))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminAPIProviders(t *testing.T) {
|
||||
sandboxHome(t)
|
||||
const canary = "sk-canary-0123456789abcdef"
|
||||
w := adminDo(t, "POST", "/provider/save", `{"id":"relay","name":"Relay","chat":"https://relay.example/v1","key":"`+canary+`"}`)
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("save: %d %s", w.Code, w.Body)
|
||||
}
|
||||
list := adminDo(t, "GET", "/providers", "")
|
||||
if list.Code != 200 || !strings.Contains(list.Body.String(), "relay") {
|
||||
t.Fatalf("providers: %d %.300s", list.Code, list.Body)
|
||||
}
|
||||
if strings.Contains(list.Body.String(), canary) || strings.Contains(w.Body.String(), canary) {
|
||||
t.Fatal("a saved key is told")
|
||||
}
|
||||
if w := adminDo(t, "POST", "/provider/delete", `{"id":"relay"}`); w.Code != 200 {
|
||||
t.Fatalf("delete: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if list := adminDo(t, "GET", "/providers", ""); strings.Contains(list.Body.String(), `"id":"relay"`) {
|
||||
t.Error("delete left the provider")
|
||||
}
|
||||
}
|
||||
|
||||
// Signing in returns the vendor's page and the code, opens nothing, and
|
||||
// takes no password.
|
||||
func TestAdminAPISignInOpensNothing(t *testing.T) {
|
||||
sandboxHome(t)
|
||||
w := adminDo(t, "POST", "/signin", `{"agent":"no-such-agent"}`)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("unknown agent: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := adminDo(t, "POST", "/signin", `{`); w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("bad body: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// Every route the API serves is one the app has, so it can't list a
|
||||
// route that went away.
|
||||
func TestAdminRoutesEveryAPIRoute(t *testing.T) {
|
||||
sandboxHome(t)
|
||||
app := http.NewServeMux()
|
||||
providerRoutes(app, nil)
|
||||
callerKeyRoutes(app)
|
||||
for _, ar := range adminRoutes {
|
||||
method, path, _ := strings.Cut(ar.pattern, " ")
|
||||
to := path
|
||||
if ar.to != "" {
|
||||
to = ar.to
|
||||
}
|
||||
to = strings.NewReplacer("{action}", "x", "{id}", "x").Replace(to)
|
||||
r := httptest.NewRequest(method, "/api"+to, strings.NewReader("{}"))
|
||||
if _, pattern := app.Handler(r); pattern == "" {
|
||||
t.Errorf("%s: the app has no route /api%s", ar.pattern, to)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -137,6 +137,7 @@
|
||||
<a href="#models">使えるもの</a>
|
||||
<a href="#quotas">クォータと使用量</a>
|
||||
<a href="#keys">短期キー</a>
|
||||
<a href="#admin">管理 API</a>
|
||||
<a href="#oidc">GitHub Actions のキー</a>
|
||||
<a href="#api">統計 API</a>
|
||||
<a href="#trouble">うまくいかないとき</a>
|
||||
@@ -245,6 +246,21 @@ steps:
|
||||
</div>
|
||||
<p>キーはルールのゲートウェイキーの下で発行され、他の発行済みキーと同じくそのキーに縛られ、ルールの期間より長くは有効になりません。名前はリポジトリ、ブランチ、実行番号です。別のリポジトリやブランチのトークン、期限切れ、交換済みのトークンには理由付きの <code>401</code> が返ります。他のコンピューターから使えるのは magpie を共有している間だけで、断られたトークンは認証失敗の回数に数えられます。ルールがなければ何も交換されません。</p>
|
||||
|
||||
<h2 id="admin"><a class="anchor" href="#admin">管理 API</a></h2>
|
||||
<p>プロバイダー、アカウント、ゲートウェイキー、アカウントグループは、許可したキーがあれば設定ファイルを手で編集せずに管理できます。許可はコマンドラインで行います(API 経由ではできません。キーは自分以上の権限を別のキーに与えられません)。</p>
|
||||
<div class="code">
|
||||
<span class="lang">Shell</span>
|
||||
<button class="copy" data-copy="ex-admin">Copy</button>
|
||||
<pre id="ex-admin">magpie gateway-key add automation
|
||||
magpie gateway-key admin <id> local <span class="c"># このコンピューターのみ</span>
|
||||
magpie gateway-key admin <id> any <span class="c"># ほかのコンピューターからも</span>
|
||||
curl -s http://127.0.0.1:3425/v1/magpie/admin/providers -H "Authorization: Bearer $KEY"
|
||||
curl -s -X POST http://127.0.0.1:3425/v1/magpie/admin/gateway-keys/add-key \
|
||||
-H "Authorization: Bearer $KEY" -d '{"name":"ci"}'</pre>
|
||||
</div>
|
||||
<p>アプリ自身のページと同じ処理が <code>/v1/magpie/admin/</code> の下にあります。<code>GET providers</code>、<code>POST provider/{save,delete,on,off,name,…}</code>、<code>POST keys/…</code>(プロバイダーのキー)、<code>GET</code>/<code>POST gateway-keys[/{add-key,rename-key,limit-key,models-key,remove-key,…}]</code>、<code>GET</code>/<code>POST account-groups[/…]</code>、そして <code>POST signin</code>(<code>{"agent":…}</code>)は、ベンダーのページと入力するコードを返し、パスワードは受け取りません。ブラウザーのあるコンピューターで開いてください。保存済みのキーとゲートウェイキーの秘密は再び返されず、このコンピューターのほかのアプリを変更する操作も提供しません。</p>
|
||||
<p>読み取り専用キー、拡張機能のキー、発行されたキーや短期キー、共有キーは使えません。キーの有無にかかわらず Web ページからは呼べません(<code>Origin</code> や <code>Sec-Fetch-*</code> を持つリクエストはすべて拒否)。このコンピューターの別名で届いたリクエストも拒否されます。ネットワーク越しに共有している場合、<code>any</code> のキーだけが通ります。</p>
|
||||
|
||||
<h2 id="api"><a class="anchor" href="#api">統計 API</a></h2>
|
||||
<p>使用量ページの内容は JSON でも、このコンピューターに、また magpie を共有している間はゲートウェイキー付きのリクエストに提供されます。予算、モデル、アカウントで制限されたキーには、自分のリクエストと上限だけが返ります。持ち主がそのキーの<span class="ui">残量</span>をオンにすると(<code>magpie gateway-key quotas <id> on</code>)、使えるもののクォータも返ります。</p>
|
||||
<ul>
|
||||
|
||||
@@ -137,6 +137,7 @@
|
||||
<a href="#models">What you get</a>
|
||||
<a href="#quotas">Quotas and usage</a>
|
||||
<a href="#keys">Short-lived keys</a>
|
||||
<a href="#admin">Management API</a>
|
||||
<a href="#oidc">Keys for GitHub Actions</a>
|
||||
<a href="#api">Stats API</a>
|
||||
<a href="#trouble">When it doesn’t work</a>
|
||||
@@ -245,6 +246,21 @@ steps:
|
||||
</div>
|
||||
<p>The key is issued under the rule’s gateway key and held to it like any other issued key, lives no longer than the rule says, and is named after the repository, branch and run. A token from another repository or branch, an expired one, or one already traded gets <code>401</code> and why. The route answers another computer only while magpie is shared, and refused tokens count against the failed sign-ins it allows. Without a rule nothing is traded.</p>
|
||||
|
||||
<h2 id="admin"><a class="anchor" href="#admin">Management API</a></h2>
|
||||
<p>Providers, accounts, gateway keys and account groups can be managed with no hand-edited file, by a key you allow to. Allow it from the command line (not through the API: a key can't give another more than it has):</p>
|
||||
<div class="code">
|
||||
<span class="lang">Shell</span>
|
||||
<button class="copy" data-copy="ex-admin">Copy</button>
|
||||
<pre id="ex-admin">magpie gateway-key add automation
|
||||
magpie gateway-key admin <id> local <span class="c"># this computer only</span>
|
||||
magpie gateway-key admin <id> any <span class="c"># also from other computers</span>
|
||||
curl -s http://127.0.0.1:3425/v1/magpie/admin/providers -H "Authorization: Bearer $KEY"
|
||||
curl -s -X POST http://127.0.0.1:3425/v1/magpie/admin/gateway-keys/add-key \
|
||||
-H "Authorization: Bearer $KEY" -d '{"name":"ci"}'</pre>
|
||||
</div>
|
||||
<p>It answers the same as the app’s own pages do, under <code>/v1/magpie/admin/</code>: <code>GET providers</code>, <code>POST provider/{save,delete,on,off,name,…}</code>, <code>POST keys/…</code> (a provider’s keys), <code>GET</code>/<code>POST gateway-keys[/{add-key,rename-key,limit-key,models-key,remove-key,…}]</code>, <code>GET</code>/<code>POST account-groups[/…]</code>, and <code>POST signin</code> with <code>{"agent":…}</code>, which answers the vendor’s page and the code to type there, never a password; open it on a computer with a browser. A saved key and a gateway key’s secret are never told again, and what changes this computer’s apps is not served.</p>
|
||||
<p>A key that is read-only, the extension’s, issued or short-lived, or the sharing key, can’t have it. A web page can’t call it, with a key or without (any request with <code>Origin</code> or <code>Sec-Fetch-*</code> is refused), and nor can a request under another name for this computer. Shared over the network, only a key set to <code>any</code> gets in.</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, and the quotas of what it may use once its owner turns on <span class="ui">Quotas</span> for it (<code>magpie gateway-key quotas <id> on</code>).</p>
|
||||
<ul>
|
||||
|
||||
@@ -137,6 +137,7 @@
|
||||
<a href="#models">能用到什么</a>
|
||||
<a href="#quotas">额度与用量</a>
|
||||
<a href="#keys">短期密钥</a>
|
||||
<a href="#admin">管理 API</a>
|
||||
<a href="#oidc">GitHub Actions 的密钥</a>
|
||||
<a href="#api">统计 API</a>
|
||||
<a href="#trouble">出问题时</a>
|
||||
@@ -245,6 +246,21 @@ steps:
|
||||
</div>
|
||||
<p>换到的密钥由规则里的网关密钥签发,和其他签发的密钥一样受它约束,有效期不超过规则所写,名字是仓库、分支和运行编号。其他仓库或分支的 token、过期的 token、已经换过的 token 会收到 <code>401</code> 和原因。只有 magpie 共享时其他电脑才能调用这个接口,被拒的 token 计入失败认证次数。没有规则就什么都换不到。</p>
|
||||
|
||||
<h2 id="admin"><a class="anchor" href="#admin">管理 API</a></h2>
|
||||
<p>提供商、账号、网关密钥和账号组都可以不改任何配置文件来管理,用你允许的密钥即可。在命令行里允许(不能通过 API:密钥给不了别的密钥比自己更多的权限):</p>
|
||||
<div class="code">
|
||||
<span class="lang">Shell</span>
|
||||
<button class="copy" data-copy="ex-admin">Copy</button>
|
||||
<pre id="ex-admin">magpie gateway-key add automation
|
||||
magpie gateway-key admin <id> local <span class="c"># 只限这台电脑</span>
|
||||
magpie gateway-key admin <id> any <span class="c"># 其他电脑也可以</span>
|
||||
curl -s http://127.0.0.1:3425/v1/magpie/admin/providers -H "Authorization: Bearer $KEY"
|
||||
curl -s -X POST http://127.0.0.1:3425/v1/magpie/admin/gateway-keys/add-key \
|
||||
-H "Authorization: Bearer $KEY" -d '{"name":"ci"}'</pre>
|
||||
</div>
|
||||
<p>它和应用自己的页面答得一样,路径在 <code>/v1/magpie/admin/</code> 下:<code>GET providers</code>、<code>POST provider/{save,delete,on,off,name,…}</code>、<code>POST keys/…</code>(提供商的密钥)、<code>GET</code>/<code>POST gateway-keys[/{add-key,rename-key,limit-key,models-key,remove-key,…}]</code>、<code>GET</code>/<code>POST account-groups[/…]</code>,以及 <code>POST signin</code>(<code>{"agent":…}</code>),它返回厂商的网页和要输入的代码,从不收密码;请在有浏览器的电脑上打开。已保存的密钥和网关密钥的明文不会再被告知,会改动这台电脑上其他应用的操作也不提供。</p>
|
||||
<p>只读密钥、浏览器扩展的密钥、签发的或短期的密钥以及共享密钥,都不能拥有它。网页不能调用它,带不带密钥都一样(带 <code>Origin</code> 或 <code>Sec-Fetch-*</code> 的请求一律拒绝),用别的名字指向本机的请求也不行。通过网络共享时,只有设为 <code>any</code> 的密钥能进来。</p>
|
||||
|
||||
<h2 id="api"><a class="anchor" href="#api">统计 API</a></h2>
|
||||
<p>用量页上的内容也以 JSON 提供给本机;共享 magpie 时,也提供给带网关密钥的请求。受预算、模型或账号限制的密钥只能看到自己的请求和限额;主人为它打开<span class="ui">额度</span>后(<code>magpie gateway-key quotas <id> on</code>),还能看到它可用部分的额度。</p>
|
||||
<ul>
|
||||
|
||||
Reference in New Issue
Block a user