Files
magpie/internal/gateway/hub_visitor_test.go
T
yetone 483b131ef0 browser: magpie in Docker uses the host's own browser, through a key the page hands out
noahhrreion ran magpie in a container and its Magpie Browser never
connected. The host's Chrome dials ws://127.0.0.1:3425/v1/magpie/browser/
extension, which reaches the container from the bridge (172.17.0.1). That
is not loopback, so the gateway refused it (403). The browser MCP also
refused every caller from elsewhere, and the hub marked the browser
HereOnly. The extension's folder under the container's HOME can't be
loaded by the host's browser either.

Nothing is opened to the network without a key:

- The extension takes a gateway key: its popup has a Gateway key field,
  and config.js carries KEY (extension 0.1.7). From another computer the
  extension connects only with ?key= of a gateway key that is on, and
  only from the extension's own Origin (checked first). Loopback is
  unchanged, and a page's origin, null, a keyless call or a rebound Host
  are all still refused (TestBrowserExtensionOnlyFromItsOrigin).
- A browser that connects with a key belongs to that key. Sessions are
  tagged key:<id>/... (browserOwner, keyedSession), and a remote caller's
  session is forced to its own key's whatever it names. The relay filters
  every lookup (forSession, all, choose) through browserConn.serves. The
  browser MCP admits a remote caller only with a gateway key; a web page
  is refused as before.
- The key the page makes is recorded as this magpie's own browser's: its
  id goes in settings.Dir()/browser-key, written temp-and-rename. This
  goes by where the key came from, not by its name. A browser connecting
  with it serves this computer's sessions too, so agents inside the
  container use it as they would one on loopback. A record that can't be
  read names no key, so no keyed browser is this computer's.
- Router: magpie mcp browser is HubServer.Keyed. A visitor from
  elsewhere gets it only with a key (HubVisitor.Key), and hubCall names
  its session key:<id>/..., so it reaches only that key's browser.
- GUI: a page whose browser can't reach magpie's folders (InContainer, or
  a page from another computer) is "away". The Magpie Browser sheet's
  button then reads Download the extension. It does a POST to
  /api/library/browser/extension with the page's origin, which answers a
  zip pointed at that origin (3430 passes the gateway's routes on) and
  holding the recorded key's secret. The key is made the first time and
  reused while it is on. The steps (unzip, chrome://extensions, Developer
  mode, Load unpacked) are shown in every language. It is a POST so that
  a link from another site can't mint a key.
- Docs: reference.md (Docker), subsystems/library.md and mcp-router.md,
  and site docker.html in en, zh and ja.

Run, at this tree rebased on origin/main 6302f88bf, on mote:
- gofmt -l, go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., and darwin, linux and windows builds:
  clean, all ok
- go test -tags nogui -run 'Browser|Hub|OwnBrowser' ./internal/gateway/,
  and the whole of internal/library, internal/gui and internal/browserext:
  ok (gateway 2.4s, library 166s, gui 104s, browserext 0.3s)
- GUI tests library-browser-away (new: every language, Chromium and
  WebKit, 1100 and 420 wide), library-browser-setup, library-browser-ask,
  i18n-keys and i18n-en-no-cjk: 115 pass. One red, i18n-keys "a plugin's words are its own", is for three
  strings this change doesn't touch and is already filed (#5332, #5426,
  #5482)

Real use, in Docker Desktop on xiaomi-gpu (Windows 11): this tree's
Dockerfile image, run as `web --addr 0.0.0.0:3430` with 3425 and 3430
published to the host's localhost. The host's Node and Playwright Chromium:
- signed in to the page, which says away:true;
- downloaded the zip (GATEWAY "ws://localhost:3530" and a KEY), twice,
  getting the same key both times;
- a keyless /mcp/magpie/browser call from the host got 401;
- loaded the unzipped extension with --load-extension. The container's log
  says "Magpie Browser 0.1.7 connected with gateway key 12d2702a…" and
  /api/library/browser says connected:true;
- an MCP client on the host with that key listed b1 (Chrome 151), opened
  http://localhost:3531/ (served on the host) and read "hello from the
  host";
- a second gateway key made in the container got "isn't connected with
  this gateway key";
- a curl inside the container to 127.0.0.1:3425/mcp/magpie/browser with no
  key listed the host browser's tabs, the host page included.

Broken by hand, each red:
- forSession left unfiltered;
- a remote session not forced to its key;
- no Origin check on a keyed connect;
- hubCall not prefixing the session;
- Keyed given to a visitor with no key;
- the old MCP guard;
- browserKey not reusing the key;
- the away peer check removed;
- serves("") without own (TestOwnBrowserKeyIsThisComputers,
  TestOwnBrowserKeyUnreadable);
- OwnBrowserKey reading the wrong file (the gateway tests and
  TestBrowserExtensionDownload).

Not tried:
- the reporter's own setup (their compose file and Chrome);
- a real agent's MCP client calling the browser from the host. Node's
  fetch sends Sec-Fetch-Mode: cors, which fromBrowser counts as a web page
  and refuses. The e2e used node's http instead. Whether an agent's MCP
  client built on fetch is hit by this is not checked; filed as #5522.
- Edge, Brave and Firefox;
- a remote page over https/wss through a proxy.

What the user does: update magpie and publish 3425 and 3430. In the web
UI open Library -> Magpie Browser -> Download the extension, unzip it and
Load unpacked in chrome://extensions. An extension 0.1.7 already loaded
can take the address and key in its popup instead.

Reported-by: noahhrreion (Discord)
2026-11-06 20:06:15 +08:00

148 lines
5.8 KiB
Go

package gateway
import (
"context"
"encoding/json"
"net/http"
"slices"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/access"
)
// A caller on another computer, by any gateway key, is never given a
// server that acts as this computer's user (Magpie Browser, magpie's image
// server, another magpie's router), which /mcp/magpie/browser and the key's
// image models refuse it directly; one by a key held to some models,
// accounts or a spend limit isn't given a program run here either. Neither
// is listed, and neither runs when called by name.
func TestHubKeepsThisComputersOwnServersHere(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("MAGPIE_TRUST_PROXY", "")
servers := []HubServer{
{Name: "magpie-browser", HereOnly: true, Program: true},
{Name: "magpie-image", HereOnly: true, Program: true},
{Name: "home-magpie", HereOnly: true, Bridge: true},
{Name: "shell", Program: true},
{Name: "docs"},
}
var tools []HubTool
for _, s := range servers {
tools = append(tools, HubTool{Server: s.Name, Tool: "do", Spec: hubSpec("do")})
}
f := &fakeHub{on: true, tools: map[string][]HubTool{"": tools}, servers: map[string][]HubServer{"": servers}}
withHub(t, f)
h := lanGuard(New().Handler())
keys, secrets := newCaller(t, "Full", "Narrow")
if _, err := access.Update("models-key", access.Change{Key: keys[1].ID, Models: []string{"some/model"}}); err != nil {
t.Fatal(err)
}
const there = "192.0.2.7:4000"
listed := func(addr string, hdr ...string) []string {
t.Helper()
m := readMCP(t, hubPostAt(h, HubMCPAll, addr, toolsList, hdr...))
var out []string
for _, t := range m.Result.Tools {
out = append(out, strings.TrimSuffix(t.Name, hubSep+"do"))
}
slices.Sort(out)
return out
}
full := []string{"Authorization", "Bearer " + secrets[0]}
narrow := []string{"Authorization", "Bearer " + secrets[1]}
if got, want := listed(here), []string{"docs", "home-magpie", "magpie-browser", "magpie-image", "shell"}; !slices.Equal(got, want) {
t.Errorf("this computer is given %v, want %v", got, want)
}
if got, want := listed(there, full...), []string{"docs", "shell"}; !slices.Equal(got, want) {
t.Errorf("a full key from there is given %v, want %v", got, want)
}
if got, want := listed(there, narrow...), []string{"docs"}; !slices.Equal(got, want) {
t.Errorf("a held key from there is given %v, want %v", got, want)
}
if got, want := listed(here, append([]string{"X-Forwarded-For", "203.0.113.9"}, full...)...), []string{"docs", "shell"}; !slices.Equal(got, want) {
t.Errorf("through a proxy here, a full key is given %v, want %v", got, want)
}
for _, c := range []struct {
name string
auth []string
}{
{"magpie-browser", full}, {"magpie-image", full}, {"home-magpie", full},
{"magpie-browser", narrow}, {"shell", narrow},
} {
m := readMCP(t, hubPostAt(h, HubMCPAll, there, toolsCall(c.name+hubSep+"do", `{"action":"tabs"}`), c.auth...))
if m.Error == nil && !m.Result.IsError {
t.Errorf("%s ran for %s from there: %+v", c.name, c.auth[1][:12], m)
}
}
if got := f.ran(); len(got) != 0 {
t.Fatalf("ran for a caller not given them: %q", got)
}
m := readMCP(t, hubPostAt(h, HubMCPAll, there, toolsCall("docs"+hubSep+"do", `{}`), narrow...))
if m.Error != nil || m.Result.IsError {
t.Fatalf("docs for the held key: %+v", m)
}
m = readMCP(t, hubPostAt(h, HubMCPAll, there, toolsCall("shell"+hubSep+"do", `{}`), full...))
if m.Error != nil || m.Result.IsError {
t.Fatalf("shell for the full key: %+v", m)
}
}
// Magpie Browser is given to a keyed caller from elsewhere too, and its
// call goes under the key's session (browser.go), whatever session the
// caller names; never to one from elsewhere with no key, nor to a page.
func TestHubGivesAKeyItsBrowser(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_ADDR", "")
t.Setenv("MAGPIE_PUBLIC_URL", "")
t.Setenv("MAGPIE_TRUST_PROXY", "")
servers := []HubServer{{Name: "magpie-browser", HereOnly: true, Program: true, Keyed: true}}
f := &fakeHub{on: true, tools: map[string][]HubTool{"": {{Server: "magpie-browser", Tool: "do", Spec: hubSpec("do")}}}, servers: map[string][]HubServer{"": servers}}
var mu sync.Mutex
var seen []string
f.call = func(ctx context.Context, server, tool string) (json.RawMessage, error) {
mu.Lock()
seen = append(seen, HubCallerOf(ctx).Session)
mu.Unlock()
return json.RawMessage(`{"content":[{"type":"text","text":"ok"}]}`), nil
}
withHub(t, f)
h := lanGuard(New().Handler())
keys, secrets := newCaller(t, "Host", "Narrow")
if _, err := access.Update("models-key", access.Change{Key: keys[1].ID, Models: []string{"some/model"}}); err != nil {
t.Fatal(err)
}
const there = "192.0.2.7:4000"
call := toolsCall("magpie-browser"+hubSep+"do", `{}`)
for i, auth := range [][]string{{"Authorization", "Bearer " + secrets[0], "Mcp-Session-Id", "abc"}, {"Authorization", "Bearer " + secrets[1]}} {
m := readMCP(t, hubPostAt(h, HubMCPAll, there, call, auth...))
if m.Error != nil || m.Result.IsError {
t.Fatalf("key %d from there: %+v", i, m)
}
}
if w := hubPostAt(h, HubMCPAll, here, call, "Origin", "http://localhost:5173"); w.Code != http.StatusForbidden {
t.Fatalf("a page here: %d %s", w.Code, w.Body.String())
}
m := readMCP(t, hubPostAt(h, HubMCPAll, here, call, "Mcp-Session-Id", "abc"))
if m.Error != nil || m.Result.IsError {
t.Fatalf("here: %+v", m)
}
mu.Lock()
defer mu.Unlock()
want := []string{"key:" + keys[0].ID + "/hub--abc", "key:" + keys[1].ID + "/", "hub--abc"}
if !slices.Equal(seen, want) {
t.Fatalf("sessions %q, want %q", seen, want)
}
for _, v := range []HubVisitor{{Away: true}, {Away: true, Held: true}} {
if v.Gives(servers[0]) {
t.Errorf("%+v is given Magpie Browser", v)
}
}
if (HubVisitor{Away: true, Key: "k"}).Gives(HubServer{Name: "magpie-image", HereOnly: true}) {
t.Error("a key from elsewhere is given magpie's image server")
}
}