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

214 lines
7.0 KiB
Go

package gui
import (
"encoding/json"
"io"
"io/fs"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/provider"
)
// #1545 (thedavidweng): Detect APIs and Each picked model ask with the
// form as it stands, not saved: a new provider's typed key and the models
// typed in its Models field, a saved one's picks not saved yet with its
// saved key when none is typed, and a copy not saved yet with the key of
// the one it copies. None of it writes anything: providers.json and the
// rest of the config folder are as they were, and no provider is added.
func TestProviderDetectDraft(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", os.Getenv("HOME"))
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
var mu sync.Mutex
var asked []string
// a relay with no model list (its /v1/models is a 404) that chats only
// for the model typed in the form, "draft-m", and the keys it knows
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var body struct{ Model string }
json.Unmarshal(b, &body)
auth := r.Header.Get("Authorization")
mu.Lock()
asked = append(asked, r.Method+" "+r.URL.Path+" "+body.Model+" "+auth)
mu.Unlock()
if r.URL.Path != "/v1/chat/completions" {
http.NotFound(w, r)
return
}
if auth != "Bearer sk-typed" && auth != "Bearer sk-saved" {
http.Error(w, `{"error":{"message":"invalid api key"}}`, http.StatusUnauthorized)
return
}
if body.Model != "draft-m" {
http.Error(w, `{"error":{"message":"model not found"}}`, http.StatusNotFound)
return
}
io.WriteString(w, `{"choices":[{"message":{"content":"hi"}}]}`)
}))
defer up.Close()
mux := http.NewServeMux()
providerRoutes(mux, nil)
post := func(h http.Handler, action, body string) *httptest.ResponseRecorder {
t.Helper()
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/"+action, strings.NewReader(body)))
return w
}
type answer struct {
Results []provider.Detection
Models []provider.ModelDetection
}
detect := func(body string) answer {
t.Helper()
w := post(mux, "detect", body)
if w.Code != 200 {
t.Fatalf("%s: %d %s", body, w.Code, w.Body)
}
var got answer
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
return got
}
chat := func(rs []provider.Detection) provider.Detection {
for _, r := range rs {
if r.Protocol == provider.Chat {
return r
}
}
t.Fatalf("no chat in %+v", rs)
return provider.Detection{}
}
keys := func() []string {
mu.Lock()
defer mu.Unlock()
var out []string
for _, a := range asked {
if strings.Contains(a, "/chat/completions") {
out = append(out, a[strings.LastIndex(a, " ")+1:])
}
}
asked = nil
return out
}
base := up.URL + "/v1"
// a new provider: the key just typed and the models typed in its form
if r := chat(detect(`{"typed":true,"key":"sk-typed","base":"` + base + `","model":"","picked":["draft-m","other"]}`).Results); !r.OK || r.Model != "draft-m" {
t.Fatalf("new, models typed: %+v", r)
}
if got := keys(); len(got) != 1 || got[0] != "sk-typed" {
t.Fatalf("new asked with %v", got)
}
got := detect(`{"typed":true,"key":"sk-typed","base":"` + base + `","detectModels":["draft-m","gone"]}`)
if len(got.Models) != 2 || !chat(got.Models[0].Results).OK || chat(got.Models[1].Results).OK {
t.Fatalf("new, each model: %+v", got.Models)
}
keys()
if ps := provider.All(); len(ps) != 0 {
t.Fatalf("a detection added %v", ps)
}
// a saved provider, its key shown masked and not typed again, with a
// model picked in the form and not saved
if w := post(mux, "save", `{"id":"relay","name":"Relay","key":"sk-saved","chat":"`+base+`","models":["saved-m"],"new":true}`); w.Code != 200 {
t.Fatalf("%d %s", w.Code, w.Body)
}
keys()
before := draftFiles(t, appdir.Config())
if _, ok := before["providers.json"]; !ok {
t.Fatalf("no providers.json in %v", before)
}
if r := chat(detect(`{"id":"relay","typed":true,"key":"","base":"` + base + `","model":"","picked":["draft-m"]}`).Results); !r.OK || r.Model != "draft-m" {
t.Fatalf("saved, a pick not saved: %+v", r)
}
if got := keys(); len(got) != 1 || got[0] != "sk-saved" {
t.Fatalf("saved asked with %v", got)
}
// a copy of it, not saved yet, with no key typed: the copied one's key
if r := chat(detect(`{"new":true,"copyOf":"relay","typed":true,"key":"","base":"` + base + `","model":"","picked":["draft-m"]}`).Results); !r.OK {
t.Fatalf("copy: %+v", r)
}
if got := keys(); len(got) != 1 || got[0] != "sk-saved" {
t.Fatalf("copy asked with %v", got)
}
// a key typed over the saved one is the one asked with
if r := chat(detect(`{"new":true,"copyOf":"relay","typed":true,"key":"sk-typed","base":"` + base + `","model":"draft-m"}`).Results); !r.OK {
t.Fatalf("copy, key typed: %+v", r)
}
if got := keys(); len(got) != 1 || got[0] != "sk-typed" {
t.Fatalf("copy with a key typed asked with %v", got)
}
// the request log is the one file a detection writes: each request it
// sent, as magpie's own (usage.SourceProbe), and nothing else changes
after := draftFiles(t, appdir.Config())
logBefore, logAfter := before["usage.jsonl"], after["usage.jsonl"]
delete(before, "usage.jsonl")
delete(after, "usage.jsonl")
if !draftSame(before, after) {
t.Fatalf("a detection wrote to the config folder:\nbefore %v\nafter %v", draftNames(before), draftNames(after))
}
if added := strings.TrimPrefix(logAfter, logBefore); added == logAfter || !strings.Contains(added, `"source":"probe"`) ||
!strings.Contains(added, `"kind":"api_detect"`) || strings.Contains(added, "sk-") {
t.Fatalf("the request log has no detection of its own:\n%s", added)
}
if ps := provider.All(); len(ps) != 1 || ps[0].ID != "relay" || len(ps[0].Models) != 1 {
t.Fatalf("providers now %+v", ps)
}
// magpie web: without its key a draft probe is turned away, and the
// vendor is never asked
guarded := webHandler("3999", "0123456789abcdef-1545", time.Hour, nil, mux)
if w := post(guarded, "detect", `{"typed":true,"key":"sk-typed","base":"`+base+`","picked":["draft-m"]}`); w.Code != http.StatusUnauthorized {
t.Fatalf("no web key: %d %s", w.Code, w.Body)
}
if got := keys(); len(got) != 0 {
t.Fatalf("asked without the web key: %v", got)
}
}
// draftFiles is every file under dir, by its path, with its bytes.
func draftFiles(t *testing.T, dir string) map[string]string {
t.Helper()
out := map[string]string{}
filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return nil
}
b, _ := os.ReadFile(p)
rel, _ := filepath.Rel(dir, p)
out[filepath.ToSlash(rel)] = string(b)
return nil
})
return out
}
func draftSame(a, b map[string]string) bool {
if len(a) != len(b) {
return false
}
for k, v := range a {
if w, ok := b[k]; !ok || w != v {
return false
}
}
return true
}
func draftNames(m map[string]string) []string {
var out []string
for k := range m {
out = append(out, k)
}
return out
}