Files
magpie/internal/gui/remote_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

182 lines
7.2 KiB
Go

package gui
import (
"encoding/json"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"os"
"runtime"
"strings"
"testing"
"time"
)
// remoteWin is the app's windows, as far as another magpie's window goes:
// the links it was asked to open.
type remoteWin struct {
Windows
opened []string
}
func (w *remoteWin) OpenRemote(link, title string) { w.opened = append(w.opened, link) }
func remotePost(t *testing.T, w Windows, path, body string) (int, string) {
t.Helper()
mux := http.NewServeMux()
remoteRoutes(mux, w)
r := httptest.NewRequest("POST", path, strings.NewReader(body))
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, r)
return rec.Code, rec.Body.String()
}
func jsonStr(s string) string { b, _ := json.Marshal(s); return string(b) }
// What is typed as the other magpie's address: the link it printed, with
// its key taken out, or a bare address; plain http only where the key
// doesn't cross the internet.
func TestRemoteAddr(t *testing.T) {
for _, c := range []struct{ in, addr, key, err string }{
{"https://magpie.example.com/?k=0123456789abcdef-key", "https://magpie.example.com/", "0123456789abcdef-key", ""},
{"magpie.example.com:3430", "https://magpie.example.com:3430/", "", ""},
{"http://192.168.1.20:3430/?k=abc&view=usage#x", "http://192.168.1.20:3430/?view=usage", "abc", ""},
{"http://100.101.1.2:3430", "http://100.101.1.2:3430/", "", ""},
{"http://nas.local:3430", "http://nas.local:3430/", "", ""},
{"http://server:3430", "http://server:3430/", "", ""},
{"https://example.com/magpie/", "https://example.com/magpie/", "", ""},
{"http://magpie.example.com:3430", "", "", "name on the internet"},
{"https://u:p@magpie.example.com", "", "", "user name"},
{"ftp://example.com", "", "", "http:// or https://"},
{"file:///etc/passwd", "", "", "isn't an address"},
{" ", "", "", "type the other"},
} {
addr, key, err := remoteAddr(c.in)
if c.err != "" {
if err == nil || !strings.Contains(err.Error(), c.err) {
t.Errorf("%q: err %v, want %q", c.in, err, c.err)
}
continue
}
if err != nil || addr != c.addr || key != c.key {
t.Errorf("%q: %q %q %v, want %q %q", c.in, addr, key, err, c.addr, c.key)
}
}
}
// xuanwo on X: the app opens a server's magpie, its routing and usage, in
// a window. The key is checked against that magpie's own page before the
// window opens, kept 0600 on this computer, never read back into the page,
// and the link the window opens signs in to the other magpie's page as a
// browser does.
func TestRemoteOpensTheOtherMagpie(t *testing.T) {
onePortHome(t)
const key = "0123456789abcdef-remote"
reached := 0
other := httptest.NewServer(webHandler("3430", key, webCookieAge, nil, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
reached++
rw.WriteHeader(http.StatusTeapot)
})))
defer other.Close()
w := &remoteWin{}
// a wrong key: said, nothing opened, nothing kept
code, body := remotePost(t, w, "/api/remote", `{"url":`+jsonStr(other.URL)+`,"key":"0123456789abcdef-wrong"}`)
if code != http.StatusBadRequest || !strings.Contains(body, "turned the key away") || len(w.opened) != 0 || reached != 0 {
t.Fatalf("wrong key: %d %s %v", code, body, w.opened)
}
if _, err := os.Stat(remoteFile()); !os.IsNotExist(err) {
t.Fatalf("a refused key was kept: %v", err)
}
// no key at all
if code, body := remotePost(t, w, "/api/remote", `{"url":`+jsonStr(other.URL)+`}`); code != http.StatusBadRequest || !strings.Contains(body, "type that magpie's key") {
t.Fatalf("no key: %d %s", code, body)
}
// the link it printed, pasted whole
code, body = remotePost(t, w, "/api/remote", `{"url":`+jsonStr(other.URL+"/?k="+key)+`}`)
if code != http.StatusOK || len(w.opened) != 1 || w.opened[0] != other.URL+"/?k="+key {
t.Fatalf("open: %d %s %v", code, body, w.opened)
}
if strings.Contains(body, key) {
t.Fatalf("the key went back to the page: %s", body)
}
if reached != 0 {
t.Fatal("the check read the page behind the key")
}
fi, err := os.Stat(remoteFile())
if err != nil {
t.Fatal(err)
}
if runtime.GOOS != "windows" && fi.Mode().Perm() != 0o600 {
t.Fatalf("remote-magpie.json is %v", fi.Mode().Perm())
}
mux := http.NewServeMux()
remoteRoutes(mux, w)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest("GET", "/api/remote", nil))
if s := rec.Body.String(); strings.Contains(s, key) || !strings.Contains(s, `"hasKey":true`) || !strings.Contains(s, other.URL) {
t.Fatalf("GET /api/remote: %s", s)
}
// the window's link signs in to the other magpie's page, as a browser
jar, _ := cookiejar.New(nil)
res, err := (&http.Client{Jar: jar, Timeout: 5 * time.Second}).Get(w.opened[0])
if err != nil {
t.Fatal(err)
}
res.Body.Close()
if res.StatusCode != http.StatusTeapot || reached != 1 || strings.Contains(res.Request.URL.String(), key) {
t.Fatalf("the window's link: %d at %s, reached %d", res.StatusCode, res.Request.URL, reached)
}
// opened again without the key: the one kept for the address
if code, body := remotePost(t, w, "/api/remote", `{"url":`+jsonStr(other.URL)+`}`); code != http.StatusOK || len(w.opened) != 2 || w.opened[1] != other.URL+"/?k="+key {
t.Fatalf("again: %d %s %v", code, body, w.opened)
}
// forgotten
if code, _ := remotePost(t, w, "/api/remote/forget", `{}`); code != http.StatusOK {
t.Fatalf("forget: %d", code)
}
if _, err := os.Stat(remoteFile()); !os.IsNotExist(err) {
t.Fatalf("forgotten, still there: %v", err)
}
}
// Something at the address that isn't a magpie page, or none: said, and
// no window opened.
func TestRemoteNotMagpie(t *testing.T) {
onePortHome(t)
plain := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
http.Redirect(rw, r, "/login", http.StatusSeeOther) // a redirect with no magpie cookie
}))
defer plain.Close()
w := &remoteWin{}
if code, body := remotePost(t, w, "/api/remote", `{"url":`+jsonStr(plain.URL)+`,"key":"0123456789abcdef-key"}`); code != http.StatusBadRequest || !strings.Contains(body, "not as a magpie page") || len(w.opened) != 0 {
t.Fatalf("not magpie: %d %s", code, body)
}
plain.Close()
if code, body := remotePost(t, w, "/api/remote", `{"url":`+jsonStr(plain.URL)+`,"key":"0123456789abcdef-key"}`); code != http.StatusBadRequest || !strings.Contains(body, "doesn't answer") || len(w.opened) != 0 {
t.Fatalf("gone: %d %s", code, body)
}
}
// A page served to a browser (magpie web, the app's Browser access) has no
// /api/remote: only the app's own windows open another magpie, and a
// browser can't read or change the key kept for it.
func TestRemoteNotOnBrowserPages(t *testing.T) {
onePortHome(t)
h := webPageHandler(t, webHost{}, nil)
for _, m := range []string{"GET", "POST"} {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(m, "/api/remote", strings.NewReader(`{"url":"http://127.0.0.1:1"}`)))
if rec.Code == http.StatusOK || strings.Contains(rec.Body.String(), "hasKey") {
t.Fatalf("%s /api/remote on a browser's page: %d %s", m, rec.Code, rec.Body.String())
}
}
// and a host that can't open windows refuses rather than keeping it
if code, body := remotePost(t, webHost{}, "/api/remote", `{"url":"http://127.0.0.1:1/?k=0123456789abcdef-key"}`); code != http.StatusBadRequest || !strings.Contains(body, "only the app") {
t.Fatalf("browser host: %d %s", code, body)
}
}