browser: the extension's key connects Magpie Browser and nothing else; own needs this computer; a key turned off closes its browser
483b131efwrote a full-access gateway key ("Magpie Browser") into the extension zip in Downloads. Anyone with a copy of the zip could use every model, MCP server and stat, and, with own = key == OwnBrowserKey(), could connect from another machine as this computer's own browser and receive this computer's agents' browser calls (page data out, prompt injection in). A keyed WebSocket also stayed open after its key was turned off. - access: Key.Browser / Identity.Browser. A browser key is also ReadOnly (so a magpie from before reads it as read-only) and never issues keys. access-key and issuer-key refuse it. ScopeBrowser(id) holds an existing key to the browser with the same secret; the sharing key is never scoped. Current(who) says whether a key Check took is still on by the same secret (Identity carries the secret's SHA-256, set on the legacy sharing-key fallback too, so a legacy caller's identity is the same before and after its migration). - gateway readOnlyGuard, the one place every route passes after the key is known: a browser key gets 403 gateway_key_browser_only on every pattern except GET /v1/magpie/browser/extension. - own: the key must be OwnBrowserKey() and the request local(r) (loopback peer, not proxied, not the page port). - browserConn keeps its key's identity. call() refuses a connection whose key is no longer Current, and a 5s watcher closes it (1008). - gui browserKey: a new key is made Browser; the recorded key is reused only once ScopeBrowser holds it. - GUI key row: "Browser only" tag (zh, zh-TW, ja, de), no access toggle. CLI prints "browser" access. agent gatewayTakes skips a browser key. Old data: an existing "Magpie Browser" key (OwnBrowserKey) is rescoped in place, same id and secret, when the gateway starts (ScopeOwnBrowserKey) and again on the next extension download. Installed extensions keep connecting with no reinstall. Every copy of an old zip loses models, MCP, stats and writes, and from another machine it is no longer this computer's browser. A user who downgrades reads the key as read-only. Keys a user made themselves are untouched. Regression, filed as #5529: Magpie in Docker with the host's Chrome reaches the container from 172.17.0.1, not loopback, so its agents no longer get the host's browser as their own. #5529 proposes pairing in its place. docs/reference.md and site docker pages (en, zh, ja) say so. Docs: docs/subsystems/gateway-routing.md (browser key), library.md (Download), docs/reference.md (Docker), site/public/docs{,/zh,/ja}/docker.html. Run on mote at origin/main2000ae439+ this change: - gofmt -l internal cmd: empty. - go vet darwin, GOOS=windows, GOOS=linux -tags nogui over access, gateway, gui, agent, cli: ok. - go test -tags nogui -count=1 -timeout 45m ./internal/gateway ./internal/gui ./internal/access ./internal/library ./internal/agent ./internal/cli: all ok except access's TestLegacyLANFallbackBeforeMigration, red from this change (the legacy fallback had no secret sum). Fixed here, then ./internal/access in full: ok. - GUI, 21 files (gateway-key-*, i18n-*, library-browser-*), chromium and webkit, every language: 332 of 334. The 2 reds fail the same on origin/main6f5d48ea0run alone: i18n-keys "a plugin's words are its own" (#5332, #5426, #5482) and gateway-key-models' 560px width check (#4081, commented). Rebased onto6f5d48ea0(remote_prove: a new POST /v1/magpie/prove route and edits to readonly.go and gateway.go, so not a -run rerun): gofmt -l empty, vet on all three ok, go test -count=1 ./internal/gateway ./internal/access ok, ./internal/gui -run Browser ok. A browser key gets 403 on the prove route too (TestBrowserKeyEveryRoute walks every pattern). Broken by hand, each red on mote: - guard off: TestBrowserKeyEveryRoute (/v1/ 200, /v1/models read_only not browser_only). - no migrate: TestBrowserKeyEveryRoute (/v1/models 200). - own without local(r): TestOwnBrowserKeyIsThisComputers. - no watcher: TestBrowserKeyOffClosesItsBrowser (stayed connected). - no Current check in call(): TestBrowserKeyOffClosesItsBrowser. - Current ignoring the secret: TestCurrent. - gui reuse without ScopeBrowser / new key without Browser: TestBrowserExtensionDownload (both). Not tried: a real Chrome with the real extension, a real Docker container, a real old key in a live HOME, the TUI. No CLI test for the "browser" access word. Tests reach no network (httptest, loopback only).
This commit is contained in:
+13
-6
@@ -3221,12 +3221,19 @@ extension*: a zip pointed at the page's own address (3430 hands the
|
||||
gateway's routes on), with a gateway key named **Magpie Browser** of its
|
||||
own, made once and reused while it is on. Unzip it and choose the folder
|
||||
with Load unpacked on `chrome://extensions`. An extension already loaded
|
||||
takes the address and a gateway key in its popup. The browser that
|
||||
connects with the page's Magpie Browser key is the container's own: its
|
||||
agents use it as they would one on loopback, and so does a caller of
|
||||
`/mcp/magpie/browser` from the host given that same key. A browser that
|
||||
connects with another key is that key's alone. A browser connecting from
|
||||
outside with no key, or from a web page's origin, is refused as before.
|
||||
takes the address and a gateway key in its popup. The Magpie Browser key
|
||||
connects the extension and nothing else: it reaches no model, MCP server
|
||||
or stats, so a copy of the zip left in Downloads spends nothing. A key a
|
||||
magpie from before made for the zip with full access is held so the next
|
||||
time the gateway starts. A browser is the container's own only when it
|
||||
connects from the container's own computer; the host's Chrome reaches the
|
||||
container from the bridge (172.17.0.1), so it is the key's alone, and the
|
||||
container's agents don't use it yet (#5529). To use it from the host, give
|
||||
the caller of `/mcp/magpie/browser` a key of its own with full access and
|
||||
connect the extension with that key. A browser that connects with another
|
||||
key is that key's alone. A browser connecting from outside with no key, or
|
||||
from a web page's origin, is refused as before. A keyed browser is let go
|
||||
once its key is turned off, removed or rotated.
|
||||
|
||||
The image has a `HEALTHCHECK`: `magpie healthcheck` exits 0 while the gateway
|
||||
answers on `MAGPIE_ADDR`, under `serve` and `web` alike, so `docker ps` shows
|
||||
|
||||
@@ -576,6 +576,30 @@ 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 browser key (`access.Key.Browser`) connects the Magpie Browser extension
|
||||
and nothing else. The GUI writes one into the extension's zip
|
||||
(`browserKey` in [`internal/gui/browser.go`](../../internal/gui/browser.go),
|
||||
`add-key` with `Browser`), and the zip lands in Downloads, so a copy of it
|
||||
can turn up anywhere. `readOnlyGuard` looks at it first: the one route it
|
||||
reaches is `GET /v1/magpie/browser/extension` (`browserKeyRoute`), and every
|
||||
other pattern, the browser MCP included, is refused 403
|
||||
`gateway_key_browser_only`, from loopback and from the network, however the
|
||||
key is sent. A browser key is `ReadOnly` too, so a magpie from before the
|
||||
field reads it as read-only, never as full. It can't be given full access
|
||||
or made an issuer (`access-key` and `issuer-key` refuse it), and an agent
|
||||
holding one isn't taken to go through magpie (`gatewayTakes`). The key a
|
||||
magpie from before made for the zip had full access. `ScopeOwnBrowserKey`,
|
||||
run as the gateway starts serving, and the next download
|
||||
(`access.ScopeBrowser`) hold the key recorded in `browser-key` to the
|
||||
extension with the same secret: the extension keeps connecting, and the
|
||||
copy in Downloads loses every model, MCP server and stat. Only a key the
|
||||
GUI made for the zip is recorded there, and the sharing key is never
|
||||
scoped. `TestBrowserKeyEveryRoute` in
|
||||
[`browser_key_test.go`](../../internal/gateway/browser_key_test.go) sends
|
||||
every pattern but the extension's, by each method, from loopback and from
|
||||
the network, and checks no upstream is reached; `TestScopeBrowser` in
|
||||
[`internal/access/browser_test.go`](../../internal/access/browser_test.go).
|
||||
|
||||
`POST /v1/magpie/quotas/codex-reset` (`Server.codexReset` in
|
||||
[`gateway.go`](../../internal/gateway/gateway.go), #3850) spends one of a
|
||||
Codex account's resets, which can't be undone, so its admission is
|
||||
|
||||
@@ -67,7 +67,7 @@ agents RTK, a CLI that cuts shell output down before the model reads it.
|
||||
- magpie's own MCP servers (`magpie-image`, `magpie-browser`, `magpie-web-search`, `magpie-vision`, and any `mcp …` run by a program named magpie) run this computer's magpie (#1439). `InstallServer` gives it magpie by full path (`update.Program`: the AppImage, not its mount; Homebrew's opt link, not the Cellar), and that path is right only on this computer. When the library is read, and after every change, `heal` points such a server whose program isn't on this computer (another system's path, a magpie moved out of Downloads, a bare `magpie`) at this magpie, so the agents and `CheckServers` get it; a magpie program that is here (another build) and a server run by any other program stay as they are. A carried library (`Collect`, for a backup or a WebDAV or S3 sync) names it as plain `magpie`, so two computers carry the same bundle and a sync doesn't write one's path over the other's; `Put` then reads it as that computer's magpie. [`self_here.go`](../../internal/library/self_here.go)
|
||||
- Magpie Web Search (`magpie-web-search`, `searchServer` in [`market.go`](../../internal/library/market.go)) is the featured, opt-in server for magpie's web search: `magpie mcp search` (`RunSearch` in [`browsermcp.go`](../../internal/browsermcp/browsermcp.go)) passes each stdio message to the gateway's `/mcp/magpie/web-search`, as `magpie mcp browser` does to its own path, with no browser session. Its sheet says each search goes where Settings › Models › Web search sends it. That page's MCP server row (`#searchMcpRow`) keeps the address to copy, and under its words Give agents Magpie Web Search… opens the sheet in the Library (`magpie.call("library", "server", "magpie-web-search")`), Turn on the Library when the Library is off, and nothing in gateway mode, as Settings › Images does for Magpie Image (lutra_fs on Discord: the search was in Settings and not in the Library; `search-mcp-library.test.cjs`). Each agent is given a 120-second tool timeout for it (`selfTimeout`). An agent in WSL is not given it directly, as with Magpie Browser; the MCP router serves it there.
|
||||
- Magpie Browser (`magpie-browser`) is opt-in, added with no agents, so the router offers it to none until one is ticked (an agent asked to use the browser reached for AppleScript instead). While its extension is connected (`GET /api/library/browser`, read again every 3 seconds while the row is shown) and no agent has it, its row in the MCP list asks which agents may use it, on a line of its own under the row's name, command and chips (from the name's left edge to the row's right one, the row's `lib-asking`), a button per agent whose chip can be clicked; a button clicks that chip, so the choice goes through `servers/agents` as a chip's does, and the row asks nothing more (`browserAsk` in [`client.js`](../../internal/gui/assets/plugins/library/client.js); `library-browser-ask.test.cjs`).
|
||||
- A page whose browser can't reach magpie's folders (magpie in a container, `gateway.InContainer`, or a page from another computer) is told so (`browserJSON.Away`), and the sheet's button is Download the extension: `POST /api/library/browser/extension` with the page's origin answers a zip of the extension (`browserext.Zip`) pointed at that origin, with the secret of the On gateway key named Magpie Browser, made by the first download (`browserKey`). It is a POST so a cross-site link can't mint a key. A browser connecting from elsewhere with a key belongs to it: the gateway's relay gives it only to sessions tagged `key:<id>/` (`browserOwner`, `keyedSession` in [`browser.go`](../../internal/gateway/browser.go)), which is what a remote caller's session is forced to. The key the page makes is recorded as this magpie's own browser's (`SetOwnBrowserKey`, a file in the settings folder), and a browser connecting with it serves this computer's sessions too (`browserConn.own`, `serves`); a record that can't be read names no key (`TestBrowserIsItsKeys`; `TestOwnBrowserKeyIsThisComputers`; `TestBrowserExtensionDownload`; `library-browser-away.test.cjs`).
|
||||
- A page whose browser can't reach magpie's folders (magpie in a container, `gateway.InContainer`, or a page from another computer) is told so (`browserJSON.Away`), and the sheet's button is Download the extension: `POST /api/library/browser/extension` with the page's origin answers a zip of the extension (`browserext.Zip`) pointed at that origin, with the secret of the On gateway key named Magpie Browser, made by the first download (`browserKey`). It is a POST so a cross-site link can't mint a key. The zip lands in Downloads, so the key is a browser key (`access.Key.Browser`): it opens the extension's socket and nothing else, no model, MCP server or stat (`readOnlyGuard`, see [gateway routing](gateway-routing.md); Gateway → Gateway keys tags it Browser only and offers no access to change). One a magpie from before made with full access is held so with the same secret as the gateway starts and on the next download (`ScopeOwnBrowserKey`, `access.ScopeBrowser`), so the extension keeps connecting. A browser connecting from elsewhere with a key belongs to it: the gateway's relay gives it only to sessions tagged `key:<id>/` (`browserOwner`, `keyedSession` in [`browser.go`](../../internal/gateway/browser.go)), which is what a remote caller's session is forced to. The key the page makes is recorded as this magpie's own browser's (`SetOwnBrowserKey`, a file in the settings folder), and a browser connecting with it serves this computer's sessions too when it connects from this computer (`browserConn.own`: the key and `local`, so not through a proxy or the page port; `serves`). From another computer, the Docker bridge's 172.17.0.1 included, the key proves nothing: a copy of the zip could connect a browser there, and this computer's agents' calls would go to it, so it serves only its key's sessions (#5529). A record that can't be read names no key. A keyed connection lasts while its key does: `watchKey` looks every 5 seconds and closes the socket once the key is turned off, removed, expired or rotated (`access.Current`), and a call looks first too (`TestBrowserIsItsKeys`; `TestOwnBrowserKeyIsThisComputers`; `TestBrowserKeyOffClosesItsBrowser`; `TestBrowserExtensionDownload`; `library-browser-away.test.cjs`; `gateway-key-readonly.test.cjs`).
|
||||
- Magpie Image Recognition (`magpie-vision`, `visionServer` in [`market.go`](../../internal/library/market.go)) is the featured, opt-in server for image recognition, beside Magpie Image and Magpie Web Search (matrix0487 on Discord: Discover had two of magpie's three): `magpie mcp vision` (`RunVision` in [`browsermcp.go`](../../internal/browsermcp/browsermcp.go)) passes each stdio message to the gateway's `/mcp/magpie/vision`, and makes `analyze_image`'s relative `image` path one in the agent's own folder on the way (`imageFrom`), since the gateway can't know where the agent runs; an absolute path, `~`, a URL or a drive goes as written. Its sheet says each image goes to Settings › Models › Images › Image recognition's model. That row has Give agents Magpie Image Recognition… (`libWay` in app.js, shared with Images' and Web search's links), Turn on the Library with the Library off, and nothing with recognition off or in gateway mode (`vision-mcp-library.test.cjs`). It gets the same 120-second tool timeout and the same WSL rule as Magpie Web Search.
|
||||
- Discover's featured list is the same with nothing set up: one of magpie's own whose model or search isn't there yet, or which Settings turned off, carries `unready` (`gateway.OwnUnready`, set by the GUI's `/api/library/market/servers`), shown as a Not set up yet badge on its card and the full reason in its sheet. It can still be added, since it answers once that is set up, and until then its tools answer with the same reason, so no agent is given a tool that fails without a word.
|
||||
- A carried library (`Collect`) has every file of each skill, its templates and other binaries included, up to `maxCarried` (16 MiB) a file and `maxCarriedAll` (32 MiB) in all, chosen smallest first across the skills (`readSkills`), so every skill's text goes before any big file. The total keeps a sealed backup under the 64 MiB a sync reads: the files are base64 twice in it. What is left out is named in `Left`, and `Put` keeps this computer's copy of such a file in the skill it puts (`keepLeft`). [`carry.go`](../../internal/library/carry.go)
|
||||
|
||||
@@ -160,6 +160,15 @@ type Key struct {
|
||||
// readOnlyRoutes and refuses it every other, every model, MCP and
|
||||
// write route among them. Off, the key may do what its other limits let it.
|
||||
ReadOnly bool `json:"readOnly,omitempty"`
|
||||
// Browser holds the key to connecting the Magpie Browser extension
|
||||
// (GET /v1/magpie/browser/extension) and nothing else: the key the
|
||||
// GUI writes into the extension's zip (gui's browserKey), which lands
|
||||
// in Downloads, where anyone who reads it has it. The gateway refuses
|
||||
// it every other route, every model and MCP server among them
|
||||
// (readOnlyGuard). Such a key is ReadOnly too, so a magpie from before
|
||||
// this field, which reads it as any other key, holds it to reading
|
||||
// stats rather than handing it every model.
|
||||
Browser bool `json:"browser,omitempty"`
|
||||
// Expires is when the key stops working (an issued key, IssueKey);
|
||||
// zero for one that doesn't. Prune removes it a while after.
|
||||
Expires time.Time `json:"expires,omitzero"`
|
||||
@@ -188,6 +197,12 @@ type Identity struct {
|
||||
Accounts []string
|
||||
Quotas bool
|
||||
ReadOnly bool
|
||||
// Browser: the key may connect the Magpie Browser extension and do
|
||||
// nothing else (Key.Browser).
|
||||
Browser bool
|
||||
// sum is the SHA-256 of the secret the request came with, so a
|
||||
// connection kept open can tell the key was rotated since (Current).
|
||||
sum [32]byte
|
||||
// Expires is when the key stops working, its issuer's expiry if
|
||||
// sooner; zero for never.
|
||||
Expires time.Time
|
||||
@@ -391,6 +406,9 @@ type Change struct {
|
||||
// ReadOnly is what "access-key" sets, and "add-key" gives the new key:
|
||||
// it may read stats and use no model (Key.ReadOnly).
|
||||
ReadOnly bool `json:"readOnly,omitempty"`
|
||||
// Browser is what "add-key" gives the new key: it may connect the
|
||||
// Magpie Browser extension alone (Key.Browser).
|
||||
Browser bool `json:"browser,omitempty"`
|
||||
// Issues is what "issuer-key" sets: the key may issue short-lived
|
||||
// keys under itself (Key.Issues).
|
||||
Issues bool `json:"issues,omitempty"`
|
||||
@@ -435,7 +453,7 @@ func Update(action string, in Change) (string, error) {
|
||||
}
|
||||
secret = Prefix + token
|
||||
}
|
||||
keys = append(keys, Key{ID: id, Name: name, Secret: secret, ReadOnly: in.ReadOnly})
|
||||
keys = append(keys, Key{ID: id, Name: name, Secret: secret, ReadOnly: in.ReadOnly || in.Browser, Browser: in.Browser})
|
||||
} else {
|
||||
i := slices.IndexFunc(keys, func(k Key) bool { return k.ID == in.Key })
|
||||
if i < 0 {
|
||||
@@ -549,6 +567,9 @@ func Update(action string, in Change) (string, error) {
|
||||
keys[i].Quotas = in.Quotas
|
||||
case "issuer-key":
|
||||
// may issue short-lived keys under itself (POST /v1/magpie/keys)
|
||||
if in.Issues && keys[i].Browser {
|
||||
return "", errors.New("This key is the Magpie Browser extension's, which can't issue keys: let another key of yours issue them")
|
||||
}
|
||||
if in.Issues && (keys[i].Issuer != "" || !keys[i].Expires.IsZero()) {
|
||||
return "", errors.New("An issued key can't issue keys of its own: let a key of yours issue them")
|
||||
}
|
||||
@@ -560,6 +581,11 @@ func Update(action string, in Change) (string, error) {
|
||||
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")
|
||||
}
|
||||
// the extension's key is in a zip in Downloads: it connects the
|
||||
// extension and nothing else, whatever access is asked
|
||||
if keys[i].Browser {
|
||||
return "", errors.New("This key is the Magpie Browser extension's: it connects the extension and nothing else. Add another key for models or stats")
|
||||
}
|
||||
keys[i].ReadOnly = in.ReadOnly
|
||||
case "on-key", "off-key":
|
||||
keys[i].Off = action == "off-key"
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// The key a magpie from before made for the Magpie Browser extension had
|
||||
// full access. ScopeBrowser holds it to the extension: the secret is the
|
||||
// same, so the extension keeps connecting, read-only for a magpie from
|
||||
// before this one, and it can neither be given full access back nor issue
|
||||
// keys. A key made for the extension now is so from the start. The sharing
|
||||
// key is never held so, and a key that isn't there says so.
|
||||
func TestScopeBrowser(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
secret, err := Update("add-key", Change{Name: "Magpie Browser"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
who, ok := Authenticate(secret)
|
||||
if !ok || who.Browser || who.ReadOnly {
|
||||
t.Fatal("a full key as made before:", who, ok)
|
||||
}
|
||||
if _, err := Update("issuer-key", Change{Key: who.KeyID, Issues: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ScopeBrowser(who.KeyID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, ok := Authenticate(secret)
|
||||
if !ok || !after.Browser || !after.ReadOnly || after.Issues || after.KeyID != who.KeyID {
|
||||
t.Fatal("held to the browser:", after, ok)
|
||||
}
|
||||
// what a magpie from before reads: read-only
|
||||
b, err := os.ReadFile(Path())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var old []struct {
|
||||
ID string
|
||||
ReadOnly bool `json:"readOnly"`
|
||||
Issues bool `json:"issues"`
|
||||
}
|
||||
if json.Unmarshal(b, &old) != nil || len(old) != 1 || !old[0].ReadOnly || old[0].Issues {
|
||||
t.Fatalf("a magpie from before reads %s", b)
|
||||
}
|
||||
if err := ScopeBrowser(who.KeyID); err != nil {
|
||||
t.Fatal("twice:", err)
|
||||
}
|
||||
for _, c := range []struct {
|
||||
action string
|
||||
in Change
|
||||
}{
|
||||
{"access-key", Change{Key: who.KeyID}},
|
||||
{"access-key", Change{Key: who.KeyID, ReadOnly: true}},
|
||||
{"issuer-key", Change{Key: who.KeyID, Issues: true}},
|
||||
} {
|
||||
if _, err := Update(c.action, c.in); err == nil {
|
||||
t.Errorf("%s %+v on the browser key", c.action, c.in)
|
||||
}
|
||||
}
|
||||
if k, _ := Authenticate(secret); !k.Browser || !k.ReadOnly {
|
||||
t.Fatal("the browser key let go:", k)
|
||||
}
|
||||
|
||||
made, err := Update("add-key", Change{Name: "Magpie Browser 2", Browser: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if k, ok := Authenticate(made); !ok || !k.Browser || !k.ReadOnly || k.Issues {
|
||||
t.Fatal("a browser key made now:", k, ok)
|
||||
}
|
||||
|
||||
if err := ScopeBrowser("no-such-key"); !errors.Is(err, ErrNoKey) {
|
||||
t.Fatal("a key that isn't there:", err)
|
||||
}
|
||||
if err := ConfigureLAN(true, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
lan := settings.Load().LANKeyID
|
||||
if lan == "" {
|
||||
t.Fatal("no sharing key")
|
||||
}
|
||||
if err := ScopeBrowser(lan); err == nil {
|
||||
t.Fatal("the sharing key was held to the browser")
|
||||
}
|
||||
if k, ok := Authenticate(LANSecret()); !ok || k.Browser || k.ReadOnly {
|
||||
t.Fatal("the sharing key changed:", k, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// Current says whether the key an identity was read from still lets it in:
|
||||
// not once it is turned off, removed or expired, or once its secret is
|
||||
// rotated (the old secret no longer does).
|
||||
func TestCurrent(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
var secrets []string
|
||||
for _, name := range []string{"Off", "Removed", "Rotated", "Kept"} {
|
||||
s, err := Update("add-key", Change{Name: name})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secrets = append(secrets, s)
|
||||
}
|
||||
var who []Identity
|
||||
for _, s := range secrets {
|
||||
w, err := Check(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !Current(w) {
|
||||
t.Fatal("a key that is on isn't current:", w.KeyName)
|
||||
}
|
||||
who = append(who, w)
|
||||
}
|
||||
if Current(Identity{KeyID: who[0].KeyID}) {
|
||||
t.Fatal("an identity read from no secret is current")
|
||||
}
|
||||
if _, err := Update("off-key", Change{Key: who[0].KeyID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Update("remove-key", Change{Key: who[1].KeyID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rotated, err := Update("rotate-key", Change{Key: who[2].KeyID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, want := range []bool{false, false, false, true} {
|
||||
if got := Current(who[i]); got != want {
|
||||
t.Errorf("%s: Current = %v, want %v", who[i].KeyName, got, want)
|
||||
}
|
||||
}
|
||||
if w, err := Check(rotated); err != nil || !Current(w) {
|
||||
t.Fatal("the rotated secret:", err)
|
||||
}
|
||||
if _, err := Update("on-key", Change{Key: who[0].KeyID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !Current(who[0]) {
|
||||
t.Fatal("a key turned on again isn't current")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package access
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -239,7 +240,9 @@ func Check(secret string) (Identity, error) {
|
||||
// fall back after either durable marker exists, or to a revoked mirror.
|
||||
if s.LAN && s.LANKeyID == "" && s.LANKey != "" && !strings.HasPrefix(s.LANKey, revokedLANPrefix) && !slices.ContainsFunc(keys, func(k Key) bool { return k.LAN }) && subtle.ConstantTimeCompare([]byte(secret), []byte(s.LANKey)) == 1 {
|
||||
k := legacyLANKey(s.LANKey)
|
||||
return Identity{KeyID: k.ID, KeyName: k.Name, Default: true}, nil
|
||||
// sum as Check gives the same key once migrated, so the
|
||||
// caller's identity is one before and after
|
||||
return Identity{KeyID: k.ID, KeyName: k.Name, Default: true, sum: sha256.Sum256([]byte(k.Secret))}, nil
|
||||
}
|
||||
return Identity{}, errUnknown
|
||||
}
|
||||
@@ -251,12 +254,73 @@ func Check(secret string) (Identity, error) {
|
||||
if k.expired(now) {
|
||||
return Identity{}, &Refused{Why: fmt.Sprintf("the gateway key %q expired at %s: ask for a new one", k.Name, k.Expires.UTC().Format(time.RFC3339))}
|
||||
}
|
||||
return identityOf(k, keys, now)
|
||||
who, err := identityOf(k, keys, now)
|
||||
who.sum = sha256.Sum256([]byte(k.Secret))
|
||||
return who, err
|
||||
}
|
||||
|
||||
// Current: who, a key Check took earlier, is still one it takes now, by
|
||||
// the same secret: not turned off, removed, expired, rotated, nor
|
||||
// bounded by an issuer that no longer lets it in. A connection a key
|
||||
// opened (Magpie Browser's WebSocket) is closed once it isn't. false
|
||||
// for no key, and when the store can't be read.
|
||||
func Current(who Identity) bool {
|
||||
if who.KeyID == "" {
|
||||
return false
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
keys, err := load()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
i := slices.IndexFunc(keys, func(k Key) bool { return k.ID == who.KeyID })
|
||||
if i < 0 {
|
||||
return false // the legacy sharing key not yet in the store is never a browser's
|
||||
}
|
||||
k := keys[i]
|
||||
if k.Off || k.Secret == "" || k.expired(Now()) || sha256.Sum256([]byte(k.Secret)) != who.sum {
|
||||
return false
|
||||
}
|
||||
_, err = identityOf(k, keys, Now())
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// ErrNoKey: there is no gateway key with that id.
|
||||
var ErrNoKey = errors.New("Key not found")
|
||||
|
||||
// ScopeBrowser holds the key id to connecting the Magpie Browser
|
||||
// extension alone (Key.Browser), read-only for a magpie from before
|
||||
// that, and unable to issue keys. It is for the key a magpie from before
|
||||
// the scope made for the extension (gui's browserKey), which could use
|
||||
// every model and was written into a zip in Downloads: the extension
|
||||
// goes on connecting with it, and the copy in the zip loses the rest.
|
||||
// The sharing key, which magpie gives its own agents, is never scoped.
|
||||
func ScopeBrowser(id string) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
keys, err := load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i := slices.IndexFunc(keys, func(k Key) bool { return k.ID == id })
|
||||
if i < 0 {
|
||||
return ErrNoKey
|
||||
}
|
||||
k := &keys[i]
|
||||
if k.LAN || k.ID == settings.Load().LANKeyID {
|
||||
return errors.New("The sharing key is given to magpie's own agents, so it can't be held to Magpie Browser")
|
||||
}
|
||||
if k.Browser && k.ReadOnly && !k.Issues {
|
||||
return nil
|
||||
}
|
||||
k.Browser, k.ReadOnly, k.Issues = true, true, false
|
||||
return save(keys)
|
||||
}
|
||||
|
||||
// identityOf is who k is, folded into its issuer when it has one.
|
||||
func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
|
||||
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), AccountModels: len(k.Models) == 0 && len(k.Accounts) > 0, Accounts: k.Accounts, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Expires: k.Expires, Issues: k.Issues && k.Issuer == ""}
|
||||
who := Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: HeldModels(k.Models, k.Accounts), AccountModels: len(k.Models) == 0 && len(k.Accounts) > 0, Accounts: k.Accounts, Quotas: k.Quotas, ReadOnly: k.ReadOnly, Browser: k.Browser, Expires: k.Expires, Issues: k.Issues && k.Issuer == "" && !k.Browser}
|
||||
// the default key as Default tells it: marked LAN, or the id the
|
||||
// settings name (settings read only for an unmarked key)
|
||||
who.Default = k.LAN || (k.ID != "" && settings.Load().LANKeyID == k.ID)
|
||||
@@ -277,6 +341,7 @@ func identityOf(k Key, keys []Key, now time.Time) (Identity, error) {
|
||||
}
|
||||
who.Accounts = foldAccounts(who.Accounts, p.Accounts)
|
||||
who.ReadOnly = who.ReadOnly || p.ReadOnly
|
||||
who.Browser = who.Browser || p.Browser
|
||||
who.Quotas = who.Quotas && p.Quotas
|
||||
if !p.Expires.IsZero() && (who.Expires.IsZero() || p.Expires.Before(who.Expires)) {
|
||||
who.Expires = p.Expires
|
||||
|
||||
@@ -75,8 +75,10 @@ func ourKey(k string) bool {
|
||||
// (#1332). A key of another magpie's, which this gateway would refuse, is
|
||||
// not.
|
||||
func gatewayTakes(k string) bool {
|
||||
_, ok := access.Authenticate(k)
|
||||
return ok
|
||||
who, ok := access.Authenticate(k)
|
||||
// Magpie Browser's key reaches no model, so an agent holding it
|
||||
// doesn't go through magpie
|
||||
return ok && !who.Browser
|
||||
}
|
||||
|
||||
// gatewayKey says want is a key magpie gives an agent for its gateway:
|
||||
|
||||
@@ -578,8 +578,12 @@ 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".
|
||||
// accessWord is a key's access as the list says it: "browser" (Magpie
|
||||
// Browser's, access.Key.Browser), "read-only" or "full".
|
||||
func accessWord(k access.Key) string {
|
||||
if k.Browser {
|
||||
return "browser"
|
||||
}
|
||||
if k.ReadOnly {
|
||||
return "read-only"
|
||||
}
|
||||
@@ -614,7 +618,9 @@ func gatewayKeyAccess(out io.Writer, args []string) error {
|
||||
return fmt.Errorf("Key not found")
|
||||
}
|
||||
k := keys[i]
|
||||
if k.ReadOnly {
|
||||
if k.Browser {
|
||||
_, err = fmt.Fprintf(out, "%s: Magpie Browser's, it connects the extension and uses no model, MCP server, stats or write\n", k.Name)
|
||||
} else 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)
|
||||
|
||||
+97
-18
@@ -42,6 +42,13 @@ import (
|
||||
// agents don't. A caller on another computer with no key, or with another
|
||||
// key, is never handed a browser. Keyed callers' sessions are the key's
|
||||
// own ("key:<id>/…", browserOwner), so a key names only its own browsers.
|
||||
//
|
||||
// The key the GUI writes into the extension's zip (OwnBrowserKey) is a
|
||||
// browser key (access.Key.Browser): it opens BrowserExtensionPath and
|
||||
// nothing else (readOnlyGuard), since the zip sits in Downloads and a copy
|
||||
// of it must not spend the user's subscriptions. A browser connected with
|
||||
// it is this computer's too only when it connected from this computer
|
||||
// (local); a connection lives only while its key is on (watchKey).
|
||||
|
||||
// BrowserMCPPath is where the browser MCP server is served.
|
||||
const BrowserMCPPath = "/mcp/magpie/browser"
|
||||
@@ -83,9 +90,17 @@ type browserConn struct {
|
||||
// key is the gateway key the browser connected with, whose callers
|
||||
// use it; "" for this computer's, connected over loopback
|
||||
key string
|
||||
// who is that key as it was when the browser connected: once it
|
||||
// isn't Current (turned off, removed, expired or rotated) the
|
||||
// connection is closed (watchKey, call)
|
||||
who access.Identity
|
||||
// own: key is the one this magpie's own page made for the user's own
|
||||
// browser (OwnBrowserKey), so this computer's callers use it too, as
|
||||
// they do one on loopback
|
||||
// browser (OwnBrowserKey) and the browser connected from this
|
||||
// computer (local), so this computer's callers use it too, as they
|
||||
// do one on loopback. From elsewhere the key alone is no proof: it is
|
||||
// in a zip in Downloads, and whoever holds a copy could otherwise
|
||||
// connect a browser of theirs and be handed this computer's agents'
|
||||
// calls (their pages read, and pages of theirs fed back).
|
||||
own bool
|
||||
since time.Time
|
||||
wmu sync.Mutex
|
||||
@@ -192,6 +207,22 @@ func SetOwnBrowserKey(id string) error {
|
||||
return os.Rename(tmp, ownBrowserKeyFile())
|
||||
}
|
||||
|
||||
// ScopeOwnBrowserKey makes the key the extension's zip was given
|
||||
// (OwnBrowserKey) a browser key, if a magpie from before browser keys made
|
||||
// it a full-access one: the extension, which holds the same secret, keeps
|
||||
// connecting, and a copy of the zip left in Downloads no longer reaches a
|
||||
// model, MCP server or stats. Only a key the GUI made for the zip is
|
||||
// recorded there (gui's browserKey), so no key the user made is touched.
|
||||
func ScopeOwnBrowserKey() {
|
||||
id := OwnBrowserKey()
|
||||
if id == "" {
|
||||
return
|
||||
}
|
||||
if err := access.ScopeBrowser(id); err != nil && !errors.Is(err, access.ErrNoKey) {
|
||||
log.Printf("Magpie Browser's gateway key %s: can't make it a browser key: %v", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// forSession is the browser a session's calls go to: the one it picked
|
||||
// while that one is connected, else the last of its owner's to connect.
|
||||
func (b *browserRelay) forSession(session string) *browserConn {
|
||||
@@ -301,6 +332,12 @@ func (b *browserRelay) call(ctx context.Context, session, tool string, args json
|
||||
if c == nil {
|
||||
return nil, browserAway(session)
|
||||
}
|
||||
if c.key != "" && !access.Current(c.who) {
|
||||
// its key was turned off since watchKey last looked: handed nothing
|
||||
b.remove(c)
|
||||
go c.drop()
|
||||
return nil, browserAway(session)
|
||||
}
|
||||
b.mu.Lock()
|
||||
if b.pending == nil {
|
||||
b.pending = map[string]chan json.RawMessage{}
|
||||
@@ -344,31 +381,68 @@ func browserAway(session string) error {
|
||||
}
|
||||
|
||||
// browserExtensionKey is the gateway key the extension's request r comes
|
||||
// with ("" for one on this computer), and whether it is let connect: from
|
||||
// this computer over loopback, or with a gateway key that is on.
|
||||
func browserExtensionKey(r *http.Request) (string, bool) {
|
||||
// with (no KeyID for one on this computer), and whether it is let
|
||||
// connect: from this computer over loopback, or with a gateway key that
|
||||
// is on and may connect a browser (one with full access, or the
|
||||
// extension's own, Key.Browser; never a read-only one).
|
||||
func browserExtensionKey(r *http.Request) (access.Identity, bool) {
|
||||
if r.Header.Get("Origin") != browserext.Origin {
|
||||
return "", false
|
||||
return access.Identity{}, false
|
||||
}
|
||||
if local(r) && loopbackHost(r.Host) {
|
||||
return "", true
|
||||
return access.Identity{}, true
|
||||
}
|
||||
if id := access.Caller(r.Context()).KeyID; id != "" {
|
||||
return id, true
|
||||
}
|
||||
// a key lanGuard didn't read: the gateway isn't on the network, so
|
||||
// this is a container's published port or a proxy on this computer
|
||||
for _, k := range callerKeys(r) {
|
||||
if c, ok := access.Authenticate(k); ok && c.KeyID != "" {
|
||||
return c.KeyID, true
|
||||
who := access.Caller(r.Context())
|
||||
if who.KeyID == "" {
|
||||
// a key lanGuard didn't read: the gateway isn't on the network,
|
||||
// so this is a container's published port or a proxy on this
|
||||
// computer
|
||||
for _, k := range callerKeys(r) {
|
||||
if c, err := access.Check(k); err == nil && c.KeyID != "" {
|
||||
who = c
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
if who.KeyID == "" || (who.ReadOnly && !who.Browser) {
|
||||
return access.Identity{}, false
|
||||
}
|
||||
return who, true
|
||||
}
|
||||
|
||||
// browserKeyCheck is how often a browser connected with a key looks
|
||||
// whether the key is still on (watchKey).
|
||||
var browserKeyCheck = 5 * time.Second
|
||||
|
||||
// watchKey closes c's connection once the key it connected with is no
|
||||
// longer Current: turned off, removed, expired or rotated. A browser
|
||||
// call looks too (call), so none is handed to it in between.
|
||||
func (c *browserConn) watchKey(ctx context.Context) {
|
||||
t := time.NewTicker(browserKeyCheck)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
if !access.Current(c.who) {
|
||||
c.drop()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// drop closes the connection of a browser whose key is no longer on.
|
||||
func (c *browserConn) drop() {
|
||||
log.Printf("Magpie Browser connected with gateway key %s: the key is no longer on, so the connection is closed", c.key)
|
||||
c.c.Close(websocket.StatusPolicyViolation, "the gateway key this browser connected with is no longer on")
|
||||
}
|
||||
|
||||
// browserExtension takes the extension's WebSocket.
|
||||
func (s *Server) browserExtension(w http.ResponseWriter, r *http.Request) {
|
||||
key, ok := browserExtensionKey(r)
|
||||
who, ok := browserExtensionKey(r)
|
||||
key := who.KeyID
|
||||
if !ok {
|
||||
http.Error(w, "only the Magpie Browser extension connects here: on this computer, or with a gateway key", http.StatusForbidden)
|
||||
return
|
||||
@@ -379,9 +453,14 @@ func (s *Server) browserExtension(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
ws.SetReadLimit(64 << 20) // a full-page screenshot
|
||||
c := &browserConn{c: ws, key: key, own: key != "" && key == OwnBrowserKey(), since: time.Now()}
|
||||
c := &browserConn{c: ws, key: key, who: who, own: key != "" && local(r) && key == OwnBrowserKey(), since: time.Now()}
|
||||
ctx := r.Context()
|
||||
defer ws.CloseNow()
|
||||
if key != "" {
|
||||
watch, stop := context.WithCancel(ctx)
|
||||
defer stop()
|
||||
go c.watchKey(watch)
|
||||
}
|
||||
added := false
|
||||
defer func() {
|
||||
if added {
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// The key magpie writes into the Magpie Browser extension's zip lands in
|
||||
// Downloads, so a copy of it can turn up anywhere. It is a browser key: it
|
||||
// opens the extension's socket and every other route the router has (every
|
||||
// model, count_tokens, a WebSocket's upgrade, every MCP server, the stats,
|
||||
// a plugin's backend and every write) is refused it, from this computer and
|
||||
// from another, however the key is sent, and no upstream is reached. The
|
||||
// key a magpie from before made with full access is held so too
|
||||
// (ScopeOwnBrowserKey), and stays so.
|
||||
func TestBrowserKeyEveryRoute(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, "Magpie Browser", "Laptop")
|
||||
ext, full := secrets[0], secrets[1]
|
||||
if err := SetOwnBrowserKey(keys[0].ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
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
|
||||
if secret != "" {
|
||||
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()
|
||||
}
|
||||
// a magpie from before gave it full access: it reached a model
|
||||
if c, b := do("POST", "/v1/chat/completions", "192.168.1.9:5000", ext); c != 200 {
|
||||
t.Fatal("the extension's key before it is held:", c, b)
|
||||
}
|
||||
ScopeOwnBrowserKey()
|
||||
ScopeOwnBrowserKey() // twice is once
|
||||
reached.Store(0)
|
||||
|
||||
refused := func(from, what string, c int, b string) {
|
||||
t.Helper()
|
||||
if c != http.StatusForbidden || !strings.Contains(b, BrowserKeyCode) {
|
||||
t.Errorf("browser key from %s: %s: %d %.200s", from, what, c, b)
|
||||
}
|
||||
}
|
||||
mux := New().routes()
|
||||
if !slices.Contains(mux.patterns, browserKeyRoute) {
|
||||
t.Fatalf("the router has no %q", browserKeyRoute)
|
||||
}
|
||||
for _, from := range []string{"192.168.1.9:5000", "127.0.0.1:5000"} {
|
||||
for _, p := range mux.patterns {
|
||||
if p == browserKeyRoute {
|
||||
continue
|
||||
}
|
||||
for _, mp := range requestsFor(p) {
|
||||
c, b := do(mp[0], mp[1], from, ext)
|
||||
refused(from, mp[0]+" "+mp[1]+" ("+p+")", c, b)
|
||||
}
|
||||
}
|
||||
// the key as each client sends it
|
||||
c, b := do("POST", "/v1/messages", from, "", "x-api-key", ext)
|
||||
refused(from, "x-api-key on /v1/messages", c, b)
|
||||
c, b = do("POST", "/v1beta/models/m1:generateContent?key="+ext, from, "")
|
||||
refused(from, "?key= on generateContent", c, b)
|
||||
c, b = do("POST", "/v1/chat/completions?key="+ext, from, "")
|
||||
refused(from, "?key= on /v1/chat/completions", c, b)
|
||||
for _, path := range []string{"/v1/responses", "/responses"} {
|
||||
c, b := do("GET", path, from, ext, "Upgrade", "websocket", "Connection", "Upgrade", "Sec-WebSocket-Version", "13", "Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
|
||||
refused(from, "a WebSocket on "+path, c, b)
|
||||
}
|
||||
if c, b := do("POST", "/v1//chat/completions", from, ext); c == 200 || strings.Contains(b, `"choices"`) {
|
||||
t.Errorf("browser key from %s: an unclean chat path: %d %.200s", from, c, b)
|
||||
}
|
||||
if n := reached.Load(); n != 0 {
|
||||
t.Fatalf("browser key from %s: the upstream was reached %d times", from, n)
|
||||
}
|
||||
// the extension's own route is let through to its handler, which
|
||||
// takes a WebSocket alone
|
||||
if c, b := do("GET", BrowserExtensionPath, from, ext, "Origin", "chrome-extension://x"); strings.Contains(b, BrowserKeyCode) {
|
||||
t.Errorf("browser key from %s: the extension's route: %d %.200s", from, c, b)
|
||||
}
|
||||
}
|
||||
|
||||
// it stays held: neither given full access nor made an issuer, and a
|
||||
// key it would issue doesn't exist to be issued
|
||||
if _, err := access.Update("access-key", access.Change{Key: keys[0].ID}); err == nil {
|
||||
t.Error("the browser key was given full access")
|
||||
}
|
||||
if _, err := access.Update("issuer-key", access.Change{Key: keys[0].ID, Issues: true}); err == nil {
|
||||
t.Error("the browser key was made an issuer")
|
||||
}
|
||||
if c, b := do("POST", "/v1/chat/completions", "192.168.1.9:5000", ext); c == 200 {
|
||||
t.Error("the browser key reached a model after:", c, b)
|
||||
}
|
||||
if c, b := do("POST", "/v1/chat/completions", "192.168.1.9:5000", full); c != 200 {
|
||||
t.Error("the other key's request:", c, b)
|
||||
}
|
||||
}
|
||||
|
||||
// A browser connected with a gateway key is let go once the key isn't on:
|
||||
// turned off, rotated or removed. Its socket is closed (watchKey), and a
|
||||
// call in the moment before that is handed to no browser (call): least of
|
||||
// all to this computer's agents' when the key was the own browser's.
|
||||
func TestBrowserKeyOffClosesItsBrowser(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
t.Setenv("MAGPIE_PUBLIC_URL", "")
|
||||
t.Setenv("MAGPIE_TRUST_PROXY", "")
|
||||
was := browserKeyCheck
|
||||
t.Cleanup(func() { browserKeyCheck = was })
|
||||
s := New()
|
||||
const testPeer, testHost = "X-Test-Peer", "X-Test-Host"
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if p := r.Header.Get(testPeer); p != "" {
|
||||
r.RemoteAddr, r.Host = p, r.Header.Get(testHost)
|
||||
r.Header.Del(testPeer)
|
||||
r.Header.Del(testHost)
|
||||
}
|
||||
lanGuard(s.Handler()).ServeHTTP(w, r)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
keys, secrets := newCaller(t, "Off", "Rotated", "Removed", "Own")
|
||||
if err := SetOwnBrowserKey(keys[3].ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ScopeOwnBrowserKey()
|
||||
away := http.Header{testPeer: {"172.17.0.1:40000"}, testHost: {"192.0.2.1:3425"}}
|
||||
reply := func(_, _, _ string, _ map[string]any) any {
|
||||
return map[string]any{"content": []any{map[string]any{"type": "text", "text": "tabs"}}}
|
||||
}
|
||||
count := func(id string) int { return len(s.browser.all(keyedSession(id, "x"))) }
|
||||
waitFor := func(what string, ok func() bool) {
|
||||
t.Helper()
|
||||
for deadline := time.Now().Add(10 * time.Second); !ok(); time.Sleep(5 * time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal(what)
|
||||
}
|
||||
}
|
||||
}
|
||||
h := lanGuard(s.Handler())
|
||||
tabs := func(addr string, hdr ...string) (string, bool) {
|
||||
t.Helper()
|
||||
m := readImageReply(t, browserPost(h, addr, imageToolCall("browser_tabs", map[string]any{}), hdr...))
|
||||
var all []string
|
||||
for _, c := range m.Result.Content {
|
||||
all = append(all, c.Text)
|
||||
}
|
||||
return strings.Join(all, "\n"), m.Result.IsError
|
||||
}
|
||||
|
||||
// the call looks for itself: the watch is too slow to see it
|
||||
browserKeyCheck = time.Hour
|
||||
fakeExtensionWith(t, srv.URL, secrets[3], http.Header{testPeer: {"127.0.0.1:40002"}, testHost: {"host.docker.internal:3425"}}, "Chrome/141", reply)
|
||||
waitFor("the own browser never connected", func() bool { return count(keys[3].ID) == 1 })
|
||||
if got, bad := tabs("127.0.0.1:5000", BrowserSessionHeader, "s1"); bad || got != "tabs" {
|
||||
t.Fatalf("this computer's caller: %q", got)
|
||||
}
|
||||
if _, err := access.Update("off-key", access.Change{Key: keys[3].ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got, bad := tabs("127.0.0.1:5000", BrowserSessionHeader, "s1"); !bad || got == "tabs" {
|
||||
t.Fatalf("this computer's caller used the browser of a key turned off: %q", got)
|
||||
}
|
||||
waitFor("the own browser stayed connected after its key was off", func() bool { return count(keys[3].ID) == 0 })
|
||||
|
||||
// rotated: the browser holds the old secret, and a caller with the
|
||||
// new one isn't handed it
|
||||
fakeExtensionWith(t, srv.URL, secrets[1], away, "Chrome/141", reply)
|
||||
waitFor("the rotated key's browser never connected", func() bool { return count(keys[1].ID) == 1 })
|
||||
fresh2, err := access.Update("rotate-key", access.Change{Key: keys[1].ID})
|
||||
if err != nil || fresh2 == "" {
|
||||
t.Fatal(fresh2, err)
|
||||
}
|
||||
if got, bad := tabs("172.17.0.1:40000", "Authorization", "Bearer "+fresh2, BrowserSessionHeader, "s1"); !bad || got == "tabs" {
|
||||
t.Fatalf("the new secret's caller used the browser the old one connected: %q", got)
|
||||
}
|
||||
|
||||
// the watch: each is let go with no call made
|
||||
browserKeyCheck = 20 * time.Millisecond
|
||||
fakeExtensionWith(t, srv.URL, secrets[0], away, "Chrome/141", reply)
|
||||
fakeExtensionWith(t, srv.URL, secrets[2], away, "Chrome/141", reply)
|
||||
fakeExtensionWith(t, srv.URL, fresh2, away, "Chrome/141", reply)
|
||||
waitFor("the keyed browsers never connected", func() bool {
|
||||
return count(keys[0].ID) == 1 && count(keys[2].ID) == 1 && count(keys[1].ID) >= 1
|
||||
})
|
||||
time.Sleep(100 * time.Millisecond) // several looks: a key that is on stays connected
|
||||
if count(keys[0].ID) != 1 || count(keys[2].ID) != 1 || count(keys[1].ID) != 1 {
|
||||
t.Fatalf("a browser whose key is on was let go: off %d, removed %d, rotated %d", count(keys[0].ID), count(keys[2].ID), count(keys[1].ID))
|
||||
}
|
||||
if _, err := access.Update("off-key", access.Change{Key: keys[0].ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor("the browser stayed connected after its key was turned off", func() bool { return count(keys[0].ID) == 0 })
|
||||
if _, err := access.Update("remove-key", access.Change{Key: keys[2].ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor("the browser stayed connected after its key was removed", func() bool { return count(keys[2].ID) == 0 })
|
||||
if _, err := access.Update("rotate-key", access.Change{Key: keys[1].ID}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitFor("the browser stayed connected after its key was rotated", func() bool { return count(keys[1].ID) == 0 })
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/coder/websocket"
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/browserext"
|
||||
)
|
||||
|
||||
@@ -457,8 +459,13 @@ func TestBrowserOwner(t *testing.T) {
|
||||
}
|
||||
|
||||
// The browser connected with the key magpie's own page made for it
|
||||
// (OwnBrowserKey) is this computer's too, as magpie in a container has no
|
||||
// browser on loopback; one connected with another key isn't.
|
||||
// (OwnBrowserKey) is this computer's too when it connected from this
|
||||
// computer (local), as through a name other than loopback's; one
|
||||
// connected with another key isn't. From elsewhere the own key proves
|
||||
// nothing: it is in a zip in Downloads, and a browser a copy of it
|
||||
// connects from another computer (the Docker bridge's 172.17.0.1, say) is
|
||||
// handed none of this computer's calls. Nor can the key call the browser
|
||||
// MCP itself: it connects the extension and nothing else.
|
||||
func TestOwnBrowserKeyIsThisComputers(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
@@ -468,11 +475,13 @@ func TestOwnBrowserKeyIsThisComputers(t *testing.T) {
|
||||
t.Fatal("an own browser key with none recorded")
|
||||
}
|
||||
s := New()
|
||||
const testPeer = "X-Test-Peer"
|
||||
// testPeer: the request comes from that address, to testHost's name
|
||||
const testPeer, testHost = "X-Test-Peer", "X-Test-Host"
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if p := r.Header.Get(testPeer); p != "" {
|
||||
r.RemoteAddr, r.Host = p, "192.0.2.1:3425"
|
||||
r.RemoteAddr, r.Host = p, cmp.Or(r.Header.Get(testHost), "192.0.2.1:3425")
|
||||
r.Header.Del(testPeer)
|
||||
r.Header.Del(testHost)
|
||||
}
|
||||
lanGuard(s.Handler()).ServeHTTP(w, r)
|
||||
}))
|
||||
@@ -484,6 +493,12 @@ func TestOwnBrowserKeyIsThisComputers(t *testing.T) {
|
||||
if got := OwnBrowserKey(); got != keys[0].ID {
|
||||
t.Fatalf("OwnBrowserKey = %q, want %q", got, keys[0].ID)
|
||||
}
|
||||
// as a magpie from before made it, with full access: held to the
|
||||
// extension as the gateway starts
|
||||
ScopeOwnBrowserKey()
|
||||
if k, _ := access.List(); !k[len(k)-2].Browser {
|
||||
t.Fatal("the own key isn't held to the extension")
|
||||
}
|
||||
away := http.Header{testPeer: {"172.17.0.1:40000"}}
|
||||
reply := func(name string) func(_, _, _ string, _ map[string]any) any {
|
||||
return func(_, _, _ string, _ map[string]any) any {
|
||||
@@ -500,9 +515,9 @@ func TestOwnBrowserKeyIsThisComputers(t *testing.T) {
|
||||
}
|
||||
return strings.Join(all, "\n"), m.Result.IsError
|
||||
}
|
||||
connected := func(id string) {
|
||||
connected := func(id string, n int) {
|
||||
t.Helper()
|
||||
for deadline := time.Now().Add(10 * time.Second); len(s.browser.all(keyedSession(id, "x"))) < 1; time.Sleep(5 * time.Millisecond) {
|
||||
for deadline := time.Now().Add(10 * time.Second); len(s.browser.all(keyedSession(id, "x"))) < n; time.Sleep(5 * time.Millisecond) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the extension never connected")
|
||||
}
|
||||
@@ -510,17 +525,37 @@ func TestOwnBrowserKeyIsThisComputers(t *testing.T) {
|
||||
}
|
||||
// another key's browser alone: not this computer's
|
||||
fakeExtensionWith(t, srv.URL, secrets[1], away, "Chrome/141", reply("the other key's"))
|
||||
connected(keys[1].ID)
|
||||
connected(keys[1].ID, 1)
|
||||
if got, bad := tabs("127.0.0.1:5000", BrowserSessionHeader, "s1"); !bad || got == "tabs of the other key's" {
|
||||
t.Fatalf("this computer's caller used another key's browser: %q", got)
|
||||
}
|
||||
fakeExtensionWith(t, srv.URL, secrets[0], away, "Chrome/141", reply("own"))
|
||||
connected(keys[0].ID)
|
||||
// the own key's copy, from another computer: not this computer's
|
||||
fakeExtensionWith(t, srv.URL, secrets[0], away, "Chrome/141", reply("a copy's"))
|
||||
connected(keys[0].ID, 1)
|
||||
if got, bad := tabs("127.0.0.1:5000", BrowserSessionHeader, "s1"); !bad || got == "tabs of a copy's" {
|
||||
t.Fatalf("this computer's caller used the browser a copy of the own key connected from elsewhere: %q", got)
|
||||
}
|
||||
// nor from loopback through a proxy, which is someone else's
|
||||
fakeExtensionWith(t, srv.URL, secrets[0], http.Header{testPeer: {"127.0.0.1:40001"}, testHost: {"magpie.example:3425"}, "X-Forwarded-For": {"203.0.113.9"}}, "Chrome/141", reply("a proxied copy's"))
|
||||
connected(keys[0].ID, 2)
|
||||
if got, bad := tabs("127.0.0.1:5000", BrowserSessionHeader, "s1"); !bad || strings.Contains(got, "copy's") {
|
||||
t.Fatalf("this computer's caller used the browser a proxied copy connected: %q", got)
|
||||
}
|
||||
// from this computer, by a name that isn't loopback's: this computer's
|
||||
fakeExtensionWith(t, srv.URL, secrets[0], http.Header{testPeer: {"127.0.0.1:40002"}, testHost: {"host.docker.internal:3425"}}, "Chrome/141", reply("own"))
|
||||
connected(keys[0].ID, 3)
|
||||
if got, bad := tabs("127.0.0.1:5000", BrowserSessionHeader, "s1"); bad || got != "tabs of own" {
|
||||
t.Fatalf("this computer's caller: %q", got)
|
||||
}
|
||||
if got, bad := tabs("172.17.0.1:40000", "Authorization", "Bearer "+secrets[0], BrowserSessionHeader, "s1"); bad || got != "tabs of own" {
|
||||
t.Fatalf("the own key's caller: %q", got)
|
||||
// the own key calls no MCP server, the browser's included
|
||||
r := httptest.NewRequest("POST", BrowserMCPPath, strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
|
||||
r.RemoteAddr = "172.17.0.1:40000"
|
||||
r.Header.Set("Authorization", "Bearer "+secrets[0])
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), BrowserKeyCode) {
|
||||
t.Fatalf("the own key's caller reached the browser MCP: %d %.200s", w.Code, w.Body.String())
|
||||
}
|
||||
if got, bad := tabs("172.17.0.1:40000", "Authorization", "Bearer "+secrets[1], BrowserSessionHeader, "s1"); bad || got != "tabs of the other key's" {
|
||||
t.Fatalf("the other key's caller: %q", got)
|
||||
|
||||
@@ -738,6 +738,7 @@ var WhileServing []func(context.Context)
|
||||
// serving, which is fine for the caller to ignore.
|
||||
func (s *Server) ListenAndServe(ctx context.Context) error {
|
||||
migrateLANKeyBestEffort()
|
||||
ScopeOwnBrowserKey()
|
||||
cfg, err := tlsConfig()
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -61,11 +61,37 @@ func (m *routeMux) HandleFunc(pattern string, h func(http.ResponseWriter, *http.
|
||||
m.ServeMux.HandleFunc(pattern, h)
|
||||
}
|
||||
|
||||
// BrowserKeyCode is the error code the Magpie Browser extension's key
|
||||
// (access.Key.Browser) is refused a route with.
|
||||
const BrowserKeyCode = "gateway_key_browser_only"
|
||||
|
||||
// browserKeyRoute is the one route the extension's key is answered: the
|
||||
// extension's WebSocket. Its key is written into a zip that lands in
|
||||
// Downloads (gui's browserKey), so whoever reads the zip has it; it must
|
||||
// spend nothing, read nothing and reach no MCP server, the browser's own
|
||||
// included (TestBrowserKeyEveryRoute).
|
||||
const browserKeyRoute = "GET " + BrowserExtensionPath
|
||||
|
||||
// readOnlyGuard refuses a read-only key every route of mux but
|
||||
// readOnlyRoutes, before anything is read, reserved or sent.
|
||||
// readOnlyRoutes, and the Magpie Browser extension's key every route but
|
||||
// browserKeyRoute, before anything is read, reserved or sent. Both are
|
||||
// judged here, after the key is known (callerGuard, lanGuard's
|
||||
// identifyCaller) and by the pattern the request is routed to, so no
|
||||
// route is left out, one added later included.
|
||||
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.Browser {
|
||||
if _, pattern := mux.Handler(r); pattern != browserKeyRoute {
|
||||
log.Printf("refused %s %s: gateway key %q is Magpie Browser's", r.Method, r.URL.Path, who.KeyName)
|
||||
writeJSON(w, http.StatusForbidden, map[string]any{"error": map[string]any{
|
||||
"message": "this gateway key is the Magpie Browser extension's: it connects the extension and nothing else, no model, MCP server, stats or write. Use another gateway key for those (Gateway → Gateway keys)",
|
||||
"type": "permission_error", "code": BrowserKeyCode}})
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
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
|
||||
|
||||
@@ -547,6 +547,8 @@ const I18N = {
|
||||
"Make read-only": "设为只读",
|
||||
"Give full access": "恢复完整权限",
|
||||
"Read only": "只读",
|
||||
"Browser only": "仅浏览器",
|
||||
"This key connects the Magpie Browser extension and nothing else. It can't use models, MCP servers or stats.": "这个密钥只用来连接 Magpie Browser 扩展,不能使用模型、MCP 服务器或统计。",
|
||||
"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} 已恢复完整权限",
|
||||
@@ -5197,6 +5199,8 @@ const I18N = {
|
||||
"Make read-only": "設為唯讀",
|
||||
"Give full access": "恢復完整權限",
|
||||
"Read only": "唯讀",
|
||||
"Browser only": "僅瀏覽器",
|
||||
"This key connects the Magpie Browser extension and nothing else. It can't use models, MCP servers or stats.": "這個金鑰只用來連接 Magpie Browser 擴充功能,不能使用模型、MCP 伺服器或統計。",
|
||||
"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} 已恢復完整權限",
|
||||
@@ -9808,6 +9812,8 @@ const I18N = {
|
||||
"Make read-only": "読み取り専用にする",
|
||||
"Give full access": "フルアクセスに戻す",
|
||||
"Read only": "読み取り専用",
|
||||
"Browser only": "ブラウザ専用",
|
||||
"This key connects the Magpie Browser extension and nothing else. It can't use models, MCP servers or stats.": "このキーは Magpie Browser 拡張機能の接続専用です。モデル、MCP サーバー、統計は使えません。",
|
||||
"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} をフルアクセスに戻しました",
|
||||
@@ -14437,6 +14443,8 @@ const I18N = {
|
||||
"Make read-only": "Nur Lesezugriff geben",
|
||||
"Give full access": "Vollen Zugriff geben",
|
||||
"Read only": "Nur Lesen",
|
||||
"Browser only": "Nur Browser",
|
||||
"This key connects the Magpie Browser extension and nothing else. It can't use models, MCP servers or stats.": "Dieser Schlüssel verbindet nur die Magpie-Browser-Erweiterung. Er kann keine Modelle, MCP-Server oder Statistiken nutzen.",
|
||||
"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",
|
||||
|
||||
@@ -226,7 +226,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"), ...(k.readOnly ? [gatewayReadOnlyTag()] : []), 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.browser ? [gatewayBrowserTag()] : 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);
|
||||
@@ -325,10 +325,12 @@ function gatewayKeyMore(k) {
|
||||
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
|
||||
// and usage, and uses nothing); the sharing key is given to agents.
|
||||
// Magpie Browser's key connects the extension alone, and stays so:
|
||||
// it is in a zip in Downloads
|
||||
...(k.browser ? [] : [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: "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) },
|
||||
]);
|
||||
@@ -349,6 +351,14 @@ function gatewayReadOnlyTag() {
|
||||
return tag;
|
||||
}
|
||||
|
||||
// Magpie Browser's key (the one the extension's zip was given) says so in
|
||||
// its row: it connects the extension and nothing else
|
||||
function gatewayBrowserTag() {
|
||||
const tag = el("span", "amodels key-readonly key-browser set", t("Browser only"));
|
||||
tag.title = t("This key connects the Magpie Browser extension and nothing else. It can't use models, MCP servers or stats.");
|
||||
return tag;
|
||||
}
|
||||
|
||||
function askGatewayKey(k, rotate) {
|
||||
const ed = el("div", "editor");
|
||||
const head = el("div", "ehead");
|
||||
|
||||
+12
-7
@@ -52,16 +52,21 @@ const browserKeyName = "Magpie Browser"
|
||||
|
||||
// browserKey is the secret of the gateway key a downloaded extension
|
||||
// connects with: the one recorded as the user's own browser's
|
||||
// (gateway.OwnBrowserKey) while it is on, else a new one, recorded. The
|
||||
// browser it connects is used by that key's callers and by this
|
||||
// computer's (gateway/browser.go), not by another key's.
|
||||
// (gateway.OwnBrowserKey) while it is on, else a new one, recorded. It is
|
||||
// a browser key (access.Key.Browser), which connects the extension and
|
||||
// nothing else: the zip it is written into lands in Downloads, and a copy
|
||||
// of it must not reach the user's models. One a magpie from before made
|
||||
// with full access is held to that first (access.ScopeBrowser). The
|
||||
// browser it connects is used by that key's callers, and by this
|
||||
// computer's when it connects from this computer (gateway/browser.go),
|
||||
// never by another key's.
|
||||
func browserKey() (string, error) {
|
||||
if id := gateway.OwnBrowserKey(); id != "" && access.On(id) {
|
||||
if id := gateway.OwnBrowserKey(); id != "" && access.On(id) && access.ScopeBrowser(id) == nil {
|
||||
if secret, err := access.Update("copy-key", access.Change{Key: id}); err == nil && secret != "" {
|
||||
return secret, nil
|
||||
}
|
||||
}
|
||||
secret, err := access.Update("add-key", access.Change{Name: browserKeyName})
|
||||
secret, err := access.Update("add-key", access.Change{Name: browserKeyName, Browser: true})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -69,8 +74,8 @@ func browserKey() (string, error) {
|
||||
if !ok {
|
||||
return "", errors.New("the key made for the extension isn't on")
|
||||
}
|
||||
// this computer's agents use the browser that connects with it, as
|
||||
// they do one on loopback
|
||||
// this computer's agents use the browser that connects with it from
|
||||
// this computer, as they do one on loopback
|
||||
if err := gateway.SetOwnBrowserKey(who.KeyID); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -67,6 +67,10 @@ func TestBrowserExtensionDownload(t *testing.T) {
|
||||
if got := gateway.OwnBrowserKey(); got != who.KeyID {
|
||||
t.Fatalf("the own browser key recorded is %q, want %q", got, who.KeyID)
|
||||
}
|
||||
// it connects the extension and nothing else: the zip is in Downloads
|
||||
if !who.Browser || !who.ReadOnly || who.Issues {
|
||||
t.Fatalf("the zip's key isn't held to the extension: %+v", who)
|
||||
}
|
||||
_, config = download(`{"at":"https://magpie.example.com/"}`)
|
||||
if !strings.Contains(config, `GATEWAY = "wss://magpie.example.com"`) || keyOf(config) != first {
|
||||
t.Fatalf("a second download got %q, want the same key at wss", config)
|
||||
@@ -86,6 +90,23 @@ func TestBrowserExtensionDownload(t *testing.T) {
|
||||
} else if gateway.OwnBrowserKey() != w.KeyID {
|
||||
t.Fatal("the new key isn't recorded as the own browser's")
|
||||
}
|
||||
// one a magpie from before made with full access is held to the
|
||||
// extension before it is handed out again, the same secret
|
||||
old, err := access.Update("add-key", access.Change{Name: browserKeyName})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldWho, _ := access.Authenticate(old)
|
||||
if err := gateway.SetOwnBrowserKey(oldWho.KeyID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, config = download(`{"at":"http://localhost:3430"}`)
|
||||
if keyOf(config) != old {
|
||||
t.Fatal("the key a magpie from before made wasn't handed out again")
|
||||
}
|
||||
if w, ok := access.Authenticate(old); !ok || !w.Browser || !w.ReadOnly {
|
||||
t.Fatalf("the key a magpie from before made isn't held to the extension: %+v", w)
|
||||
}
|
||||
for _, at := range []string{"ftp://x", "http://u:p@x:1", "http://x/path", "http://x?k=1", "javascript:alert(1)"} {
|
||||
b, _ := json.Marshal(map[string]string{"at": at})
|
||||
if code, _ := download(string(b)); code != http.StatusBadRequest {
|
||||
|
||||
@@ -1,24 +1,27 @@
|
||||
// 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.
|
||||
// key, which magpie gives its own agents, can't be made read-only. Magpie
|
||||
// Browser's key says it is the browser's and has no access to change.
|
||||
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" },
|
||||
en: { browser: "Browser only", 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: { browser: "仅浏览器", more: "密钥操作", make: "设为只读", full: "恢复完整权限", tag: "只读", made: "Server 已设为只读", given: "Server 已恢复完整权限", why: "共享密钥会交给 Agent 使用,不能设为只读" },
|
||||
"zh-TW": { browser: "僅瀏覽器", more: "金鑰操作", make: "設為唯讀", full: "恢復完整權限", tag: "唯讀", made: "Server 已設為唯讀", given: "Server 已恢復完整權限", why: "共享金鑰會交給 Agent 使用,不能設為唯讀" },
|
||||
ja: { browser: "ブラウザ専用", more: "キーの操作", make: "読み取り専用にする", full: "フルアクセスに戻す", tag: "読み取り専用", made: "Server を読み取り専用にしました", given: "Server をフルアクセスに戻しました", why: "共有キーはエージェントに渡されるため、読み取り専用にはできません" },
|
||||
de: { browser: "Nur Browser", 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 },
|
||||
// the key the Magpie Browser extension's zip was given
|
||||
{ id: "ext", name: "Magpie Browser", masked: "sk-magpie-key-…555555", readOnly: true, browser: true },
|
||||
];
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
@@ -77,6 +80,16 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
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");
|
||||
|
||||
// Magpie Browser's key says it is the browser's, not read-only,
|
||||
// and its access isn't changed from the menu
|
||||
assert.equal((await tag("ext").textContent()).trim(), w.browser);
|
||||
assert.ok((await tag("ext").getAttribute("title")).length > 10, "the tag says what a browser key is");
|
||||
await menu("ext");
|
||||
assert.equal(await item(w.make).count(), 0);
|
||||
assert.equal(await item(w.full).count(), 0);
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(events.filter((e) => e.action === "access-key" && e.body.key === "ext").length, 0);
|
||||
|
||||
// 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`);
|
||||
|
||||
@@ -153,7 +153,7 @@ docker logs magpie</pre>
|
||||
|
||||
<h2 id="browser"><a class="anchor" href="#browser">Your own browser</a></h2>
|
||||
<p>Magpie Browser lets agents act in your own browser, through its extension. The extension can’t be loaded from the container’s folders, so in the browser UI open <span class="ui">Library</span> → <span class="ui">Magpie Browser</span> and click <span class="ui">Download the extension</span>. The zip is pointed at the page’s own address, with a gateway key named <b>Magpie Browser</b> of its own. Unzip it, open <code>chrome://extensions</code>, turn on Developer mode and click <span class="ui">Load unpacked</span> on the unzipped folder. An extension already loaded takes the address (<code>http://localhost:3430</code>, or the gateway’s published port) and a gateway key in its popup.</p>
|
||||
<p>The browser connected with the downloaded extension is the container’s own: agents in the container use it, and so does an agent on the host that calls <code>/mcp/magpie/browser</code> with the same Magpie Browser key. A browser given another key is that key’s alone.</p>
|
||||
<p>The Magpie Browser key connects the extension and nothing else: it can’t use models, MCP servers or stats, so a copy of the zip left in Downloads spends nothing. The host’s browser reaches the container from Docker’s bridge, not from the container’s own computer, so it is that key’s alone and the container’s agents don’t use it yet (<a href="https://github.com/yetone/magpie/issues/5529">#5529</a>). To use it from an agent on the host, give that agent a gateway key of its own with full access, connect the extension with the same key in its popup, and call <code>/mcp/magpie/browser</code> with it. A browser given another key is that key’s alone, and it is let go once its key is turned off, removed or rotated.</p>
|
||||
|
||||
<h2 id="volume"><a class="anchor" href="#volume">What is kept</a></h2>
|
||||
<p>Everything magpie writes is under <code>/config</code>, so a restart, or a new container on the same volume, keeps your providers, keys, sign-ins and plugins.</p>
|
||||
|
||||
@@ -153,7 +153,7 @@ docker logs magpie</pre>
|
||||
|
||||
<h2 id="browser"><a class="anchor" href="#browser">自分のブラウザ</a></h2>
|
||||
<p>Magpie Browser は拡張機能を通して、エージェントにあなた自身のブラウザを操作させます。コンテナ内のフォルダは拡張機能として読み込めないので、ブラウザ UI で <span class="ui">ライブラリ</span> → <span class="ui">Magpie Browser</span> を開き、<span class="ui">拡張機能をダウンロード</span> をクリックします。zip はこのページ自身のアドレスを指し、<b>Magpie Browser</b> という名前の専用ゲートウェイキーが入っています。展開して <code>chrome://extensions</code> を開き、デベロッパー モードをオンにして、展開したフォルダを <span class="ui">パッケージ化されていない拡張機能を読み込む</span> で選びます。読み込み済みの拡張機能は、ポップアップでアドレス(<code>http://localhost:3430</code> か、ゲートウェイを公開したポート)とゲートウェイキーを受け付けます。</p>
|
||||
<p>ダウンロードした拡張機能で接続したブラウザはコンテナ自身のものです。コンテナ内のエージェントが使い、同じ Magpie Browser キーで <code>/mcp/magpie/browser</code> を呼ぶホストのエージェントも使えます。別のキーで接続したブラウザは、そのキーだけのものです。</p>
|
||||
<p>Magpie Browser キーは拡張機能の接続専用で、モデル、MCP サーバー、統計は使えません。ダウンロードフォルダに残った zip のコピーで利用枠が使われることはありません。ホストのブラウザは Docker のブリッジ経由でコンテナにつながり、コンテナと同じコンピュータからの接続ではないため、そのキーだけのものになり、コンテナ内のエージェントはまだ使えません(<a href="https://github.com/yetone/magpie/issues/5529">#5529</a>)。ホストのエージェントから使うには、そのエージェントにフルアクセスのゲートウェイキーを渡し、拡張機能のポップアップで同じキーを入れて接続し、そのキーで <code>/mcp/magpie/browser</code> を呼びます。別のキーで接続したブラウザはそのキーだけのもので、キーを無効化、削除、ローテーションすると接続は切れます。</p>
|
||||
|
||||
<h2 id="volume"><a class="anchor" href="#volume">保存されるもの</a></h2>
|
||||
<p>magpie が書くものはすべて <code>/config</code> の下にあるので、再起動しても、同じボリュームで新しいコンテナを作っても、プロバイダ、キー、サインイン、プラグインは残ります。</p>
|
||||
|
||||
@@ -153,7 +153,7 @@ docker logs magpie</pre>
|
||||
|
||||
<h2 id="browser"><a class="anchor" href="#browser">你自己的浏览器</a></h2>
|
||||
<p>Magpie Browser 通过它的扩展,让 Agent 在你自己的浏览器里操作。容器里的文件夹没法直接加载成扩展,所以在浏览器界面打开 <span class="ui">资源库</span> → <span class="ui">Magpie Browser</span>,点 <span class="ui">下载扩展</span>。下载的 zip 指向这个页面自己的地址,并带一个名为 <b>Magpie Browser</b> 的专用网关密钥。解压后打开 <code>chrome://extensions</code>,打开开发者模式,点 <span class="ui">加载已解压的扩展程序</span>,选择解压出的文件夹。已经加载过的扩展,也可以在它的弹窗里填地址(<code>http://localhost:3430</code>,或网关发布到主机的端口)和网关密钥。</p>
|
||||
<p>用下载的扩展连上的浏览器就是这个容器自己的:容器里的 Agent 直接用它,主机上用同一个 Magpie Browser 密钥调用 <code>/mcp/magpie/browser</code> 的 Agent 也能用。填了别的密钥连上的浏览器只属于那个密钥。</p>
|
||||
<p>Magpie Browser 密钥只用来连接扩展,不能使用模型、MCP 服务器或统计,所以留在下载文件夹里的 zip 副本花不了你的额度。主机上的浏览器经 Docker 的网桥连到容器,不算容器所在电脑本机的连接,所以它只属于这个密钥,容器里的 Agent 暂时用不到它(<a href="https://github.com/yetone/magpie/issues/5529">#5529</a>)。要让主机上的 Agent 用它:给这个 Agent 一个完整权限的网关密钥,在扩展弹窗里填同一个密钥连上,再用它调用 <code>/mcp/magpie/browser</code>。填了别的密钥连上的浏览器只属于那个密钥;密钥被停用、删除或轮换后,连接随即断开。</p>
|
||||
|
||||
<h2 id="volume"><a class="anchor" href="#volume">保存了什么</a></h2>
|
||||
<p>magpie 写的所有东西都在 <code>/config</code> 下,所以重启、或者在同一个数据卷上新建容器,供应商、密钥、登录和插件都还在。</p>
|
||||
|
||||
Reference in New Issue
Block a user