From c84c3e1c0359c7e27b6070a522bb673fddd70032 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 30 Oct 2026 22:51:23 +0800 Subject: [PATCH] gateway: a key's holder sees its own usage and setup at /me zytszone on X runs one magpie's gateway for a whole department, whose people can't be given the admin's app. Each now opens the gateway's /me at the address they reach it at, types the gateway key they were given, and sees that key's own name, limits and what is spent of them, its usage over today, 7 and 30 days with its most used models, the models it may use, and copy-ready setup for Claude Code (settings.json env), Codex (config.toml provider, /v1, responses), any OpenAI-compatible client and a curl test. The base URL is the address the page was opened at, never 127.0.0.1; the key is a placeholder until "Put my key in the setup" is ticked. Strings in en, zh, zh-TW, ja and de. - GET /me (keypage.html, embedded) is the same bytes for everyone and holds no data, so lanGuard serves exactly GET/HEAD /me (no escaped path) to another machine without a key, after the allow list, the rebinding check and the not-shared 403, which still apply. Its CSP loads nothing from elsewhere, posts no form and forbids framing. - GET /v1/magpie/me (keyInfo) answers access.Caller's own key only. No key, a wrong one, one turned off and magpie's own token are 401 alike; ?key= is refused 400 so a key never sits in an address or a log. It names no account, other key, provider or secret; its models are /v1/models' for that key (keyAllowed), none for a read-only key. The page sends the key as Authorization to its own origin with credentials omitted and keeps it in sessionStorage only. - Both are in readOnlyRoutes, /me in clientPrefixes (magpie web's page port), and Gateway -> Gateway keys shows the page's address (MAGPIE_PUBLIC_URL, else the LAN address offered) with a Copy, while shared and with a key. Docs: gateway-routing.md, reference.md. Run: - mote: go build -tags nogui ./...; go vet -tags nogui gateway+gui; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway; go test -tags nogui -count=1 ./internal/gateway ./internal/gui: ok (gateway 732s). gofmt -l clean. Rebased onto 18b63fe5f after that; there: build, vet, and the KeyPage, read-only, client path, page port, LAN guard, caller usage and core script budget tests ok. - Key page Go tests, through the real lanGuard(Handler()) chain, from the network and from loopback: the key sees its own name, usage, top model, limits and allowed models and nothing of Bob, Bob's secret, the upstream key or magpie's token; no key, wrong key, turned-off key (Bearer and x-api-key), magpie's Token, ?key=, Origin null, an evil.localhost page, a foreign origin with a good key and a rebound Host all get nothing; the page opens without a key, not on POST, /me/x or /%6De, and not while unshared; a read-only key gets no models. - GUI, key-page.test.cjs: Chromium on mote and WebKit on the Linux box (magpie-desktop), 390px, all five languages, 24 of 24; i18n-keys ok. The 46 Gateway/caller-key GUI files and i18n-keys on the Linux box, both engines: 645 pass, 11 red at concurrency 4. Serially 6 stay red, and the same tests are red on origin/main a0cb8b646 there: api-key-theme "system", gateway-key-limit webkit en/zh, connect-snippet-shell, gateway-key-models (#4120), phone-rows (#4218). Broken by hand, each red then restored: lanGuard's /me exemption removed (page 401); the KeyID check removed (no key/wrong/off/Token got data); keyAllowed dropped (Alice saw plan/m2); the RawPath check dropped (/%6De served); the ?key refusal dropped (200 with Alice's data). Not tried: a real Claude Code or Codex pointed at a shared gateway with the page's snippets; WebKit on macOS (every WebKit launch on mote hangs right now, for every session, a bare launch included); the whole GUI suite and a full go test ./... (one suite per machine; mote is running other sessions' suites). --- docs/reference.md | 8 + docs/subsystems/gateway-routing.md | 31 +- internal/gateway/gateway.go | 2 + internal/gateway/key_page.go | 131 ++++++ internal/gateway/key_page_test.go | 253 ++++++++++ internal/gateway/keypage.html | 496 ++++++++++++++++++++ internal/gateway/lan.go | 6 + internal/gateway/oneport.go | 3 + internal/gateway/readonly.go | 2 + internal/gui/assets/i18n.js | 8 + internal/gui/assets/plugins/gateway/keys.js | 16 + internal/gui/tests/README.md | 12 + internal/gui/tests/key-page.test.cjs | 176 +++++++ 13 files changed, 1142 insertions(+), 2 deletions(-) create mode 100644 internal/gateway/key_page.go create mode 100644 internal/gateway/key_page_test.go create mode 100644 internal/gateway/keypage.html create mode 100644 internal/gui/tests/key-page.test.cjs diff --git a/docs/reference.md b/docs/reference.md index f126f1d94..9890b708a 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -686,6 +686,14 @@ Usage page this way (#1547). Requests from this computer that send no gateway key are not limited; a gateway key used from this computer is. +A key's holder can also open **`/me`** in a browser at the address they +reach the gateway at (for example `http://192.168.1.10:3999/me`), type +their key, and see its own limits, its usage over today, 7 and 30 days, the +models it may use, and copy-ready setup for Claude Code, Codex and any +OpenAI-compatible client. It shows nothing of other keys, accounts or +providers. Gateway → Gateway keys shows that address with a Copy button, +so it can be handed out with the keys. + A gateway key can also be held to some **models** (#882): pick them with the **All models** badge on the key's row, or run `magpie gateway-key models openai/gpt-5 anthropic/*` (`all` takes the restriction off). A pattern is diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index c6d01e795..be9cbc0a7 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -425,8 +425,8 @@ after `callerGuard`, so the key is known from loopback and from elsewhere, and before `withCaller` and `keyLimited`, so nothing is read, reserved or sent first. It judges the pattern `ServeMux.Handler` routes the request to against `readOnlyRoutes` (`GET /`, `/v1`, the quotas, their history and -cards, the usage summary and its requests, the key's limit and the -concurrency) and refuses every other with 403 `gateway_key_read_only`: +cards, the usage summary and its requests, the key's limit, the key +page and its data, and the concurrency) and refuses every other with 403 `gateway_key_read_only`: every model route, `count_tokens`, the Responses WebSocket's upgrade, every MCP server, Codex's and Gemini's backends, the catch-all and every write (`POST /v1/magpie/usage/requests`, the quotas' refresh). A route added later @@ -466,6 +466,33 @@ with it off, a key held to a limit gets 503 and nothing is sent. A local magpie asks it with each of its remote-magpie keys for that key's card on its Usage page (#1547), a window per limit's cap. +`GET /me` is the key page: a gateway key's holder opens it in a browser at +the address they reach the gateway at, types their key, and sees that key's +own name, limits, usage (today, 7 and 30 days, its most used models) and +the models it may use, with the setup for Claude Code, Codex and an +OpenAI-compatible client whose base URL is the address the page was opened +at (zytszone on X: a department shares one magpie, whose app its people +can't be given). The page itself (`keypage.html`, embedded) is the same +bytes for everyone and holds no data, so `lanGuard` serves exactly `GET` +or `HEAD /me` (`keyPageOpen`: no escaped path) to another machine without a +key, after the allow list, the rebinding check and the not-shared refusal, +which still apply. Its data is `GET /v1/magpie/me` (`keyInfo`), which takes +the key as every route does (`Authorization` or `x-api-key`) and answers +only `access.Caller`'s own: no key, a wrong one, one turned off and +magpie's own token are 401 alike, and `?key=` is refused 400, so a key is +never written into an address or a log. It names no account, no other key, +no provider and no secret; its models are `/v1/models`' for that key +(`keyAllowed`), none for a read-only key. The page loads nothing from +elsewhere, posts no form and can't be framed (its CSP), keeps the key in +the tab's `sessionStorage` only, and sends it to its own origin with +`credentials: "omit"`. Gateway → Gateway keys shows the page's address +(`MAGPIE_PUBLIC_URL`, else the LAN address offered) with a Copy, while +shared and with a key (`gatewayKeyPage` in `keys.js`). `key_page.go`, and +`TestKeyPageTellsAKeyItsOwn`, `TestKeyPageRefusesWithoutItsKey` and +`TestKeyPageOpensWithoutAKey` in +[`key_page_test.go`](../../internal/gateway/key_page_test.go); +`internal/gui/tests/key-page.test.cjs` drives the page itself. + System One uses `RouteDecider` and `postDecide` in [`decide.go`](../../internal/gateway/decide.go), taking one provider prefix off at each hop and preserving the state, questions and vendor errors. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 8b809f638..87df60506 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -807,6 +807,8 @@ 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) + mux.HandleFunc("GET "+KeyPagePath, s.keyPage) + mux.HandleFunc("GET "+keyPageData, s.keyInfo) // the Claude Code processes the Claude subscription runs, for magpie // claude-code runs (loopback only) mux.HandleFunc("GET "+ClaudeRunsPath, s.claudeRuns) diff --git a/internal/gateway/key_page.go b/internal/gateway/key_page.go new file mode 100644 index 000000000..dfa8d9c53 --- /dev/null +++ b/internal/gateway/key_page.go @@ -0,0 +1,131 @@ +package gateway + +import ( + _ "embed" + "net/http" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/budget" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/usage" +) + +// KeyPagePath is the page a gateway key's holder opens in a browser at the +// address they reach the gateway at (zytszone on X: magpie shared with a +// whole department, whose people can't be given the admin's app). It asks +// for their key and shows, from keyInfo, that key's own name, limits, +// usage and models, and the setup to paste into Claude Code, Codex or an +// OpenAI-compatible client, with the address it was opened at as the base +// URL. +const KeyPagePath = "/me" + +// keyPageData is the key page's own route. +const keyPageData = "/v1/magpie/me" + +//go:embed keypage.html +var keyPageHTML []byte + +// keyPageOpen: r asks for the key page itself, which lanGuard serves to +// another machine without a key while magpie is shared: it is the same +// bytes for everyone and has no data in it. Its data (keyInfo) needs the +// key as every other route does. +func keyPageOpen(r *http.Request) bool { + return r.URL.Path == KeyPagePath && r.URL.RawPath == "" && (r.Method == http.MethodGet || r.Method == http.MethodHead) +} + +// keyPage serves the key page. It loads nothing from anywhere else, posts +// nothing and can't be framed, so a page that tricks a holder into +// opening it can't read or steer what they type into it. +func (s *Server) keyPage(w http.ResponseWriter, r *http.Request) { + h := w.Header() + h.Set("Content-Type", "text/html; charset=utf-8") + h.Set("Content-Security-Policy", "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'") + h.Set("X-Frame-Options", "DENY") + h.Set("X-Content-Type-Options", "nosniff") + h.Set("Referrer-Policy", "no-referrer") + h.Set("Cache-Control", "no-cache") + w.Write(keyPageHTML) +} + +// keyPageUsage are the periods the key page sums its key's calls over. +var keyPageUsage = []usage.Period{usage.Today, usage.Week, usage.Month} + +// keyInfo is what the calling gateway key may know of itself, for the key +// page: its name, its limits and what it has spent of them, its calls +// over today, 7 and 30 days and the models it called most, and the models +// it may use. Nothing in it is another key's, an account's, a provider's +// key or the admin's: no account names, no other key, no secret (the +// holder typed theirs). No key, a wrong one, one turned off and magpie's +// own token (which is no gateway key) are answered 401 alike. +func (s *Server) keyInfo(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if r.URL.Query().Has("key") { + writeError(w, provider.Chat, http.StatusBadRequest, "send the gateway key as Authorization: Bearer or x-api-key, never in the address") + return + } + who := access.Caller(r.Context()) + if who.KeyID == "" || who.KeyID == usage.NoCallerKey { + writeError(w, provider.Chat, http.StatusUnauthorized, "send an enabled gateway key as Authorization: Bearer or x-api-key") + return + } + limits := budget.All(access.Key{ID: who.KeyID, Name: who.KeyName, Limit: who.Limit, More: who.More}, limitClock()) + if limits == nil { + limits = []budget.Status{} + } + sums := map[string]keyPageTotals{} + // the models it called most, as their vendors name them + top := []keyPageModel{} + for _, p := range keyPageUsage { + page := usage.QueryPage(p, usage.Filter{CallerKey: who.KeyID}, 0, 1) + sums[string(p)] = keyPageSum(page.Sum) + if p != usage.Month { + continue + } + for _, sh := range page.By["model"] { + if len(top) < 8 { + top = append(top, keyPageModel{ID: sh.ID, keyPageTotals: keyPageSum(sh.Totals)}) + } + } + } + models := []map[string]string{} + // a read-only key is refused every model (readOnlyGuard) + if !who.ReadOnly { + // as /v1/models tells this key, for no agent in particular + shown, _ := provider.CatalogFor("") + shown = keyAllowed(r, shown) + labels := provider.Labels(shown) + for i, e := range shown { + models = append(models, map[string]string{"id": e.ID, "label": labels[i]}) + } + } + writeJSON(w, 200, map[string]any{ + "name": who.KeyName, + "readOnly": who.ReadOnly, + "limits": limits, + "usage": sums, + "topModels": top, + "models": models, + "version": Version, + }) +} + +// keyPageTotals are the sums the key page shows of a key's calls. +type keyPageTotals struct { + Calls int `json:"calls"` + Errors int `json:"errors"` + Input int `json:"input"` + Output int `json:"output"` + CacheRead int `json:"cache_read"` + CacheWrite int `json:"cache_write"` + Cost float64 `json:"cost"` + Unpriced int `json:"unpriced"` +} + +type keyPageModel struct { + ID string `json:"id"` + keyPageTotals +} + +func keyPageSum(t usage.Totals) keyPageTotals { + return keyPageTotals{Calls: t.Calls, Errors: t.Errors, Input: t.Input, Output: t.Output, CacheRead: t.CacheRead, CacheWrite: t.CacheWrite, Cost: t.Cost, Unpriced: t.Unpriced} +} diff --git a/internal/gateway/key_page_test.go b/internal/gateway/key_page_test.go new file mode 100644 index 000000000..2767fda27 --- /dev/null +++ b/internal/gateway/key_page_test.go @@ -0,0 +1,253 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/budget" + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// keyPageGateway is a shared gateway with a plan of two models and two +// keys, each with calls of its own: "Alice" held to plan/m1 and called +// once, "Bob" held to a daily token limit and called twice. +func keyPageGateway(t *testing.T) (http.Handler, []access.Key, []string) { + t.Helper() + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + budget.Forget() + pinLimitClock(t) + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":30,"completion_tokens":5}}`) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1", "m2"}}); err != nil { + t.Fatal(err) + } + keys, secrets := newCaller(t, "Alice", "Bob") + if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: []string{"plan/m1"}}); err != nil { + t.Fatal(err) + } + setLimit(t, keys[1].ID, &access.Limit{Period: "day", Tokens: 1000}) + h := lanGuard(New().Handler()) + for _, secret := range []string{secrets[0], secrets[1], secrets[1]} { + r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq)) + r.RemoteAddr = "192.168.1.9:5000" + r.Header.Set("Authorization", "Bearer "+secret) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != 200 { + t.Fatal("call", w.Code, w.Body.String()) + } + } + return h, keys, secrets +} + +type keyPageReq struct { + method, path, from, host string + header map[string]string +} + +func (q keyPageReq) do(h http.Handler) *httptest.ResponseRecorder { + r := httptest.NewRequest(q.method, q.path, nil) + r.RemoteAddr = q.from + if q.host != "" { + r.Host = q.host + } + for k, v := range q.header { + r.Header.Set(k, v) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +type keyPageInfo struct { + Name string `json:"name"` + ReadOnly bool `json:"readOnly"` + Limits []budget.Status `json:"limits"` + Usage map[string]keyPageTotals `json:"usage"` + TopModels []keyPageModel `json:"topModels"` + Models []struct{ ID, Label string } +} + +// zytszone on X: a department's people each have a gateway key and can't +// be given the admin's app. The key page's data tells a key what is its +// own: its name, limits, calls and models, from another machine, and +// nothing of the other key, the provider's key or either secret. +func TestKeyPageTellsAKeyItsOwn(t *testing.T) { + h, keys, secrets := keyPageGateway(t) + for i, secret := range secrets { + w := keyPageReq{method: "GET", path: keyPageData, from: "192.168.1.9:5000", header: map[string]string{"Authorization": "Bearer " + secret}}.do(h) + if w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + if cc := w.Header().Get("Cache-Control"); cc != "no-store" { + t.Error("Cache-Control", cc) + } + body := w.Body.String() + other := 1 - i + for _, leak := range []string{keys[other].Name, keys[other].ID, secrets[other], secret, "upstream-secret", Token} { + if strings.Contains(body, leak) { + t.Errorf("key %s is told %q: %s", keys[i].Name, leak, body) + } + } + var got keyPageInfo + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got.Name != keys[i].Name || got.ReadOnly { + t.Errorf("name %q readOnly %v", got.Name, got.ReadOnly) + } + calls := []int{1, 2}[i] + for _, p := range []string{"today", "7d", "30d"} { + if u := got.Usage[p]; u.Calls != calls || u.Input != 30*calls || u.Output != 5*calls { + t.Errorf("%s: %s usage %+v", keys[i].Name, p, u) + } + } + if len(got.TopModels) != 1 || got.TopModels[0].ID != "m1" || got.TopModels[0].Calls != calls { + t.Errorf("%s: top models %+v", keys[i].Name, got.TopModels) + } + var ids []string + for _, m := range got.Models { + ids = append(ids, m.ID) + } + if want := []string{"plan/m1", "plan/m1,plan/m2"}[i]; strings.Join(ids, ",") != want { + t.Errorf("%s: models %v, want %s", keys[i].Name, ids, want) + } + if i == 0 && len(got.Limits) != 0 { + t.Errorf("Alice has no limit: %+v", got.Limits) + } + if i == 1 && (len(got.Limits) != 1 || got.Limits[0].TokenLimit != 1000 || got.Limits[0].Tokens != 70) { + t.Errorf("Bob's limit: %+v", got.Limits) + } + } +} + +// No key, a wrong one, one turned off or removed, magpie's own token and +// a key in the address are all told nothing, from another machine and +// from this one; and a page from elsewhere (Origin null, a *.localhost +// name, another site, a rebound name) is refused as on every route. +func TestKeyPageRefusesWithoutItsKey(t *testing.T) { + h, keys, secrets := keyPageGateway(t) + if _, err := access.Update("off-key", access.Change{Key: keys[1].ID}); err != nil { + t.Fatal(err) + } + remote, here := "192.168.1.9:5000", "127.0.0.1:5000" + bearer := func(k string) map[string]string { return map[string]string{"Authorization": "Bearer " + k} } + for _, c := range []struct { + name string + q keyPageReq + want int + }{ + {"no key", keyPageReq{from: remote}, 401}, + {"wrong key", keyPageReq{from: remote, header: bearer("sk-magpie-not-a-key")}, 401}, + {"turned off", keyPageReq{from: remote, header: bearer(secrets[1])}, 401}, + {"turned off, x-api-key", keyPageReq{from: remote, header: map[string]string{"x-api-key": secrets[1]}}, 401}, + {"key in the address", keyPageReq{from: remote, path: keyPageData + "?key=" + secrets[0]}, 400}, + {"here, no key", keyPageReq{from: here}, 401}, + {"here, wrong key", keyPageReq{from: here, header: bearer("sk-magpie-not-a-key")}, 401}, + {"here, turned off", keyPageReq{from: here, header: bearer(secrets[1])}, 401}, + {"here, magpie's token", keyPageReq{from: here, header: bearer(Token)}, 401}, + {"here, key in the address", keyPageReq{from: here, path: keyPageData + "?key=" + secrets[0]}, 400}, + {"Origin null", keyPageReq{from: here, header: map[string]string{"Origin": "null"}}, 403}, + {"a localhost subdomain", keyPageReq{from: here, header: map[string]string{"Origin": "http://evil.localhost"}}, 403}, + {"another site, with the key", keyPageReq{from: here, header: map[string]string{"Origin": "https://evil.example", "Authorization": "Bearer " + secrets[0]}}, 403}, + {"another site, remote, with the key", keyPageReq{from: remote, header: map[string]string{"Origin": "https://evil.example", "Authorization": "Bearer " + secrets[0]}}, 403}, + {"rebound name", keyPageReq{from: here, host: "evil.example:3425", header: map[string]string{"Sec-Fetch-Site": "same-origin"}}, 403}, + {"remote, Origin null, no key", keyPageReq{from: remote, header: map[string]string{"Origin": "null"}}, 401}, + } { + c.q.method = "GET" + if c.q.path == "" { + c.q.path = keyPageData + } + w := c.q.do(h) + if w.Code != c.want { + t.Errorf("%s: %d, want %d: %s", c.name, w.Code, c.want, w.Body.String()) + } + for _, k := range keys { + if strings.Contains(w.Body.String(), k.Name) || strings.Contains(w.Body.String(), k.ID) { + t.Errorf("%s: told %s: %s", c.name, k.Name, w.Body.String()) + } + } + } + // and the key that works still does + if w := (keyPageReq{method: "GET", path: keyPageData, from: remote, header: bearer(secrets[0])}).do(h); w.Code != 200 { + t.Fatal("Alice", w.Code) + } +} + +// The page itself is opened before its key is typed: from another machine +// without a key while magpie is shared, never framed, loading nothing +// from elsewhere and never sending the key in an address. Not shared, it +// isn't answered at all; a rebound name is refused it here. +func TestKeyPageOpensWithoutAKey(t *testing.T) { + h, _, _ := keyPageGateway(t) + w := keyPageReq{method: "GET", path: KeyPagePath, from: "192.168.1.9:5000", header: map[string]string{"User-Agent": "Mozilla/5.0"}}.do(h) + if w.Code != 200 || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/html") { + t.Fatal(w.Code, w.Header()) + } + csp := w.Header().Get("Content-Security-Policy") + for _, want := range []string{"default-src 'none'", "connect-src 'self'", "frame-ancestors 'none'", "form-action 'none'"} { + if !strings.Contains(csp, want) { + t.Errorf("CSP %q lacks %q", csp, want) + } + } + if w.Header().Get("X-Frame-Options") != "DENY" || w.Header().Get("Referrer-Policy") != "no-referrer" { + t.Error(w.Header()) + } + page := w.Body.String() + if strings.Contains(page, "?key=") || strings.Contains(page, "&key=") || !strings.Contains(page, `Authorization: "Bearer " + k`) { + t.Error("the page sends its key some other way than the Authorization header") + } + // a path that isn't the page's exactly, and any other method, needs + // the key as every other route does + for _, q := range []keyPageReq{{method: "POST", path: KeyPagePath}, {method: "GET", path: KeyPagePath + "/x"}, {method: "GET", path: "/%6De"}} { + q.from = "192.168.1.9:5000" + if w := q.do(h); w.Code != 401 { + t.Errorf("%s %s: %d", q.method, q.path, w.Code) + } + } + if w := (keyPageReq{method: "GET", path: KeyPagePath, from: "127.0.0.1:5000", host: "evil.example:3425", header: map[string]string{"User-Agent": "Mozilla/5.0"}}).do(h); w.Code != 403 { + t.Error("rebound", w.Code) + } + s := settings.Load() + s.LAN = false + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if w := (keyPageReq{method: "GET", path: KeyPagePath, from: "192.168.1.9:5000"}).do(h); w.Code != 403 { + t.Error("not shared", w.Code) + } + if w := (keyPageReq{method: "GET", path: KeyPagePath, from: "127.0.0.1:5000"}).do(h); w.Code != 200 { + t.Error("here", w.Code) + } +} + +// A read-only key opens the page and reads its own usage, and is told +// no models, as it may call none. +func TestKeyPageReadOnlyKey(t *testing.T) { + h, keys, secrets := keyPageGateway(t) + if _, err := access.Update("access-key", access.Change{Key: keys[0].ID, ReadOnly: true}); err != nil { + t.Fatal(err) + } + bearer := map[string]string{"Authorization": "Bearer " + secrets[0]} + if w := (keyPageReq{method: "GET", path: KeyPagePath, from: "192.168.1.9:5000", header: bearer}).do(h); w.Code != 200 { + t.Fatal("page", w.Code, w.Body.String()) + } + w := keyPageReq{method: "GET", path: keyPageData, from: "192.168.1.9:5000", header: bearer}.do(h) + var got keyPageInfo + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &got) != nil { + t.Fatal(w.Code, w.Body.String()) + } + if !got.ReadOnly || len(got.Models) != 0 || got.Usage["30d"].Calls != 1 { + t.Fatalf("%+v", got) + } +} diff --git a/internal/gateway/keypage.html b/internal/gateway/keypage.html new file mode 100644 index 000000000..4c169a490 --- /dev/null +++ b/internal/gateway/keypage.html @@ -0,0 +1,496 @@ + + + + + + +magpie key + + + +
+
+

Your gateway key

+

Enter the gateway key you were given to see what it has used, what it may use and how to set up your agents.

+
+ +
+ + +
+ +

The key stays in this tab and is sent to this gateway alone.

+
+
+ + +
+ + + diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index dec0aa5ea..9086ea8a7 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -367,6 +367,12 @@ func lanGuard(next http.Handler) http.Handler { http.Error(w, "magpie isn't shared on the local network", http.StatusForbidden) return } + // the key page itself is the same bytes for everyone, so it is + // opened before the key it asks for is typed; its data isn't + if remote && keyPageOpen(r) { + next.ServeHTTP(w, r) + return + } if remote || managedKey(r) { var ok bool r, ok = identifyCaller(w, r) diff --git a/internal/gateway/oneport.go b/internal/gateway/oneport.go index 6cf480d41..bc5b481fc 100644 --- a/internal/gateway/oneport.go +++ b/internal/gateway/oneport.go @@ -28,6 +28,9 @@ var clientPrefixes = []string{ "/models", "/chat/completions", "/responses", "/messages", "/images", "/embeddings", "/rerank", "/audio", "/videos", "/muse-code/models", CodexPath, AlphaSearchPath, "/mcp", + // the key page (KeyPagePath): a key's holder opens it at the address + // they give their agents + KeyPagePath, } // ClientPath: p is one of the gateway's client routes, which `magpie web` diff --git a/internal/gateway/readonly.go b/internal/gateway/readonly.go index 5d2dcde48..b2078053c 100644 --- a/internal/gateway/readonly.go +++ b/internal/gateway/readonly.go @@ -34,6 +34,8 @@ var readOnlyRoutes = map[string]bool{ "GET /v1/magpie/usage/requests": true, "GET /v1/magpie/limit": true, "GET /v1/magpie/concurrency": true, + "GET " + KeyPagePath: true, + "GET " + keyPageData: true, } // ReadOnlyCode is the error code a read-only key is refused a route with. diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 46199eeac..d0b1c01f3 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -444,6 +444,8 @@ const I18N = { "Gateway key rotated. Update clients on other computers.": "网关密钥已轮换,请更新其他电脑上的客户端。", "Add gateway key": "添加网关密钥", "Create a gateway key for each client. Usage is counted separately for each key.": "为每个客户端创建一个网关密钥,分别统计用量。", + "Key holders see their usage and setup at": "密钥持有人可在此查看自己的用量和配置方法:", + "Key page": "密钥页面", "Gateway keys are for other computers, and for a tunnel to this one such as Cloudflare Tunnel: they are added here once Share on local network is on. Agents on this computer need none.": "网关密钥给其他电脑用,也给连到这台电脑的隧道(如 Cloudflare Tunnel)用:打开「局域网共享」后在这里添加。这台电脑上的 Agent 不需要密钥。", "Gateway key name": "网关密钥名称", "Key name, e.g. Laptop": "密钥名称,例如笔记本", @@ -4645,6 +4647,8 @@ const I18N = { "Gateway key rotated. Update clients on other computers.": "閘道金鑰已輪換,請更新其他電腦上的用戶端。", "Add gateway key": "新增閘道金鑰", "Create a gateway key for each client. Usage is counted separately for each key.": "為每個用戶端建立一個閘道金鑰,分別統計用量。", + "Key holders see their usage and setup at": "金鑰持有人可在此查看自己的用量和設定方法:", + "Key page": "金鑰頁面", "Gateway keys are for other computers, and for a tunnel to this one such as Cloudflare Tunnel: they are added here once Share on local network is on. Agents on this computer need none.": "閘道金鑰給其他電腦用,也給連到這臺電腦的通道(如 Cloudflare Tunnel)用:開啟「區域網共享」後在這裡新增。這臺電腦上的 Agent 不需要金鑰。", "Gateway key name": "閘道金鑰名稱", "Key name, e.g. Laptop": "金鑰名稱,例如筆記本", @@ -8808,6 +8812,8 @@ const I18N = { "Gateway key rotated. Update clients on other computers.": "ゲートウェイキーを更新しました。他のコンピュータのクライアントを更新してください。", "Add gateway key": "ゲートウェイキーを追加", "Create a gateway key for each client. Usage is counted separately for each key.": "クライアントごとにゲートウェイキーを作成してください。使用量はキーごとに集計されます。", + "Key holders see their usage and setup at": "キーの持ち主はここで自分の使用量と設定方法を確認できます:", + "Key page": "キーのページ", "Gateway keys are for other computers, and for a tunnel to this one such as Cloudflare Tunnel: they are added here once Share on local network is on. Agents on this computer need none.": "ゲートウェイキーは他のコンピュータや、Cloudflare Tunnel などこのコンピュータへのトンネル用です。「ローカルネットワークで共有」をオンにするとここで追加できます。このコンピュータのエージェントには不要です。", "Gateway key name": "ゲートウェイキー名", "Key name, e.g. Laptop": "キー名(例:ノートPC)", @@ -12988,6 +12994,8 @@ const I18N = { "Gateway key rotated. Update clients on other computers.": "Zugangsschlüssel erneuert. Aktualisieren Sie die Clients auf anderen Computern.", "Add gateway key": "Zugangsschlüssel hinzufügen", "Create a gateway key for each client. Usage is counted separately for each key.": "Erstellen Sie für jeden Client einen Zugangsschlüssel. Die Nutzung wird je Schlüssel getrennt gezählt.", + "Key holders see their usage and setup at": "Wer einen Schlüssel hat, sieht Nutzung und Einrichtung hier:", + "Key page": "Schlüsselseite", "Gateway keys are for other computers, and for a tunnel to this one such as Cloudflare Tunnel: they are added here once Share on local network is on. Agents on this computer need none.": "Zugangsschlüssel sind für andere Computer und für einen Tunnel zu diesem Computer wie Cloudflare Tunnel: Sie werden hier hinzugefügt, sobald „Im lokalen Netzwerk freigeben“ an ist. Agenten auf diesem Computer brauchen keinen.", "Gateway key name": "Name des Zugangsschlüssels", "Key name, e.g. Laptop": "Schlüsselname, z. B. Laptop", diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index 6fbf9c7ca..9bb0a08c6 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -230,6 +230,22 @@ function renderGatewayKeys() { if (gatewayKeyDraft !== null) list.append(gatewayKeyForm()); else if (!gatewayKeys.length) list.append(el("div", "none", t("No gateway keys yet"))); box.append(list); + const page = gatewayKeyPage(); + if (page) box.append(page); +} + +// the key page (the gateway's /me): where a key's holder, with their key +// alone, sees what it has used and may use and the setup for their agents +// (zytszone on X: a department shares one magpie, whose app its people +// can't be given). Its address is the one other machines reach. +function gatewayKeyPage() { + const g = providers?.gateway, lan = g?.lanURLs || []; + const at = g?.publicURL || (lan.includes(connectURL) ? connectURL : lan[0]); + if (!at || !gatewayKeys?.length) return null; + const url = at.replace(/\/+$/, "") + "/me"; + const p = el("div", "usage-note gw-key-page"); + p.append(el("span", "", t("Key holders see their usage and setup at")), " ", el("code", "", url), copyBtn(url, t("Key page"))); + return p; } const ROTATE_GLYPH = "M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3.25h-3.25"; diff --git a/internal/gui/tests/README.md b/internal/gui/tests/README.md index e7684434a..be4dc6cc9 100644 --- a/internal/gui/tests/README.md +++ b/internal/gui/tests/README.md @@ -47,6 +47,18 @@ a live gateway. ## Gateway Caller Keys +`key-page.test.cjs` drives the gateway's key page (`/me`, +`internal/gateway/keypage.html`, under the gateway's CSP) at 390px in +Chromium and WebKit and every language: a wrong key is told so in the +page's language and shows nothing; the right one shows its limit, its +usage and most used model, picks that model, and gives Claude Code, Codex, +OpenAI-compatible and curl setup at the address the page was opened at, +with a placeholder until "Put my key in the setup" is ticked. A reload +keeps the key in the tab, Forget takes it away, and no request carries the +key in its address. A read-only key gets no setup. Gateway → Gateway keys +shows the page's address (the LAN one, or `MAGPIE_PUBLIC_URL`) with a +Copy, translated, and nothing with no key. + `gateway-keys-empty.test.cjs` checks the Gateway page with no gateway key yet, as magpie web on a 390px phone: "No gateway keys yet" sits inside the list's card, inset from its edges, in the muted colour and size of Recent diff --git a/internal/gui/tests/key-page.test.cjs b/internal/gui/tests/key-page.test.cjs new file mode 100644 index 000000000..41cc0abea --- /dev/null +++ b/internal/gui/tests/key-page.test.cjs @@ -0,0 +1,176 @@ +const assert = require("node:assert/strict"); +const fs = require("node:fs"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +// zytszone on X: magpie shared with a whole department, whose people can't +// be given the admin's app. Each opens the gateway's /me with their own +// gateway key and sees that key's limits, usage and models, and the setup +// for Claude Code, Codex and an OpenAI-compatible client with the address +// they opened it at. The page is the gateway's own file +// (internal/gateway/keypage.html), served as the gateway serves it, under +// its Content-Security-Policy; its data is a fixture that answers only the +// key sent as Authorization, never in the address. +const html = fs.readFileSync(path.resolve(__dirname, "../../gateway/keypage.html"), "utf8"); +const CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"; +const KEY = "sk-magpie-alice-0123456789"; +const BASE = "http://gw.test:3999"; +const ME = { + name: "Alice", readOnly: false, version: "dev", + limits: [{ period: "day", start: "2026-10-30T00:00:00Z", reset: "2026-10-31T00:00:00Z", calls: 4, tokens: 750, cost: 0, tokenLimit: 1000, tokensLeft: 250, costLeft: 0, spent: false }], + usage: { + today: { calls: 4, errors: 0, input: 600, output: 150, cache_read: 0, cache_write: 0, cost: 0.12, unpriced: 0 }, + "7d": { calls: 9, errors: 0, input: 1200, output: 300, cache_read: 0, cache_write: 0, cost: 0.3, unpriced: 0 }, + "30d": { calls: 20, errors: 1, input: 3000, output: 700, cache_read: 500, cache_write: 0, cost: 0.8, unpriced: 0 }, + }, + topModels: [{ id: "m2", calls: 12, errors: 0, input: 2000, output: 500, cache_read: 0, cache_write: 0, cost: 0.5, unpriced: 0 }], + models: [{ id: "plan/m1", label: "m1 · Plan" }, { id: "plan/m2", label: "m2 · Plan" }], +}; +const TITLE = { en: "Your gateway key", zh: "你的网关密钥", "zh-TW": "你的閘道金鑰", ja: "あなたのゲートウェイキー", de: "Ihr Zugangsschlüssel" }; +const LOCALE = { en: "en-US", zh: "zh-CN", "zh-TW": "zh-TW", ja: "ja-JP", de: "de-DE" }; + +async function open(engine, lang, me = ME) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width: 390, height: 844 }, locale: LOCALE[lang], reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + const seen = { urls: [], errors: [] }; + page.on("pageerror", (e) => seen.errors.push(e.message)); + page.on("request", (r) => seen.urls.push(r.url())); + await page.route("**/*", (route) => { + const req = route.request(), url = new URL(req.url()); + if (url.pathname === "/me") return route.fulfill({ contentType: "text/html; charset=utf-8", headers: { "Content-Security-Policy": CSP }, body: html }); + if (url.pathname === "/v1/magpie/me") { + if (url.searchParams.has("key")) return route.fulfill({ status: 400, json: {} }); + if (req.headers().authorization !== "Bearer " + KEY) return route.fulfill({ status: 401, json: { error: { message: "no" } } }); + return route.fulfill({ json: me }); + } + return route.fulfill({ status: 404, body: "" }); + }); + await page.goto(BASE + "/me"); + return { browser, page, seen }; +} + +const signIn = async (page, key) => { + await page.fill("#key", key); + await page.click("#go"); +}; +const snippet = (page) => page.locator("#snip pre").first().textContent(); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang}: a key's holder sees their own key and its setup`, async (t) => { + const { browser, page, seen } = await open(engine, lang); + t.after(() => browser.close()); + assert.equal(await page.locator("#signin h1").textContent(), TITLE[lang]); + // a wrong key is told so, in the page's language, and shows nothing + await signIn(page, "sk-magpie-wrong"); + await page.locator("#err").waitFor(); + const err = await page.locator("#err").textContent(); + assert.ok(err.length > 10, err); + if (lang !== "en") assert.doesNotMatch(err, /enabled gateway key/); + assert.equal(await page.locator("#info").isHidden(), true); + await signIn(page, KEY); + await page.locator("#info").waitFor(); + assert.equal(await page.locator("#name").textContent(), "Alice"); + assert.equal(await page.locator("#key").inputValue(), "", "the key is taken out of the field"); + // its limit, with how much is used + assert.equal(await page.locator("#limits .bar").count(), 1); + assert.equal(await page.locator("#limits .bar").getAttribute("aria-valuenow"), "75"); + // its usage: three periods + assert.equal(await page.locator("#stats .stat").count(), 3); + assert.match(await page.locator("#top").textContent(), /m2/); + // the model it called most is picked; the setup has the address it + // was opened at and a placeholder, not the key + assert.equal(await page.locator('#models button[aria-checked="true"]').getAttribute("data-id"), "plan/m2"); + let s = await snippet(page); + const claude = JSON.parse(s); + assert.equal(claude.env.ANTHROPIC_BASE_URL, BASE); + assert.equal(claude.env.ANTHROPIC_MODEL, "plan/m2"); + assert.equal(claude.env.ANTHROPIC_AUTH_TOKEN, "YOUR_GATEWAY_KEY"); + await page.check("#withKey"); + assert.equal(JSON.parse(await snippet(page)).env.ANTHROPIC_AUTH_TOKEN, KEY); + // Codex: its provider at /v1, the picked model + await page.click('#tabs [data-tab="codex"]'); + await page.click('#models [data-id="plan/m1"]'); + s = await snippet(page); + assert.match(s, /^model = "plan\/m1"\nmodel_provider = "magpie"\n/); + assert.match(s, /base_url = "http:\/\/gw\.test:3999\/v1"/); + assert.match(s, /wire_api = "responses"/); + assert.match(s, new RegExp(`experimental_bearer_token = "${KEY}"`)); + await page.click('#tabs [data-tab="openai"]'); + assert.deepEqual(await page.locator("#snip .kv code").allTextContents(), [BASE + "/v1", KEY, "plan/m1"]); + await page.click('#tabs [data-tab="curl"]'); + assert.match(await snippet(page), /curl http:\/\/gw\.test:3999\/v1\/chat\/completions/); + // filtering the models + await page.fill("#filter", "m1"); + assert.equal(await page.locator("#models button").count(), 1); + // nothing sideways at a phone's width + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + // a reload in the tab keeps it; Forget takes it away + await page.reload(); + await page.locator("#info").waitFor(); + await page.click("#forget"); + await page.locator("#signin").waitFor(); + assert.equal(await page.evaluate(() => sessionStorage.getItem("magpie-key")), null); + await page.reload(); + await page.locator("#signin").waitFor(); + assert.equal(await page.locator("#info").isHidden(), true); + // the key never went in an address + assert.deepEqual(seen.urls.filter((u) => u.includes("alice") || u.includes("key=")), []); + assert.deepEqual(seen.errors, []); + }); + } + + test(`${engine}: a read-only key is shown its usage and no setup`, async (t) => { + const { browser, page } = await open(engine, "en", { ...ME, readOnly: true, models: [], limits: [] }); + t.after(() => browser.close()); + await signIn(page, KEY); + await page.locator("#info").waitFor(); + assert.equal(await page.locator("#setupBlock").isHidden(), true); + assert.equal(await page.locator("#readOnly").isVisible(), true); + assert.equal(await page.locator("#limits").textContent(), "No limit on this key."); + }); + + // the admin finds the page's address under the gateway keys, the one + // other machines reach, and copies it + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang}: the gateway keys say where their holders look`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 390, height: 844 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", [], { lan: true, web: true })); + await page.goto("http://magpie.test/?view=gateway"); + const line = page.locator("#gatewayKeys .gw-key-page"); + await line.waitFor(); + assert.equal(await line.locator("code").textContent(), "http://192.168.1.10:3999/me"); + const text = await line.locator("span").first().textContent(); + if (lang === "en") assert.equal(text, "Key holders see their usage and setup at"); + else assert.notEqual(text, "Key holders see their usage and setup at"); + assert.equal(await line.locator("button.copy").count(), 1); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)); + assert.deepEqual(errors, []); + }); + } + + test(`${engine}: MAGPIE_PUBLIC_URL is the address given, and no keys gives none`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const ctx = await browser.newContext({ viewport: { width: 1000, height: 800 }, reducedMotion: "reduce" }); + let page = await ctx.newPage(); + page.setDefaultTimeout(6000); + await page.route("**/*", fixture("en", "light", [], { lan: true, web: true, publicURL: "https://ai.corp.example" })); + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#gatewayKeys .gw-key-page").waitFor(); + assert.equal(await page.locator("#gatewayKeys .gw-key-page code").textContent(), "https://ai.corp.example/me"); + page = await ctx.newPage(); + await page.route("**/*", fixture("en", "light", [], { lan: true, web: true, keys: [] })); + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#gatewayKeys .none").waitFor(); + assert.equal(await page.locator("#gatewayKeys .gw-key-page").count(), 0); + }); +}