diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index eb85d502a..77c48af3a 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -414,6 +414,32 @@ request alone. `Server.gatewayTrace` in `TestHeldKeyToldNoAccounts` in [`quotas_held_key_test.go`](../../internal/gateway/quotas_held_key_test.go). +A read-only gateway key (`access.Key.ReadOnly`, set by `add-key` or +`access-key`; `magpie gateway-key add --read-only`, `gateway-key +access read-only|full`, or the key's menu in Gateway → Gateway keys) +reads this magpie's stats and uses nothing: a desk display polling +`/v1/magpie/quotas` and `/v1/magpie/usage` keeps such a key in its flash. +`readOnlyGuard` in [`readonly.go`](../../internal/gateway/readonly.go) sits +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`: +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 +is refused it until it is put in that list. A read-only key is held to +nothing else, so `heldKey` leaves it alone and it reads the usage summary +and every account's quotas as a key held to nothing does; none of those +routes tells a key's secret. The sharing key can't be read-only: magpie +gives it to its own agents (`LANSecret`). A magpie from before this field +reads such a key as a full one. `TestReadOnlyKeyEveryRoute` in +[`readonly_test.go`](../../internal/gateway/readonly_test.go) fails when a +route the router has is in neither `readOnlyRoutes` nor its refused list, +and sends each refused pattern, by each method it takes, from loopback and +from the network. + A remote provider serves the conversation, token-counting, System One, embeddings, rerank, speech-to-text, image generation/edit and video creation/status/content APIs. Gemini clients enter through the local Gemini adapter and follow the diff --git a/internal/access/access.go b/internal/access/access.go index beff2878b..3921f0437 100644 --- a/internal/access/access.go +++ b/internal/access/access.go @@ -134,6 +134,12 @@ type Key struct { // every model it may use, of the accounts and keys it may use, names // and balances included. Off, it is told none (#1981). Quotas bool `json:"quotas,omitempty"` + // ReadOnly holds the key to reading this magpie's stats (Steven on + // Discord: a desk display polling quotas and usage, its key kept in + // a device's flash): the gateway answers it only the routes in its + // readOnlyRoutes and refuses it every other, every model, MCP and + // write route among them. Off, the key may do what its other limits let it. + ReadOnly bool `json:"readOnly,omitempty"` } // Identity is the gateway key a request came with, its budget, the @@ -145,6 +151,7 @@ type Identity struct { Models []string Accounts []string Quotas bool + ReadOnly bool } type contextKey struct{} @@ -300,6 +307,9 @@ type Change struct { Accounts []string `json:"accounts,omitempty"` // Quotas is what "quotas-key" sets (#2216). Quotas bool `json:"quotas,omitempty"` + // ReadOnly is what "access-key" sets, and "add-key" gives the new key: + // it may read stats and use no model (Key.ReadOnly). + ReadOnly bool `json:"readOnly,omitempty"` // Secret is the value "add-key" gives the new key, one its clients // already send (love1sbug on X: keys handed out from another gateway); // "" for one magpie makes. @@ -341,7 +351,7 @@ func Update(action string, in Change) (string, error) { } secret = Prefix + token } - keys = append(keys, Key{ID: id, Name: name, Secret: secret}) + keys = append(keys, Key{ID: id, Name: name, Secret: secret, ReadOnly: in.ReadOnly}) } else { i := slices.IndexFunc(keys, func(k Key) bool { return k.ID == in.Key }) if i < 0 { @@ -441,6 +451,14 @@ func Update(action string, in Change) (string, error) { keys[i].Accounts = as case "quotas-key": keys[i].Quotas = in.Quotas + case "access-key": + // the sharing key is the one magpie gives its own agents (a + // WSL distro's under NAT, LANSecret): read-only, they could + // no longer use a model + if in.ReadOnly && defaultKey { + return "", errors.New("The sharing key is the one magpie gives agents that reach it from elsewhere, so it can't be read-only: add a key of its own for reading stats") + } + keys[i].ReadOnly = in.ReadOnly case "on-key", "off-key": keys[i].Off = action == "off-key" case "remove-key": @@ -455,7 +473,7 @@ func Update(action string, in Change) (string, error) { default: return "", fmt.Errorf("unknown key action %q", action) } - if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "quotas-key" { + if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "quotas-key" && action != "access-key" { mirror = &keys[i] } } @@ -502,7 +520,7 @@ func Authenticate(secret string) (Identity, bool) { if k.Off { return Identity{}, false } - return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Accounts: k.Accounts, Quotas: k.Quotas}, true + return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), Accounts: k.Accounts, Quotas: k.Quotas, ReadOnly: k.ReadOnly}, true } } s := settings.Load() diff --git a/internal/access/readonly_test.go b/internal/access/readonly_test.go new file mode 100644 index 000000000..8406ec656 --- /dev/null +++ b/internal/access/readonly_test.go @@ -0,0 +1,62 @@ +package access + +import ( + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +// A read-only key (Steven on Discord: a desk display's) is made so by +// add-key or access-key, is told so by Authenticate, and is made full +// again; the sharing key, which magpie gives its own agents, is never. +func TestReadOnlyKey(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + display, err := Update("add-key", Change{Name: "Desk display", ReadOnly: true}) + if err != nil { + t.Fatal(err) + } + laptop, err := Update("add-key", Change{Name: "Laptop"}) + if err != nil { + t.Fatal(err) + } + if who, ok := Authenticate(display); !ok || !who.ReadOnly { + t.Fatal("added read-only:", who, ok) + } + who, ok := Authenticate(laptop) + if !ok || who.ReadOnly { + t.Fatal("added full:", who, ok) + } + id := who.KeyID + if _, err := Update("access-key", Change{Key: id, ReadOnly: true}); err != nil { + t.Fatal(err) + } + if who, _ := Authenticate(laptop); !who.ReadOnly { + t.Fatal("access-key read-only:", who) + } + keys, _ := List() + if !keys[1].ReadOnly || keys[1].Secret != "" { + t.Fatal("listed:", keys[1]) + } + if _, err := Update("access-key", Change{Key: id}); err != nil { + t.Fatal(err) + } + if who, _ := Authenticate(laptop); who.ReadOnly { + t.Fatal("access-key full:", who) + } + + s := settings.Load() + s.LANKeyID = id + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if _, err := Update("access-key", Change{Key: id, ReadOnly: true}); err == nil || !strings.Contains(err.Error(), "sharing key") { + t.Fatal("the sharing key made read-only:", err) + } + if who, _ := Authenticate(laptop); who.ReadOnly { + t.Fatal("the sharing key is read-only:", who) + } + if _, err := Update("access-key", Change{Key: id}); err != nil { + t.Fatal("the sharing key given full access:", err) + } +} diff --git a/internal/cli/gateway_key_readonly_test.go b/internal/cli/gateway_key_readonly_test.go new file mode 100644 index 000000000..aa0aa42c7 --- /dev/null +++ b/internal/cli/gateway_key_readonly_test.go @@ -0,0 +1,70 @@ +package cli + +import ( + "bytes" + "os" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/settings" +) + +// gateway-key add --read-only and gateway-key access (Steven on Discord: a +// desk display's key reads stats and uses no model). +func TestGatewayKeyCLIReadOnly(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", os.Getenv("HOME")) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if err := settings.Save(settings.Settings{LAN: true}); err != nil { + t.Fatal(err) + } + call := func(args ...string) string { + t.Helper() + var out bytes.Buffer + if err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...)); err != nil { + t.Fatal(args, err) + } + return strings.TrimSpace(out.String()) + } + display := call("add", "Desk display", "--read-only") + laptop := call("add", "--read-only", "Laptop", "--key", "cpa-laptop-key-0042") + if laptop != "cpa-laptop-key-0042" { + t.Fatal("--read-only beside --key:", laptop) + } + for _, s := range []string{display, laptop} { + if who, ok := access.Authenticate(s); !ok || !who.ReadOnly { + t.Fatal("added read-only:", who, ok) + } + } + keys, _ := access.List() + id := keys[1].ID + if got := call("list"); !strings.Contains(got, "ACCESS") || strings.Count(got, "read-only") != 2 { + t.Fatal("list:", got) + } + if got := call("access", id); !strings.Contains(got, "Laptop: read-only") { + t.Fatal("access:", got) + } + if got := call("access", id, "full"); !strings.Contains(got, "Laptop: full access") { + t.Fatal("access full:", got) + } + if who, _ := access.Authenticate(laptop); who.ReadOnly { + t.Fatal("still read-only:", who) + } + if got := call("list"); strings.Count(got, "read-only") != 1 || !strings.Contains(got, "full") { + t.Fatal("list after:", got) + } + call("access", id, "read-only") + if who, _ := access.Authenticate(laptop); !who.ReadOnly { + t.Fatal("not read-only:", who) + } + for _, args := range [][]string{{"access"}, {"access", id, "write"}, {"access", id, "full", "x"}, {"access", "missing", "full"}} { + if err := gatewayKeysTo(&bytes.Buffer{}, append([]string{"gateway-key"}, args...)); err == nil { + t.Error("accepted", args) + } + } + help := helpFor([]string{"gateway-key", "--help"}) + if !strings.Contains(help, "--read-only") || !strings.Contains(help, "gateway-key access [read-only|full]") { + t.Fatal("help:", help) + } +} diff --git a/internal/cli/gateway_keys_cli.go b/internal/cli/gateway_keys_cli.go index 682d42209..12d521999 100644 --- a/internal/cli/gateway_keys_cli.go +++ b/internal/cli/gateway_keys_cli.go @@ -40,6 +40,19 @@ func gatewayKeysTo(out io.Writer, args []string) error { access.MigrateLegacyLANKeyBestEffort() return gatewayKeyQuotas(out, args[1:]) } + if action == "access" { + access.MigrateLegacyLANKeyBestEffort() + return gatewayKeyAccess(out, args[1:]) + } + // add --read-only: a key that reads stats and uses no model + // (Steven on Discord: a desk display) + readOnly := false + if action == "add" { + if i := slices.Index(args[1:], "--read-only"); i >= 0 { + readOnly = true + args = slices.Delete(slices.Clone(args), 1+i, 2+i) + } + } // add --key : the key keeps a value its clients already // send (love1sbug on X); "--key -" reads it from stdin, out of the // shell's history @@ -59,7 +72,7 @@ func gatewayKeysTo(out io.Writer, args []string) error { args = args[:2] } if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) { - return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] | rotate | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads]] | models [all | /|/* ...] | accounts [all | /|/ ...] | quotas [on | off]") + return fmt.Errorf("usage: magpie gateway-key list | add [--key | --key -] [--read-only] | rotate | remove | limit [list | off | reset [] | remove | [add] day|week|month|d|h [--tokens N] [--cost USD] [--cache-reads]] | models [all | /|/* ...] | accounts [all | /|/ ...] | quotas [on | off] | access [read-only | full]") } switch action { case "list", "add", "rotate", "remove": @@ -73,7 +86,7 @@ func gatewayKeysTo(out io.Writer, args []string) error { return err } w := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0) - fmt.Fprintln(w, "ID\tNAME\tSTATE\tGATEWAY KEY\tLIMIT\tMODELS\tACCOUNTS") + fmt.Fprintln(w, "ID\tNAME\tSTATE\tGATEWAY KEY\tLIMIT\tMODELS\tACCOUNTS\tACCESS") now := time.Now() // an account is shown by who is signed in, kept by its stable id (#905) names := provider.AccountNames() @@ -96,18 +109,18 @@ func gatewayKeysTo(out io.Writer, args []string) error { } accounts = strings.Join(shown, ",") } - fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n", k.ID, strings.Map(func(r rune) rune { + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", k.ID, strings.Map(func(r rune) rune { if r < 32 || r == 127 { return ' ' } return r - }, k.Name), state, k.Masked, limitWords(k, now), models, accounts) + }, k.Name), state, k.Masked, limitWords(k, now), models, accounts, accessWord(k)) } return w.Flush() } in := access.Change{Key: args[1]} if action == "add" { - in = access.Change{Name: args[1], Secret: own} + in = access.Change{Name: args[1], Secret: own, ReadOnly: readOnly} } secret, err := access.Update(action+"-key", in) if err != nil { @@ -501,3 +514,47 @@ func gatewayKeyQuotas(out io.Writer, args []string) error { } return err } + +// accessWord is a key's access as the list says it: "read-only" or "full". +func accessWord(k access.Key) string { + if k.ReadOnly { + return "read-only" + } + return "full" +} + +// gatewayKeyAccess shows or sets whether a key may use models or only +// read magpie's stats (Steven on Discord: a desk display's key): +// +// magpie gateway-key access which it has +// magpie gateway-key access read-only|full quotas and usage alone, or what its other limits let it +func gatewayKeyAccess(out io.Writer, args []string) error { + usage := fmt.Errorf("usage: magpie gateway-key access [read-only | full]") + if len(args) == 0 || len(args) > 2 { + return usage + } + id := args[0] + if len(args) == 2 { + if args[1] != "read-only" && args[1] != "full" { + return usage + } + if _, err := access.Update("access-key", access.Change{Key: id, ReadOnly: args[1] == "read-only"}); 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] + if k.ReadOnly { + _, err = fmt.Fprintf(out, "%s: read-only, it reads quotas and usage and uses no model, MCP server or write\n", k.Name) + } else { + _, err = fmt.Fprintf(out, "%s: full access, models and stats as its other limits let it\n", k.Name) + } + return err +} diff --git a/internal/cli/main.go b/internal/cli/main.go index 6d7e9c205..6e109885f 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -120,10 +120,11 @@ const usage = `magpie — one place to pick every agent's model magpie heap [] a Go heap profile of the running magpie, with its memory numbers, for a report of it using too much memory magpie cpu [] [--seconds N] a Go CPU profile of the running magpie over 30s (5..120) while you use it, for a report of it using too much CPU magpie goroutines [] every goroutine of the running magpie, its stack and how long it waited, for a report of it stuck at something - magpie gateway-key list|add |rotate |remove manage the keys clients use to call a shared gateway + magpie gateway-key list|add [--read-only]|rotate |remove manage the keys clients use to call a shared gateway magpie gateway-key limit [list|off|reset [n]|remove |[add] day|week|month|d|h --tokens N --cost USD --cache-reads] a key's own limits, and what it used magpie gateway-key models [all|/|/* ...] the models a key may use, every one unless it names some magpie gateway-key quotas [on|off] whether a key held to a budget, models or accounts is told the quotas of what it may use + magpie gateway-key access [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 mcp image the image and video generation MCP server an agent is given from the library (stdio) magpie tools [] the tools magpie's MCP servers give agents (images, vision, web search, plugins'), with their parameters magpie tool [-- …] [] [-o ] [--json] call one through the running magpie; an image or video it makes is saved diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 5c6e515e6..d3e7e1f2c 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -758,7 +758,18 @@ func (s *Server) ListenAndServe(ctx context.Context) error { // Handler routes the client APIs. func (s *Server) Handler() http.Handler { - mux := http.NewServeMux() + mux := s.routes() + // the goroutine dump first, ahead of every lock the rest can be stuck + // on (dumpFirst) + // a socket's turns go through all of it again (socketEntry) + return socketEntry(s.dumpFirst(s.counted(holdCatalog(corsGuard(callerGuard(readOnlyGuard(mux, withCaller(keyLimited(mux))))))))) +} + +// routes are the client APIs, each by its pattern: readOnlyGuard reads +// which one a request is for, and TestReadOnlyKeyEveryRoute that each is +// judged for a read-only key. +func (s *Server) routes() *routeMux { + mux := &routeMux{ServeMux: http.NewServeMux()} mux.HandleFunc("GET /{$}", s.info) // an OpenAI-compatible base URL answers too: Empryo lists a provider with // no key of its own only when its baseURL does @@ -857,10 +868,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech and /v1beta/models/*") }) - // the goroutine dump first, ahead of every lock the rest can be stuck - // on (dumpFirst) - // a socket's turns go through all of it again (socketEntry) - return socketEntry(s.dumpFirst(s.counted(holdCatalog(corsGuard(callerGuard(withCaller(keyLimited(mux)))))))) + return mux } // responsesOverHTTP answers a GET on /v1/responses. A WebSocket upgrade diff --git a/internal/gateway/oneport_test.go b/internal/gateway/oneport_test.go index fbd246244..ee0e0dd8d 100644 --- a/internal/gateway/oneport_test.go +++ b/internal/gateway/oneport_test.go @@ -3,13 +3,10 @@ package gateway import ( "net/http" "net/http/httptest" - "os" - "regexp" "strings" "testing" "github.com/yetone/magpie/internal/access" - "github.com/yetone/magpie/internal/provider" ) // Every route Handler registers is either a client route `magpie web`'s @@ -19,35 +16,9 @@ import ( // /_magpie/. A route added to Handler and to neither fails this, so the // one-port page doesn't miss it, or take it, by accident. func TestClientPathCoversHandler(t *testing.T) { - src, err := os.ReadFile("gateway.go") - if err != nil { - t.Fatal(err) - } - start := strings.Index(string(src), "func (s *Server) Handler() http.Handler {") - end := strings.Index(string(src)[start:], "\n}\n") - body := string(src)[start : start+end] - consts := map[string]string{ - "claudeMCPPath": claudeMCPPath, "CodexPath": CodexPath, "CodexCatalogPath": CodexCatalogPath, - "AlphaSearchPath": AlphaSearchPath, "HeapPath": HeapPath, "CPUPath": CPUPath, - "GoroutinesPath": GoroutinesPath, "ClaudeRunsPath": ClaudeRunsPath, "SearchMCPPath": SearchMCPPath, "VisionMCPPath": VisionMCPPath, - "ImageMCPPath": ImageMCPPath, "ImageMCPFiles": ImageMCPFiles, - "ToolsMCPPath": ToolsMCPPath, "HubMCPPath": HubMCPPath, "HubMCPAll": HubMCPAll, "provider.RemoteCardsPath": provider.RemoteCardsPath, - "provider.RemoteRefreshPath": provider.RemoteRefreshPath, - } - re := regexp.MustCompile(`mux\.HandleFunc\(((?:"[^"]*"|[A-Za-z.]+)(?:\s*\+\s*(?:"[^"]*"|[A-Za-z.]+))*),`) + // the patterns as routes() registers them, not as its source reads n := 0 - for _, m := range re.FindAllStringSubmatch(body, -1) { - pat := "" - for _, part := range strings.Split(m[1], "+") { - part = strings.TrimSpace(part) - if strings.HasPrefix(part, `"`) { - pat += strings.Trim(part, `"`) - } else if v, ok := consts[part]; ok { - pat += v - } else { - t.Fatalf("Handler names %s, which this test doesn't know: add it to consts", part) - } - } + for _, pat := range New().routes().patterns { if i := strings.IndexByte(pat, ' '); i >= 0 { pat = pat[i+1:] } @@ -59,7 +30,7 @@ func TestClientPathCoversHandler(t *testing.T) { } } if n < 60 { - t.Fatalf("found %d routes in Handler: the pattern no longer reads it", n) + t.Fatalf("found %d routes in Handler", n) } } diff --git a/internal/gateway/readonly.go b/internal/gateway/readonly.go new file mode 100644 index 000000000..5d2dcde48 --- /dev/null +++ b/internal/gateway/readonly.go @@ -0,0 +1,71 @@ +package gateway + +import ( + "log" + "net/http" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// A read-only gateway key (access.Key.ReadOnly) reads this magpie's stats +// and uses nothing (Steven on Discord: an ESP32 desk display polling +// /v1/magpie/quotas and /v1/magpie/usage every 15s, its key kept in the +// device's flash, which had to be a key that could spend every account). +// It is answered the routes below alone, by the pattern the request is +// routed to, so a route added later is refused it until it is put here: +// every model route, count_tokens, a WebSocket's upgrade, every MCP +// server, a plugin's backend and every write are refused, whatever +// method or path spelling reaches them. TestReadOnlyKeyEveryRoute fails +// when a route is neither here nor in its list of refused ones. +// +// What it reads is what a key held to nothing reads: the usage summary +// and every account's quotas (it is no one else's to spend, so heldKey +// leaves it alone unless it is held to a budget, models or accounts as +// well). None of these routes tells a gateway key's secret. +var readOnlyRoutes = map[string]bool{ + "GET /{$}": true, + "GET /v1": true, + "GET /v1/{$}": true, + "GET /v1/magpie/quotas": true, + "GET /v1/magpie/quotas/history": true, + "GET " + provider.RemoteCardsPath: true, + "GET /v1/magpie/usage": true, + "GET /v1/magpie/usage/requests": true, + "GET /v1/magpie/limit": true, + "GET /v1/magpie/concurrency": true, +} + +// ReadOnlyCode is the error code a read-only key is refused a route with. +const ReadOnlyCode = "gateway_key_read_only" + +// routeMux is a ServeMux that keeps the patterns it was given. +type routeMux struct { + *http.ServeMux + patterns []string +} + +func (m *routeMux) HandleFunc(pattern string, h func(http.ResponseWriter, *http.Request)) { + m.patterns = append(m.patterns, pattern) + m.ServeMux.HandleFunc(pattern, h) +} + +// readOnlyGuard refuses a read-only key every route of mux but +// readOnlyRoutes, before anything is read, reserved or sent. +func readOnlyGuard(mux *routeMux, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + who := access.Caller(r.Context()) + if who.ReadOnly { + // a path that isn't clean is routed to a redirect under the + // pattern of where it goes, and judged again when it gets there + if _, pattern := mux.Handler(r); !readOnlyRoutes[pattern] { + log.Printf("refused %s %s: gateway key %q is read-only", r.Method, r.URL.Path, who.KeyName) + writeJSON(w, http.StatusForbidden, map[string]any{"error": map[string]any{ + "message": "this gateway key is read-only: it may read magpie's quotas and usage (GET /v1/magpie/quotas, /v1/magpie/quotas/history, /v1/magpie/usage, /v1/magpie/usage/requests, /v1/magpie/limit) and use no model, MCP server or write. Use a key with full access for that (Gateway → Gateway keys, or magpie gateway-key access full)", + "type": "permission_error", "code": ReadOnlyCode}}) + return + } + } + next.ServeHTTP(w, r) + }) +} diff --git a/internal/gateway/readonly_test.go b/internal/gateway/readonly_test.go new file mode 100644 index 000000000..605eb7830 --- /dev/null +++ b/internal/gateway/readonly_test.go @@ -0,0 +1,194 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "regexp" + "slices" + "strings" + "sync/atomic" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// readOnlyRefused is every route a read-only key is refused, by the pattern +// it is registered under. A route the router has that is neither here nor +// in readOnlyRoutes fails TestReadOnlyKeyEveryRoute, so a new one is +// classified before it ships: the guard refuses it until then. +var readOnlyRefused = []string{ + // model lists and their Ollama spellings: what the key could use + "GET /v1/models", "GET /models", "GET /v1/models/{id...}", "GET /muse-code/models", + "GET /api/hello", "GET /api/version", "GET /api/tags", + "POST /api/show", "POST /api/chat", "POST /api/generate", + // writes, another key's routes, the whole trace, debugging + "POST /v1/magpie/usage/requests", "POST " + provider.RemoteRefreshPath, + "GET /v1/magpie/route", "GET /v1/magpie/trace", + "GET " + ClaudeRunsPath, "GET " + HeapPath, "GET " + CPUPath, "GET " + GoroutinesPath, + "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", + "POST /v1/responses", "POST /responses", "GET /v1/responses", "GET /responses", + "POST /v1/messages", "POST /messages", "POST /v1/systemone", + "POST /v1" + AlphaSearchPath, "POST " + AlphaSearchPath, "POST /v1/messages/count_tokens", + "POST /v1/images/generations", "POST /images/generations", "POST /v1/images/edits", "POST /images/edits", + "POST /v1/embeddings", "POST /embeddings", "POST /v1/rerank", "POST /rerank", + "POST /v1/audio/transcriptions", "POST /audio/transcriptions", + "POST /v1/audio/translations", "POST /audio/translations", + "POST /v1/audio/speech", "POST /audio/speech", + "POST /v1/videos", "POST /videos", "GET /v1/videos/{id}", "GET /videos/{id}", + "GET /v1/videos/{id}/content", "GET /videos/{id}/content", + // MCP servers, plugins' and Codex's backends, Gemini, everything else + "POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}", + SearchMCPPath, VisionMCPPath, ImageMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, + HubMCPPath + "{agent}", HubMCPAll, CodexPath + "/", "GET " + CodexCatalogPath, + "GET /v1beta/models", "POST /v1beta/models/{call...}", "/", +} + +var wildcard = regexp.MustCompile(`\{[a-z]+(\.\.\.)?\}`) + +// requestsFor is a request a pattern is routed, one per method it takes. +func requestsFor(pattern string) [][2]string { + methods, path := []string{"GET", "POST", "PUT", "DELETE"}, pattern + if m, p, ok := strings.Cut(pattern, " "); ok { + methods, path = []string{m}, p + } + switch { + case path == "/": + path = "/no/such/route" // the catch-all + case strings.HasSuffix(path, "{$}"): + path = strings.TrimSuffix(path, "{$}") // that path alone + case strings.HasSuffix(path, "/"): + path += "x" // a subtree: a path under it + } + path = wildcard.ReplaceAllString(path, "x") + var out [][2]string + for _, m := range methods { + out = append(out, [2]string{m, path}) + } + return out +} + +// Steven on Discord: an ESP32 desk display polls magpie's quotas and usage +// on his network every 15s and sends no model request, yet the key it +// keeps in flash had to be one that could spend every account. A +// read-only key is answered the stats alone: every other route the +// router has (every model, count_tokens, a WebSocket's upgrade, every +// MCP server, a plugin's backend and every write) is refused it, from +// this computer and from another, and no upstream is reached. What it +// reads is what a key held to nothing reads, the usage summary and every +// account's quotas, and none of it is a key's secret. +func TestReadOnlyKeyEveryRoute(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + var reached atomic.Int32 + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reached.Add(1) + 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}}`) + })) + defer up.Close() + if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil { + t.Fatal(err) + } + keys, secrets := newCaller(t, "Desk display", "Laptop") + if _, err := access.Update("access-key", access.Change{Key: keys[0].ID, ReadOnly: true}); err != nil { + t.Fatal(err) + } + display, full := secrets[0], secrets[1] + + mux := New().routes() + for _, p := range mux.patterns { + if readOnlyRoutes[p] == slices.Contains(readOnlyRefused, p) { + t.Errorf("route %q is in neither readOnlyRoutes nor readOnlyRefused, or in both: say whether a read-only key may reach it", p) + } + } + for p := range readOnlyRoutes { + if !slices.Contains(mux.patterns, p) { + t.Errorf("readOnlyRoutes names %q, which the router doesn't have", p) + } + } + + h := lanGuard(New().Handler()) + do := func(method, path, from, secret string, hdr ...string) (int, string) { + var body io.Reader + if method == "POST" || method == "PUT" { + body = strings.NewReader(chatReq) + } + r := httptest.NewRequest(method, path, body) + r.RemoteAddr = from + r.Header.Set("Authorization", "Bearer "+secret) + r.Header.Set("Content-Type", "application/json") + for i := 0; i+1 < len(hdr); i += 2 { + r.Header.Set(hdr[i], hdr[i+1]) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code, w.Body.String() + } + + // the full key makes a request, so there is usage to read + if c, b := do("POST", "/v1/chat/completions", "192.168.1.9:5000", full); c != 200 { + t.Fatal("a full key's request:", c, b) + } + reached.Store(0) + + for _, from := range []string{"192.168.1.9:5000", "127.0.0.1:5000"} { + for _, p := range readOnlyRefused { + for _, mp := range requestsFor(p) { + c, b := do(mp[0], mp[1], from, display) + if c != http.StatusForbidden || !strings.Contains(b, ReadOnlyCode) { + t.Errorf("read-only key from %s: %s %s (%s): %d %.200s", from, mp[0], mp[1], p, c, b) + } + } + } + // a WebSocket's upgrade, by its header and by a path that isn't clean + for _, path := range []string{"/v1/responses", "/responses"} { + c, b := do("GET", path, from, display, "Upgrade", "websocket", "Connection", "Upgrade", "Sec-WebSocket-Version", "13", "Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") + if c != http.StatusForbidden || !strings.Contains(b, ReadOnlyCode) { + t.Errorf("read-only key from %s: a WebSocket on %s: %d %.200s", from, path, c, b) + } + } + if c, b := do("POST", "/v1//chat/completions", from, display); c == 200 || strings.Contains(b, `"choices"`) { + t.Errorf("read-only key from %s: an unclean chat path: %d %.200s", from, c, b) + } + if n := reached.Load(); n != 0 { + t.Fatalf("read-only key from %s: the upstream was reached %d times", from, n) + } + + for p := range readOnlyRoutes { + for _, mp := range requestsFor(p) { + c, b := do(mp[0], mp[1], from, display) + if c == http.StatusForbidden || c == http.StatusUnauthorized { + t.Errorf("read-only key from %s: %s %s refused: %d %.200s", from, mp[0], mp[1], c, b) + } + for _, s := range append(slices.Clone(secrets), "upstream-secret") { + if strings.Contains(b, s) { + t.Errorf("read-only key from %s: %s %s tells a secret: %.200s", from, mp[0], mp[1], b) + } + } + } + } + // the usage summary, which a held key isn't told, and the quotas + c, b := do("GET", "/v1/magpie/usage", from, display) + if c != 200 || !strings.Contains(b, "Laptop") { + t.Errorf("read-only key from %s: the usage summary: %d %.300s", from, c, b) + } + if c, b := do("GET", "/v1/magpie/quotas", from, display); c != 200 || strings.Contains(b, provider.KeyHeldCode) { + t.Errorf("read-only key from %s: the quotas: %d %.300s", from, c, b) + } + } + + // the full key is as it was; made full again, so is the display's + if c, b := do("POST", "/v1/chat/completions", "192.168.1.9:5000", full); c != 200 { + t.Error("the full key's request after:", c, b) + } + if _, err := access.Update("access-key", access.Change{Key: keys[0].ID}); err != nil { + t.Fatal(err) + } + if c, b := do("POST", "/v1/chat/completions", "192.168.1.9:5000", display); c != 200 { + t.Error("the display's key given full access:", c, b) + } +} diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 34c5a15e8..46e835f93 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -2801,6 +2801,9 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } and gives way before the row runs past a narrow window */ #gatewayKeys .amodels.key-quotas { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; } #gatewayKeys .acc:not(:hover) > .key-quotas:not(.set):not(:focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; } +/* a read-only key's tag, always shown, never a button */ +#gatewayKeys .amodels.key-readonly { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: default; } +#gatewayKeys .amodels.key-readonly:hover { color: var(--accent); background: var(--accent-soft); } /* the Settings row's picker: the key row's badge, always shown */ .row.pref .proto.pick { flex: none; margin-left: auto; display: inline-flex; align-items: center; gap: 3px; height: 24px; padding: 0 6px 0 9px; font: inherit; font-size: 12px; color: var(--fg-2); border: 0; border-radius: 7px; background: var(--pill); white-space: nowrap; cursor: default; transition: background .12s, color .12s; } .row.pref .proto.pick svg { opacity: .7; transition: transform .15s var(--ease); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index d97de74fa..afb541029 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -458,6 +458,13 @@ const I18N = { "Copy gateway key": "复制网关密钥", "Rotate key": "轮换密钥", "Key actions": "密钥操作", + "Make read-only": "设为只读", + "Give full access": "恢复完整权限", + "Read only": "只读", + "This key only reads quotas and usage. It can't use models or MCP servers, or change anything.": "这个密钥只能读取额度和用量,不能使用模型和 MCP 服务器,也不能更改任何内容。", + "{name} is read-only": "{name} 已设为只读", + "{name} has full access": "{name} 已恢复完整权限", + "The sharing key is given to agents, so it can't be read-only": "共享密钥会交给 Agent 使用,不能设为只读", "No gateway keys yet": "尚无网关密钥", "No gateway key": "无网关密钥", "Rotate gateway key?": "轮换网关密钥?", @@ -4618,6 +4625,13 @@ const I18N = { "Copy gateway key": "複製閘道金鑰", "Rotate key": "輪換金鑰", "Key actions": "金鑰操作", + "Make read-only": "設為唯讀", + "Give full access": "恢復完整權限", + "Read only": "唯讀", + "This key only reads quotas and usage. It can't use models or MCP servers, or change anything.": "這個金鑰只能讀取額度和用量,不能使用模型和 MCP 伺服器,也不能變更任何內容。", + "{name} is read-only": "{name} 已設為唯讀", + "{name} has full access": "{name} 已恢復完整權限", + "The sharing key is given to agents, so it can't be read-only": "共享金鑰會交給 Agent 使用,不能設為唯讀", "No gateway keys yet": "尚無閘道金鑰", "No gateway key": "無閘道金鑰", "Rotate gateway key?": "輪換閘道金鑰?", @@ -8740,6 +8754,13 @@ const I18N = { "Copy gateway key": "ゲートウェイキーをコピー", "Rotate key": "キーを再発行", "Key actions": "キーの操作", + "Make read-only": "読み取り専用にする", + "Give full access": "フルアクセスに戻す", + "Read only": "読み取り専用", + "This key only reads quotas and usage. It can't use models or MCP servers, or change anything.": "このキーは残量と使用量を読むだけです。モデルや MCP サーバーは使えず、何も変更できません。", + "{name} is read-only": "{name} を読み取り専用にしました", + "{name} has full access": "{name} をフルアクセスに戻しました", + "The sharing key is given to agents, so it can't be read-only": "共有キーはエージェントに渡されるため、読み取り専用にはできません", "No gateway keys yet": "ゲートウェイキーはまだありません", "No gateway key": "ゲートウェイキーなし", "Rotate gateway key?": "ゲートウェイキーを再発行しますか?", @@ -12879,6 +12900,13 @@ const I18N = { "Copy gateway key": "Zugangsschlüssel kopieren", "Rotate key": "Schlüssel erneuern", "Key actions": "Schlüsselaktionen", + "Make read-only": "Nur Lesezugriff geben", + "Give full access": "Vollen Zugriff geben", + "Read only": "Nur Lesen", + "This key only reads quotas and usage. It can't use models or MCP servers, or change anything.": "Dieser Schlüssel liest nur Kontingente und Nutzung. Er kann keine Modelle oder MCP-Server nutzen und nichts ändern.", + "{name} is read-only": "{name} hat jetzt nur Lesezugriff", + "{name} has full access": "{name} hat wieder vollen Zugriff", + "The sharing key is given to agents, so it can't be read-only": "Der Freigabeschlüssel wird an Agenten gegeben und kann daher nicht auf Nur Lesen gestellt werden", "No gateway keys yet": "Noch keine Zugangsschlüssel", "No gateway key": "Ohne Zugangsschlüssel", "Rotate gateway key?": "Zugangsschlüssel erneuern?", diff --git a/internal/gui/assets/plugins/gateway/keys.js b/internal/gui/assets/plugins/gateway/keys.js index e229d3b06..6fbf9c7ca 100644 --- a/internal/gui/assets/plugins/gateway/keys.js +++ b/internal/gui/assets/plugins/gateway/keys.js @@ -222,7 +222,7 @@ function renderGatewayKeys() { tick.onclick = () => gatewayKeyAction(k.off ? "on-key" : "off-key", { key: k.id }); // the copy sits by the key it copies (the owner: stranded among the // badges it read as nobody's); Rotate and Remove wait in the row's menu - row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), gatewayModelsBadge(k), gatewayQuotasBadge(k), gatewayLimitBadge(k), gatewayKeyMore(k)); + row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), copyCallerKeyBtn(k), el("span", "grow"), ...(k.readOnly ? [gatewayReadOnlyTag()] : []), gatewayModelsBadge(k), gatewayQuotasBadge(k), gatewayLimitBadge(k), gatewayKeyMore(k)); const under = gatewayLimit?.id === k.id ? [gatewayLimitEditor(k)] : keyUsed(k).map((u) => gatewayLimitLine(k, u)); if (under.length) row.classList.add("with-limit"), row.append(...under); list.append(row); @@ -250,6 +250,11 @@ function gatewayKeyMore(k) { // added again) openRowMenu(more, [ { name: k.off ? "Enable key" : "Disable key", icon: POWER_GLYPH, run: () => gatewayKeyAction(k.off ? "on-key" : "off-key", { key: k.id }) }, + // read-only (Steven on Discord: a desk display's key reads quotas + // and usage, and uses nothing); the sharing key is given to agents + k.readOnly + ? { name: "Give full access", icon: EYE_GLYPH, run: () => gatewayKeyAccess(k, false) } + : { name: "Make read-only", icon: EYE_GLYPH, run: () => gatewayKeyAccess(k, true), off: k.lan, why: k.lan ? t("The sharing key is given to agents, so it can't be read-only") : "" }, { name: "Rotate key", icon: ROTATE_GLYPH, run: () => askGatewayKey(k, true) }, { name: "Remove", icon: REMOVE_GLYPH, sep: true, run: () => askGatewayKey(k, false) }, ]); @@ -257,6 +262,19 @@ function gatewayKeyMore(k) { return more; } +const EYE_GLYPH = "M1.5 8S4 3.5 8 3.5 14.5 8 14.5 8 12 12.5 8 12.5 1.5 8 1.5 8zM8 9.9a1.9 1.9 0 1 0 0-3.8 1.9 1.9 0 0 0 0 3.8z"; +async function gatewayKeyAccess(k, readOnly) { + const out = await gatewayKeyAction("access-key", { key: k.id, readOnly }); + if (out) status(t(readOnly ? "{name} is read-only" : "{name} has full access", { name: k.name }), "ok"); +} +// a read-only key says so in its row, always: it reads quotas and usage +// and uses no model +function gatewayReadOnlyTag() { + const tag = el("span", "amodels key-readonly set", t("Read only")); + tag.title = t("This key only reads quotas and usage. It can't use models or MCP servers, or change anything."); + return tag; +} + function askGatewayKey(k, rotate) { const ed = el("div", "editor"); const head = el("div", "ehead"); diff --git a/internal/gui/tests/fixtures/caller-keys.cjs b/internal/gui/tests/fixtures/caller-keys.cjs index 3482e6e81..270bf9b91 100644 --- a/internal/gui/tests/fixtures/caller-keys.cjs +++ b/internal/gui/tests/fixtures/caller-keys.cjs @@ -80,7 +80,7 @@ function fixture(lang, theme, events, options = {}) { let key = keys.find((k) => k.id === lanKeyID); if (lan && (!key || body.newKey)) { if (!key) { - key = { id: "lan-key-" + (++serial), name: "Magpie" }; + key = { id: "lan-key-" + (++serial), name: "Magpie", lan: true }; lanKeyID = key.id; keys.push(key); } @@ -169,6 +169,7 @@ function fixture(lang, theme, events, options = {}) { if (action === "models-key") k.models = body.models?.length ? body.models : undefined; if (action === "accounts-key") k.accounts = body.accounts?.length ? body.accounts : undefined; if (action === "quotas-key") k.quotas = body.quotas || undefined; + if (action === "access-key") k.readOnly = body.readOnly || undefined; if (action === "copy-key") secret = k.id === lanKeyID ? lanSecret : secrets.get(k.id); return json({ keys, secret }); } diff --git a/internal/gui/tests/gateway-card.test.cjs b/internal/gui/tests/gateway-card.test.cjs index 3889179ad..74678a0df 100644 --- a/internal/gui/tests/gateway-card.test.cjs +++ b/internal/gui/tests/gateway-card.test.cjs @@ -13,8 +13,8 @@ const { fixture } = require("./fixtures/caller-keys.cjs"); // alone wasn't seen as a switch, so a key was removed and added again); // and Connect folded until it is opened. const WORDS = { - en: { share: "Share on local network", local: "This computer", lan: "Local network", more: "Key actions", off: "Disable key", on: "Enable key", rotate: "Rotate key", remove: "Remove" }, - zh: { share: "局域网共享", local: "本机", lan: "局域网", more: "密钥操作", off: "停用密钥", on: "启用密钥", rotate: "轮换密钥", remove: "移除" }, + en: { share: "Share on local network", local: "This computer", lan: "Local network", more: "Key actions", off: "Disable key", on: "Enable key", readOnly: "Make read-only", rotate: "Rotate key", remove: "Remove" }, + zh: { share: "局域网共享", local: "本机", lan: "局域网", more: "密钥操作", off: "停用密钥", on: "启用密钥", readOnly: "设为只读", rotate: "轮换密钥", remove: "移除" }, "zh-TW": { share: "區域網共享", local: "本機", lan: "區域網", more: "金鑰操作" }, ja: { share: "ローカルネットワークで共有", local: "このコンピュータ", lan: "ローカルネットワーク", more: "キーの操作" }, de: { share: "Im lokalen Netzwerk freigeben", local: "Dieser Computer", lan: "Lokales Netzwerk", more: "Schlüsselaktionen" }, @@ -95,9 +95,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const menu = page.locator(".row-menu"); await menu.waitFor(); const items = (await menu.getByRole("menuitem").allTextContents()).map((s) => s.trim()); - assert.equal(items.length, 3); - if (w.rotate) assert.deepEqual(items, [w.off, w.rotate, w.remove]); - assert.deepEqual(items, await page.evaluate(() => [t("Disable key"), t("Rotate key"), t("Remove")])); + assert.equal(items.length, 4); + if (w.rotate) assert.deepEqual(items, [w.off, w.readOnly, w.rotate, w.remove]); + assert.deepEqual(items, await page.evaluate(() => [t("Disable key"), t("Make read-only"), t("Rotate key"), t("Remove")])); // off from the menu, then on again: the key stays, only its switch moves await menu.getByRole("menuitem").first().click(); await menu.waitFor({ state: "detached" }); diff --git a/internal/gui/tests/gateway-key-readonly.test.cjs b/internal/gui/tests/gateway-key-readonly.test.cjs new file mode 100644 index 000000000..c85e81715 --- /dev/null +++ b/internal/gui/tests/gateway-key-readonly.test.cjs @@ -0,0 +1,96 @@ +// A read-only gateway key (Steven on Discord: an ESP32 desk display that +// polls quotas and usage and uses no model) is made so from its row's menu, +// says so in its row, and is given full access the same way; the sharing +// key, which magpie gives its own agents, can't be made read-only. +const assert = require("node:assert/strict"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { fixture } = require("./fixtures/caller-keys.cjs"); + +const words = { + en: { more: "Key actions", make: "Make read-only", full: "Give full access", tag: "Read only", made: "Server is read-only", given: "Server has full access", why: "The sharing key is given to agents, so it can't be read-only" }, + zh: { more: "密钥操作", make: "设为只读", full: "恢复完整权限", tag: "只读", made: "Server 已设为只读", given: "Server 已恢复完整权限", why: "共享密钥会交给 Agent 使用,不能设为只读" }, + "zh-TW": { more: "金鑰操作", make: "設為唯讀", full: "恢復完整權限", tag: "唯讀", made: "Server 已設為唯讀", given: "Server 已恢復完整權限", why: "共享金鑰會交給 Agent 使用,不能設為唯讀" }, + ja: { more: "キーの操作", make: "読み取り専用にする", full: "フルアクセスに戻す", tag: "読み取り専用", made: "Server を読み取り専用にしました", given: "Server をフルアクセスに戻しました", why: "共有キーはエージェントに渡されるため、読み取り専用にはできません" }, + de: { more: "Schlüsselaktionen", make: "Nur Lesezugriff geben", full: "Vollen Zugriff geben", tag: "Nur Lesen", made: "Server hat jetzt nur Lesezugriff", given: "Server hat wieder vollen Zugriff", why: "Der Freigabeschlüssel wird an Agenten gegeben und kann daher nicht auf Nur Lesen gestellt werden" }, +}; + +const keys = () => [ + { id: "laptop", name: "Laptop", masked: "sk-magpie-key-…111111", readOnly: true }, + { id: "server", name: "Server", masked: "sk-magpie-key-…222222" }, + { id: "magpie", name: "Magpie", masked: "sk-magpie-key-…444444", lan: true }, +]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const width of [1100, 420]) { + for (const [lang, w] of Object.entries(words)) { + test(`${engine} ${width} ${lang}: a gateway key is made read-only and given full access again`, 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, height: 700 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(6000); + const events = [], errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", fixture(lang, "light", events, { lan: true, keys: keys() })); + await page.goto("http://magpie.test/?view=gateway"); + await page.locator("#gatewayKeys .acc[data-key]").last().waitFor(); + const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`); + const tag = (id) => row(id).locator(".key-readonly"); + const item = (name) => page.locator(".row-menu [role=menuitem]").filter({ hasText: name }); + const menu = async (id) => { + await row(id).hover(); + await row(id).getByRole("button", { name: w.more, exact: true }).click(); + await page.locator(".row-menu").waitFor(); + }; + // read-only says so always, not only on hover; a full key says nothing + await page.mouse.move(0, 0); + assert.equal((await tag("laptop").textContent()).trim(), w.tag); + assert.ok((await tag("laptop").boundingBox()).width > 0, "the read-only tag is hidden"); + assert.ok((await tag("laptop").getAttribute("title")).length > 10, "the tag says what read-only means"); + assert.equal(await tag("server").count(), 0); + + const view = page.locator("#view-gateway"); + const scrolled = async () => [await view.evaluate((v) => v.scrollTop), await page.evaluate(() => window.scrollY)]; + const before = await scrolled(); + await menu("server"); + assert.equal(await item(w.full).count(), 0); + await item(w.make).click(); + await page.waitForFunction(() => !!document.querySelector('#gatewayKeys .acc[data-key="server"] .key-readonly')); + assert.deepEqual(events.filter((e) => e.action === "access-key").map((e) => e.body), [{ key: "server", readOnly: true }]); + assert.equal((await page.locator("#status").textContent()).trim(), w.made); + assert.equal((await tag("server").textContent()).trim(), w.tag); + + await menu("server"); + assert.equal(await item(w.make).count(), 0); + await item(w.full).click(); + await page.waitForFunction(() => !document.querySelector('#gatewayKeys .acc[data-key="server"] .key-readonly')); + assert.deepEqual(events.filter((e) => e.action === "access-key").at(-1).body, { key: "server", readOnly: false }); + assert.equal((await page.locator("#status").textContent()).trim(), w.given); + + // the sharing key: the item is there, off, and says why + await menu("magpie"); + const off = item(w.make); + assert.equal(await off.isDisabled(), true); + assert.equal((await off.locator(".rm-why").textContent()).trim(), w.why); + await page.keyboard.press("Escape"); + assert.equal(events.filter((e) => e.action === "access-key" && e.body.key === "magpie").length, 0); + assert.deepEqual(await scrolled(), before, "a click moved the page"); + + // the row still fits: nothing runs past the window's edge + const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(over <= 0, `the page scrolls sideways by ${over}px`); + const rowBox = await row("laptop").boundingBox(), b = await tag("laptop").boundingBox(); + assert.ok(b.x >= rowBox.x && b.x + b.width <= rowBox.x + rowBox.width + 1, "the tag runs out of its row"); + assert.equal(await page.locator("select").count(), 0, "no native select"); + // a border all round is the badge's own; a left one alone is a stripe + const borders = await page.locator("#gatewayKeys .key-readonly").evaluateAll((els) => els.map((e) => { + const c = getComputedStyle(e); + return { left: c.borderLeftStyle, right: c.borderRightStyle, leftColor: c.borderLeftColor, rightColor: c.borderRightColor }; + })); + assert.ok(borders.length > 0); + for (const b of borders) assert(b.left === "none" || (b.left === b.right && b.leftColor === b.rightColor), `a coloured left border: ${JSON.stringify(b)}`); + assert.deepEqual(errors, []); + }); + } + } +}