Files
magpie/internal/gui/browser_test.go
T
yetone e1eeeed734 browser: the extension's key connects Magpie Browser and nothing else; own needs this computer; a key turned off closes its browser
483b131ef wrote 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/main 2000ae439 + 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/main 6f5d48ea0 run alone: i18n-keys "a plugin's words are its
  own" (#5332, #5426, #5482) and gateway-key-models' 560px width check
  (#4081, commented).

Rebased onto 6f5d48ea0 (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).
2026-11-06 22:11:02 +08:00

138 lines
4.6 KiB
Go

package gui
import (
"archive/zip"
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gateway"
)
// A browser magpie's folders are out of reach of downloads the extension,
// pointed at the page's own address and given a gateway key of its own,
// the same key each time while it is on.
func TestBrowserExtensionDownload(t *testing.T) {
sandboxHome(t)
mux := http.NewServeMux()
browserRoutes(mux, folderOnly{})
download := func(body string) (int, string) {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/library/browser/extension", strings.NewReader(body)))
if w.Code != 200 {
return w.Code, ""
}
if got := w.Header().Get("Content-Disposition"); got != `attachment; filename="Magpie Browser Extension.zip"` {
t.Errorf("Content-Disposition %q", got)
}
zr, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len()))
if err != nil {
t.Fatal(err)
}
for _, f := range zr.File {
if f.Name == "Magpie Browser Extension/config.js" {
rc, _ := f.Open()
b, _ := io.ReadAll(rc)
rc.Close()
return 200, string(b)
}
}
t.Fatal("no config.js in the zip")
return 0, ""
}
keyOf := func(config string) string {
m := regexp.MustCompile(`KEY = "([^"]*)"`).FindStringSubmatch(config)
if m == nil {
t.Fatalf("no KEY in %q", config)
}
return m[1]
}
_, config := download(`{"at":"http://localhost:3430"}`)
if !strings.Contains(config, `GATEWAY = "ws://localhost:3430"`) {
t.Fatalf("config %q isn't pointed at the page's address", config)
}
first := keyOf(config)
who, ok := access.Authenticate(first)
if !ok {
t.Fatalf("the zip's key %q isn't a gateway key", first)
}
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)
}
if keys, _ := access.List(); len(keys) != 1 || keys[0].Name != browserKeyName {
t.Fatalf("keys after two downloads: %+v", keys)
}
// a key turned off isn't handed out again
if _, err := access.Update("off-key", access.Change{Key: who.KeyID}); err != nil {
t.Fatal(err)
}
_, config = download(`{"at":"http://localhost:3430"}`)
if again := keyOf(config); again == first {
t.Fatal("a key turned off was put in the extension again")
} else if w, ok := access.Authenticate(again); !ok {
t.Fatal("the new key isn't on")
} 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 {
t.Errorf("at %q: %d, want 400", at, code)
}
}
}
// Away: a page looked at from another computer downloads the extension.
func TestBrowserAwayFromAnotherComputer(t *testing.T) {
sandboxHome(t)
mux := http.NewServeMux()
browserRoutes(mux, folderOnly{})
for addr, want := range map[string]bool{"127.0.0.1:5000": false, "[::1]:5000": false, "192.168.1.20:5000": true} {
r := httptest.NewRequest("GET", "/api/library/browser", nil)
r.RemoteAddr = addr
w := httptest.NewRecorder()
mux.ServeHTTP(w, r)
var b browserJSON
if err := json.Unmarshal(w.Body.Bytes(), &b); err != nil {
t.Fatal(err)
}
// a test run inside a container is away from every page
if b.Away != want && !(b.Away && !want && gateway.InContainer()) {
t.Errorf("%s: away %v, want %v", addr, b.Away, want)
}
}
}