Files
magpie/internal/gui/web_app_test.go
T
RainierandClaude Opus 5.5 4d9b798d50 web: a LazyCat box's administrators open the page with the box's sign-in (MAGPIE_WEB_SIGN_IN=lazycat) (#5987)
magpie in a LazyCat app (懒猫微服) is opened from the box's app list by
someone signed in to the box already, and asks for a key they never
saw: it is in the container's log. A package can only hand the key to
every browser that reaches the app, or put a proxy in front that adds
the key's cookie to what the box signed in.

The box's ingress, lzc-ingress, sends a browser that isn't signed in to
the box's login page, and puts on every request it passes the app the
box account (X-HC-User-ID), its role (X-HC-User-Role, ADMIN or NORMAL)
and what sent it (X-HC-Source, client for a browser), in place of what
the caller sent. With MAGPIE_WEB_SIGN_IN=lazycat webGuard takes that
sign-in besides the key: lazyCatSignIn lets in an ADMIN account sent by
a browser, each of the three named once, and tells anyone else the box's
reason.

The box's sign-in is a cookie of the box's, and the box's apps are one
site, so a browser sends it with another app's page's requests too: an
earlier build of this change let another app's page on the box include
/boot.js and read window.bootPrefs. So it is taken only for what the
page itself or the user asked for (boxFetched, the Fetch Metadata:
Sec-Fetch-Site same-origin or none, or a GET or HEAD navigation to a
document from another page), never for another page's script, frame,
fetch or form POST, nor from a browser that sends no Fetch Metadata.

It sets no cookie of the page's own, so signing out of the box signs out
of the page. The key's link and cookie work as before, /api still
answers the page alone (webOwnPage), and the gateway's client routes on
the page's port go to the gateway first (onePort), which asks for a
gateway key. StartWeb refuses another value, and lazycat where
LAZYCAT_APP_DOMAIN, which LazyCat sets in an app's containers, isn't
set: all magpie can check, so the setting is the package's word that the
box's ingress is the only way to the page's port. magpie web prints the
box's address beside the link.

Docs: reference.md's new LazyCat section, with a manifest and what must
never reach the page's port, and gui-shell.md's Browser mode row.

On a box (lzcos 1.6.2+fix.4), a probe app that echoes its request
headers: a signed-in browser's request carries X-HC-User-ID,
X-HC-User-Role ADMIN and X-HC-Source client, forged ones replaced; not
signed in, / goes to the login page and a public path gets none of the
three (forged ones taken off, repeated or in lower case too), while
X-HC-User-Groups passes on as the caller wrote it, so it is never read;
a TCP ingress passes every header as sent. Another app's container
reaches the app through the ingress alone (straight to the app's
container it times out); the box itself, and a container in its network
(network_mode: host, which a manifest may set), reach the port.

A test app made from the docs' manifest, running a build of this change
on 68cb92e8e in the image's place as its user (uid 65532): the box's
administrator opens the console with no key, and no cookie is set;
/v1/models still asks for a gateway key; from another app's page a
navigation opens the console, while a script include of /boot.js and a
frame are turned away; in the container, past the ingress, a request
with no Fetch Metadata, no X-HC-Source, NORMAL or a header twice gets a
401. Bound to /lzcapp/var/config, which the box makes as root's, magpie
couldn't write /config; bound to /lzcapp/var it can, and a gateway key
outlived the container.

Tests, through webServed with the headers the probe saw:
TestLazyCatSignInOpensThePage, TurnsAway, AsksWhereFrom, IsAskedEachTime
and IsNoGatewayKey (the client routes, with each sign-in that opens the
page), and TestWebBoxSignInChecksItsValue.
TestRemoteOpensTheOtherMagpie, new on main, gives webHandler no box
sign-in.

Run, at this tree, on 6c3f113ce: Docker golang:1.26.8 (linux/arm64):
gofmt clean; go vet -tags gtk3 ./... (with the GTK and WebKitGTK
headers, as CI), -tags nogui and GOOS=windows clean; both builds ok.
macOS 27.2 (go1.26.8, not root, a temporary HOME): go vet ./... and the
two cross vets clean, the three builds ok; go test -tags nogui ./...,
TestScriptFindsClaudeMoved skipped (it runs the real
/Applications/Claude.app, #5989): 92 packages ok; red outside
this change, each red the same at 6c3f113ce:
TestBunProxyLoginWithReservedCharacters (#3397),
TestGitUpdateInstallsTheBranchsCommitNow and
TestGitUpdateKeepsACommitPin (#5988), on this Mac's bun 1.3.11,
older than MinBun; TestEveryRouteHasACommandOrIsNamed: POST
/api/settings/join, new with e053c337a, has no command. /join, new
with it too, is a client route, so the docs' manifest lists it.

Broken by hand, each red, all green again put back; a break that lets in
what must be turned away was seen to reach the page: TurnsAway with the
once-each check out, no sender taken, the role in any case, the role or
the sender check out (IsAskedEachTime too), app:… and system alone
turned away, or the key's "open the link" kept in the box's 401;
AsksWhereFrom with boxFetched out, no Fetch Metadata taken, another
page's navigation taken of any method or into a frame, an object or an
embed (or anything but an iframe), its request for a document that isn't
a navigation, or another app's page's script (same-site, no-cors);
OpensThePage with another page's navigation taken by GET alone, or none
taken (IsNoGatewayKey too), a cookie set, or webOwnPage out;
IsAskedEachTime with the first sign-in kept; ChecksItsValue with lazycat
taken outside LazyCat or StartWeb not asking webBoxSignIn's error;
IsNoGatewayKey with the client routes behind the box's sign-in, or one
the box signs in on, or a HEAD to one, given to the page;
TestLazyCatManifestListsTheClientRoutes with /me out of the docs.

Not tried: a NORMAL account in a real browser (the box has one
account); signing out of the box in a browser; the box's own client
apps opening the page; a browser without Fetch Metadata; a header named
twice on a signed-in request through the ingress (a browser can't send
one); a multi-instance app; another lzcos version; a community plugin's
page on the box; a real vendor call through the box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:15:40 +08:00

140 lines
4.5 KiB
Go

package gui
import (
"bytes"
"encoding/json"
"fmt"
"image"
_ "image/png"
"net/http"
"net/http/httptest"
"path/filepath"
"regexp"
"strings"
"testing"
)
// magpie web added to an iPhone's home screen opened in Safari, with its
// address bar (ninja_s6114 on Discord): the page named no web app
// manifest and no apple-mobile-web-app-capable. Now it does, and the
// manifest and the icons it and the page name are served, with their
// types, to a browser that asks for them without the page's cookie, as a
// home screen or an install prompt may. Nothing else is.
func TestWebAppAddsToHomeScreen(t *testing.T) {
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"))
const key = "0123456789abcdef-key"
srv := webHandler("3430", key, 0, nil, webPageHandler(t, webHost{}, nil))
do := func(method, path string, signedIn bool) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, path, nil)
if signedIn {
r.AddCookie(&http.Cookie{Name: "magpie_web_3430", Value: key})
}
rec := httptest.NewRecorder()
srv.ServeHTTP(rec, r)
return rec
}
page := do("GET", "/", true)
if page.Code != http.StatusOK {
t.Fatalf("the page, signed in: %d", page.Code)
}
html := page.Body.String()
for _, want := range []string{
`<meta name="apple-mobile-web-app-capable" content="yes">`,
`<meta name="mobile-web-app-capable" content="yes">`,
`<meta name="apple-mobile-web-app-status-bar-style"`,
} {
if !strings.Contains(html, want) {
t.Errorf("the page lacks %s", want)
}
}
// a theme colour a browser's tab would take too would change how magpie
// web looks in Safari and Chrome; only the app's window takes it
for _, m := range regexp.MustCompile(`<meta name="theme-color"[^>]*>`).FindAllString(html, -1) {
if !strings.Contains(m, `media="(display-mode: standalone)`) {
t.Errorf("a theme colour outside standalone: %s", m)
}
}
link := func(rel string) string {
m := regexp.MustCompile(`<link rel="` + rel + `" href="([^"]+)"`).FindStringSubmatch(html)
if m == nil {
t.Fatalf("the page names no %s", rel)
}
return "/" + m[1]
}
// type and size of the png at path, fetched with no cookie
icon := func(path, sizes string) {
rec := do("GET", path, false)
if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "image/png" {
t.Errorf("%s without the cookie: %d %q", path, rec.Code, rec.Header().Get("Content-Type"))
return
}
c, _, err := image.DecodeConfig(bytes.NewReader(rec.Body.Bytes()))
if err != nil {
t.Errorf("%s: %v", path, err)
return
}
if got := fmt.Sprintf("%dx%d", c.Width, c.Height); got != sizes {
t.Errorf("%s is %s, named %s", path, got, sizes)
}
}
icon(link("apple-touch-icon"), "180x180")
mf := link("manifest")
rec := do("GET", mf, false)
if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json") {
t.Fatalf("%s without the cookie: %d %q", mf, rec.Code, rec.Header().Get("Content-Type"))
}
var m struct {
StartURL string `json:"start_url"`
Icons []struct{ Src, Sizes, Type string }
}
if err := json.Unmarshal(rec.Body.Bytes(), &m); err != nil {
t.Fatal(err)
}
var raw map[string]any
json.Unmarshal(rec.Body.Bytes(), &raw)
if raw["name"] != "magpie" || raw["display"] != "standalone" || m.StartURL == "" {
t.Errorf("manifest: name %v, display %v, start_url %q", raw["name"], raw["display"], m.StartURL)
}
big := false
for _, ic := range m.Icons {
icon("/"+ic.Src, ic.Sizes)
big = big || ic.Sizes == "512x512"
}
if !big {
t.Error("the manifest has no 512px icon, which Chrome on Android wants to install the page")
}
if rec := do("HEAD", mf, false); rec.Code != http.StatusOK {
t.Errorf("HEAD %s without the cookie: %d", mf, rec.Code)
}
// every other file and route still wants the key, and so do these
// files asked for any other way
for _, c := range []struct{ method, path string }{
{"GET", "/"},
{"GET", "/index.html"},
{"GET", "/app.js"},
{"GET", "/boot.js"},
{"GET", "/icons/favicon.svg"},
{"GET", "/icons/magpie.svg"},
{"GET", "/api/state"},
{"GET", "/api/providers"},
{"GET", "/manifest.json/"},
{"GET", "/Manifest.json"},
{"GET", "/icons/../app.js"},
{"GET", "/icons/apple-touch-icon.png/../../app.js"},
{"POST", "/manifest.json"},
{"PUT", "/icons/icon-512.png"},
} {
if rec := do(c.method, c.path, false); rec.Code != http.StatusUnauthorized {
t.Errorf("%s %s without the cookie: %d, want 401", c.method, c.path, rec.Code)
}
}
}