Files
magpie/internal/gui/pluginpanel_test.go
T
yetone 5eab14a8cc plugin pages: magpie web reaches a page's local service on its own address, so the chat page works from another computer
aigcfree (Discord DM) runs `magpie web --addr 0.0.0.0:3430` on an Ubuntu
server behind nginx and opens it from a Windows PC. Plugins -> 对话
(@magpie-community/page-chat) showed "127.0.0.1 refused to connect": the
page sends its frame to the chat server on 127.0.0.1, which in that
browser is the Windows PC.

A plugin now declares its page's service (package.json
magpie.page.service {port, option}: the port, or the plugin option that
holds it, from its plugins.json options; plugin.ServiceSpec). Served to a
browser (isWeb), /api/plugin-pages gives the page `service`:
_magpie/service/ under its token, and the bridge hands the frame
magpie.service as an absolute address. The desktop window and slot pages
get none, and the routes answer 404 there, so the local path is as before.

servePageService reverse-proxies /_magpie/plugin/<token>/_magpie/service/…
to 127.0.0.1:<port>. The service stays on loopback. The way in is the
page's own: the per-run token that only a signed-in /api hands out,
behind AllowGuard. Nothing is weakened:
- Host is set to 127.0.0.1:<port>, which the service's rebinding check
  wants.
- The window's cookie is taken off.
- Origin must be absent or null (403 otherwise).
- Set-Cookie is dropped.
- Every reply is sandboxed (sandbox allow-scripts; frame-ancestors
  'self'), with Referrer-Policy no-referrer and nosniff.
- The gateway's own port is never served, since a request from this
  server is loopback and the gateway takes that without a key.
- Event streams flush as they come (FlushInterval -1, X-Accel-Buffering:
  no for nginx). webCompressed no longer gzips text/event-stream, which
  held a stream back until gzip's buffer filled.
- A redirect to the service's own address is made relative.
- The entry starts the plugin host as the page's HTML does (pageHost).
- A service not up yet answers its frame with a 502 page that tries
  again in 2s.

page-chat 0.1.2 (magpie-community/plugins 4a46212, on dist) declares the
service, goes to magpie.service when given one (else 0.1.1's path:
127.0.0.1 on loopback, the SSH-tunnel note from elsewhere), and asks
api/… by relative address.

Docs: plugin-runtime.md P4 (the page row), gui-shell.md (no gzip for event
streams).

Tests: TestPluginPageServiceListedToBrowserOnly, TestPluginPageServiceSpec,
TestPluginPageServiceProxied (through webHandler: Host, cookie, Set-Cookie,
CSP, escaped path and query, foreign Origin 403, made-up token 404,
redirects, SSE first event before the end and not gzipped),
TestPluginPageServiceDown, TestServiceLocation; plugin-page.test.cjs
checks magpie.service in a browser page and its absence in a slot.

Run at 276683d85, this change on origin/main e61e10535. It was rebased
since onto c1660481c, a one-line WorkBuddy mover min in internal/provider.
181fd0a68
(another session's proxy, path _service/, {portOption}) is reverted
there by 3870ddf0a, and nothing of it is left:
- go test ./internal/gui/ ./internal/plugin/ -timeout 45m, native on the
  Windows box: every new test ok. 8 reds, none in code this touches:
  - 6 fail the same at origin/main c1660481c, run there by name:
    TestGatewayHeldByAContainer, TestLodyImportHandoff,
    TestImportStatusUnreadableIsUnknown, TestAionUiImportRow,
    TestUpdateThatWontStart, TestPiPackage. All are in #4115.
  - TestLoadConcurrentWithSavesAndEdits is red 2 of 3 alone here and red
    at c1660481c too (a rename "Access is denied"); it is in #1827.
  - TestDesktopSessionTitlesOnPages passes alone (3 of 3). In the package
    run it listed the box's real WSL Codex session. Filed as #4185.
- Earlier, at bc247a8cc, on mote: the new Go tests, and go vet of both
  packages.
- Not run at this tree: the full go test ./... . mote was at load 300+
  with three other sessions' full suites, and the Linux box had one. A
  run at an older base (fa5ff2fec) had 25 packages ok, internal/agent
  among them, and none red when it was stopped for the rebase.
- gofmt -l: clean. go vet ./internal/gui ./internal/plugin: darwin on
  mote, native Windows on xiaomi-gpu. A Linux vet from mote fails in wails'
  cgo files, and in WSL for lack of gtk4/webkitgtk-6.0 headers, both
  unrelated to this change; CI vets Linux with its headers.
- plugin-page.test.cjs on the Windows box, both engines: WebKit 3/3.
  Chromium's first test is #4180, which fails the same on origin/main
  f463a8aaf. The next commit fixes #4180 at its cause.
- Real: a sandbox magpie web on mote (0.0.0.0:3561, sandbox HOME,
  MAGPIE_WEB_KEY, the real chat package from a folder, a fake gateway).
  Playwright on the Windows box opened Plugins -> chat over the LAN in
  Chromium and WebKit. The frame went to
  http://mote.local:3561/_magpie/plugin/<tok>/_magpie/service/?theme=…
  with origin null. Its fonts.css and style.css came through the proxy. A
  sent message streamed back "remote chat works", and the fake gateway
  logged both POSTs.
  - From the Mac over the LAN: /api/plugin-pages without the cookie
    gives 401. A made-up token gives 404. A foreign Origin gives 403.
    POST api/chat without the chat token gives 403 (the service's own
    check). mote.local:3563 directly is refused (loopback only).
  - Before bun was reachable in the sandbox, the frame got the 502 retry
    page.
- Broken by hand, each red then restored:
  - Without the event-stream exclusion, the stream arrives gzipped.
  - Without the Host rewrite, the cookie strip or the web gate, each
    assertion is red.
  - With the bridge's service dropped, plugin-page.test.cjs is red in
    WebKit ("magpie.service").

Not tried:
- A real nginx in front.
- A WebSocket through the proxy (httputil handles the upgrade; the chat
  page uses none).
- TLS (--tls-cert).
- The desktop app with page-chat 0.1.2: its fallback is 0.1.1's path,
  covered by the plugin's launcher tests.
2026-10-29 14:28:24 +08:00

178 lines
6.8 KiB
Go

package gui
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/settings"
)
// copyTree copies a testdata folder to to.
func copyTree(t *testing.T, from, to string) {
t.Helper()
err := filepath.WalkDir(from, func(p string, d os.DirEntry, err error) error {
if err != nil {
return err
}
rel, _ := filepath.Rel(from, p)
if d.IsDir() {
return os.MkdirAll(filepath.Join(to, rel), 0o755)
}
b, err := os.ReadFile(p)
if err != nil {
return err
}
return os.WriteFile(filepath.Join(to, rel), b, 0o644)
})
if err != nil {
t.Fatal(err)
}
}
// panelPlugins writes plugins.json with the example panel plugin
// (testdata/panel-plugin), on and a copy switched off, and two copies of
// the example page plugin that each ask to replace Usage; it answers
// their specs in that order.
func panelPlugins(t *testing.T) (on, off, first, second string) {
t.Helper()
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("XDG_DATA_HOME", filepath.Join(h, ".local", "share"))
t.Setenv("MAGPIE_BUN", "")
t.Setenv("PATH", "")
on, off = filepath.Join(h, "src", "notes"), filepath.Join(h, "src", "notes-off")
first, second = filepath.Join(h, "src", "usage-a"), filepath.Join(h, "src", "usage-b")
copyTree(t, "testdata/panel-plugin", on)
copyTree(t, "testdata/panel-plugin", off)
for i, dir := range []string{first, second} {
copyTree(t, "testdata/page-plugin", dir)
pkg := `{"name":"usage-` + string(rune('a'+i)) + `","version":"0.1.0","magpie":{"page":{"title":"Usage ` + string(rune('A'+i)) + `","file":"page/index.html","replaces":"usage"},"permissions":["usage:summary"]}}`
if err := os.WriteFile(filepath.Join(dir, "package.json"), []byte(pkg), 0o644); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(h, "secret.txt"), []byte("SECRET"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(settings.Dir(), 0o755); err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(map[string]any{"plugins": []map[string]any{{"spec": on}, {"spec": off, "off": true}, {"spec": first}, {"spec": second}}})
if err := os.WriteFile(filepath.Join(settings.Dir(), "plugins.json"), b, 0o644); err != nil {
t.Fatal(err)
}
return on, off, first, second
}
// A plugin's panels are listed with the page each goes in, and each is
// served by a token of its own, shut in as a page is: to its own folder,
// off the network, and none of a plugin switched off.
func TestPluginPanelsServedShutIn(t *testing.T) {
on, off, _, _ := panelPlugins(t)
h := pageMux()
var panels []pluginPanel
w := do(h, httptest.NewRequest("GET", "/api/plugin-panels", nil))
if err := json.Unmarshal(w.Body.Bytes(), &panels); err != nil || len(panels) != 3 {
t.Fatalf("panels: %s %v", w.Body, err)
}
want := []struct{ slot, title, key string }{
{"provider", "Notes", "plugin-magpie-provider-notes-0"},
{"usage", "Top models today", "plugin-magpie-provider-notes-1"},
{"settings", "Provider notes", "plugin-magpie-provider-notes-2"},
}
toks := map[string]bool{}
for i, p := range panels {
if p.Spec != on || p.Slot != want[i].slot || p.Title != want[i].title || p.Key != want[i].key || len(p.Reads) != 1 || p.Reads[0] != "usage:summary" {
t.Errorf("panel %d: %+v", i, p)
}
tok := strings.Split(strings.TrimPrefix(p.URL, pluginPagePrefix), "/")[0]
if toks[tok] || tok == pageToken(on) {
t.Errorf("panel %d shares a token: %s", i, tok)
}
toks[tok] = true
r := httptest.NewRequest("GET", p.URL, nil)
r.Host = "127.0.0.1:3437"
w := do(h, r)
if w.Code != 200 || !strings.Contains(w.Body.String(), "<html") {
t.Fatalf("panel %d: %d %s", i, w.Code, w.Body)
}
csp := w.Header().Get("Content-Security-Policy")
for _, want := range []string{"sandbox allow-scripts", "connect-src 'none'", "script-src 127.0.0.1:3437" + pluginPagePrefix + tok + "/;"} {
if !strings.Contains(csp, want) {
t.Errorf("panel %d: policy %q has no %q", i, csp, want)
}
}
if strings.Contains(csp, "allow-same-origin") {
t.Errorf("panel %d: policy %q lets it out", i, csp)
}
for _, path := range []string{pluginPagePrefix + tok + "/../package.json", pluginPagePrefix + tok + "/../../secret.txt"} {
r := httptest.NewRequest("GET", "/", nil)
r.URL.Path = path
w := httptest.NewRecorder()
servePluginPage(w, r, false)
if w.Code == 200 || strings.Contains(w.Body.String(), "SECRET") || strings.Contains(w.Body.String(), `"name"`) {
t.Errorf("%s: %d %s", path, w.Code, w.Body)
}
}
}
// the switched-off copy's panels, by the token they would have
r := httptest.NewRequest("GET", "/", nil)
r.URL.Path = pluginPagePrefix + pageToken(off+"\x00panel\x000") + "/notes.html"
w = httptest.NewRecorder()
servePluginPage(w, r, false)
if w.Code == 200 {
t.Errorf("a plugin switched off's panel: %d", w.Code)
}
}
// A panels-only plugin reads what it declared and nothing else, through
// the same endpoint as a page, and sets its own options.
func TestPluginPanelsReadWhatTheyDeclared(t *testing.T) {
on, off, _, _ := panelPlugins(t)
h := pageMux()
post := func(path, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", path, strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
return do(h, r)
}
spec, _ := json.Marshal(on)
if w := post("/api/plugin-pages/read", `{"spec":`+string(spec)+`,"read":"providers:list"}`); w.Code != http.StatusForbidden {
t.Errorf("an undeclared read: %d %s", w.Code, w.Body)
}
if w := post("/api/plugin-pages/read", `{"spec":`+string(spec)+`,"read":"usage:summary"}`); w.Code != 200 {
t.Errorf("a declared read: %d %s", w.Code, w.Body)
}
offSpec, _ := json.Marshal(off)
if w := post("/api/plugin-pages/read", `{"spec":`+string(offSpec)+`,"read":"usage:summary"}`); w.Code == 200 {
t.Errorf("a plugin switched off read: %d", w.Code)
}
if w := post("/api/plugin-pages/options", `{"spec":`+string(spec)+`,"options":{"notes":{"openai":"work"}}}`); w.Code != 200 || !strings.Contains(w.Body.String(), `"openai":"work"`) {
t.Errorf("options set: %d %s", w.Code, w.Body)
}
}
// Two plugins asking to replace one built-in page: the first in
// plugins.json's order takes its place, the other is a page of its own.
func TestPluginPageReplacesFirstWins(t *testing.T) {
_, _, first, second := panelPlugins(t)
var pages []pluginPage
w := do(pageMux(), httptest.NewRequest("GET", "/api/plugin-pages", nil))
if err := json.Unmarshal(w.Body.Bytes(), &pages); err != nil || len(pages) != 2 {
t.Fatalf("pages: %s %v", w.Body, err)
}
if pages[0].Spec != first || pages[0].Replaces != "usage" {
t.Errorf("the first: %+v", pages[0])
}
if pages[1].Spec != second || pages[1].Replaces != "" {
t.Errorf("the second: %+v", pages[1])
}
}