From e053c337aa6a9111ba88c91016684554c0918ff2 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 10 Nov 2026 22:32:27 +0800 Subject: [PATCH] gateway: join a shared magpie with a password (EV_John_Liu on X) EV_John_Liu asked for quick setup on a LAN: the central magpie serves a page behind a password where other PCs and Macs get their config and a new key of their own. Settings -> Network and sharing -> Join with a password sets the password (at least 8 characters; only a salted PBKDF2-SHA256 hash is kept, in join.json, 0600, written through temp-and-rename; a file that can't be read or parsed means joining is closed). The row then shows the address to give out, /join, and Turn off joining. /join is the key page (/me) opened to join: the visitor types a name for the computer and the password. POST /v1/magpie/join makes a gateway key named after that computer (or "Joined from "). The key is listed in Gateway keys like any other, where it can be limited or removed. The page shows the key once and then the setup for that key: Claude Code, Codex, a new magpie tab (`magpie provider add remote-magpie '' url='
'`), OpenAI-compatible and curl. Every route judged: - lanGuard lets another machine reach GET /join and the join route without a key, only while magpie is shared. The route checks the password itself. - A browser's POST must come from the page itself. Host must be one of this computer's own names (IP, localhost, MAGPIE_PUBLIC_URL's, its hostname), so a DNS-rebound name is refused. Origin must equal Host. Missing Origin and Origin "null" are refused, and so is any Sec-Fetch-Site but same-origin. corsGuard still refuses null, foreign and *.localhost Origins before this. curl and scripts, which send no browser marks, are judged on the password alone. - Throttle: each try from another machine costs a token, a right password too. The bucket holds 10 and refills one every 10s, so a guesser gets about 360 tries an hour, and a flood of tries makes no flood of keys. Over the limit the route answers 429 with Retry-After. - The password and key never go in a URL or a log line. The key comes back only in a no-store 201 body. Logs name the key's id and the caller's address. - The routes are classed in the key-slot and read-only route lists. They carry no key. Run on mote at this head (rebased on 065ca02c2): - gofmt clean - go vet: darwin, linux -tags nogui and windows, for access, gateway and gui - go test: access, gui, and gateway's join, route-list, key page and LAN tests - The whole gateway package ran before the rebase, and its only reds were the two route-list guards fixed here. - GUI (node --test), chromium and webkit: lan-join (new), key-page, mtls-settings, allow-ips, i18n-keys, lan-docker, lan-lazycat, lan-address-height, side-gateway-lan: all ok before the rebase, and lan-join, key-page and i18n-keys ok again at this head. - That GUI run caught a TDZ error: JOINING was read before its const, which broke /me too. It is fixed in this commit, and key-page went from red to green. Broken by hand (each red, then put back): - no throttle: TestJoinHoldsAGuesser red - no lanGuard bypass: TestJoinMakesARevocableKey, TestJoinHoldsAGuesser and TestJoinClosed red - no ownHost check: TestJoinRefusesOtherPages red - joinRefusal returning "": rebound remote, cross-site and no-Origin browser POSTs each got a 201, red - Dropping only the Origin comparison stayed green, because corsGuard refuses the same Origins first. Not tried: - a real two-machine LAN join with the built app - a Windows or Linux run of the tests (vet only) - the full suite, which starts after the tag --- docs/subsystems/gateway-routing.md | 28 ++ internal/access/join.go | 148 ++++++++++ internal/access/join_test.go | 51 ++++ internal/gateway/gateway.go | 5 + internal/gateway/join.go | 195 +++++++++++++ internal/gateway/join_test.go | 261 ++++++++++++++++++ internal/gateway/key_slots_test.go | 2 +- internal/gateway/keypage.html | 118 +++++++- internal/gateway/lan.go | 7 + internal/gateway/oneport.go | 2 + internal/gateway/readonly.go | 4 + internal/gui/api.go | 5 + internal/gui/assets/i18n.js | 32 +++ .../gui/assets/plugins/gateway/settings.js | 52 ++++ internal/gui/join.go | 31 +++ internal/gui/tests/lan-join.test.cjs | 209 ++++++++++++++ 16 files changed, 1141 insertions(+), 9 deletions(-) create mode 100644 internal/access/join.go create mode 100644 internal/access/join_test.go create mode 100644 internal/gateway/join.go create mode 100644 internal/gateway/join_test.go create mode 100644 internal/gui/join.go create mode 100644 internal/gui/tests/lan-join.test.cjs diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 17220f63c..7bea66dc8 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -886,6 +886,34 @@ shared and with a key (`gatewayKeyPage` in `keys.js`). `key_page.go`, and [`key_page_test.go`](../../internal/gateway/key_page_test.go); `internal/gui/tests/key-page.test.cjs` drives the page itself. +`GET /join` is the same page as the join page (EV_John_Liu on X): with a +password set in Settings → Local network → Join with a password +(`POST /api/settings/join`, `internal/gui/join.go`), another computer +opens it, types the password and a name for itself, and gets a gateway +key of its own (`access.Update("add-key")`, named for it or "Joined from +
"), shown once and then filled into the page's setup, which adds +a magpie tab (`magpie provider add remote-magpie`). The key is listed in +Gateway keys and is limited, turned off or removed there like any other. +Only a salted PBKDF2-SHA256 hash of the password is kept, in `join.json` +(`internal/access/join.go`, 0600, temp and rename); a file that can't be +read or parsed means joining is closed. `lanGuard` lets `GET /join` and +`GET`/`POST /v1/magpie/join` (`joinPageOpen`, `joinAsked`) through +without a key, after the allow list, the rebinding check, mTLS and the +not-shared refusal. `joinKey` then refuses a browser's request +(`fromBrowser`) unless the Host is this computer's own (`ownHost`: no +rebound name, no `*.localhost`) and the Origin is that same address, not +missing and not `null`, with `Sec-Fetch-Site` same-origin where sent; +curl and scripts are judged on the password alone. Every try from another +machine takes a token from the join's own bucket (10, then one each 10s), +the right password too, so a guesser and a flood of keys are both held +with 429 and `Retry-After`. Neither the password nor the key is logged, +and the key goes back in a `no-store` body only. `join.go`, and +`TestJoinMakesARevocableKey`, `TestJoinHoldsAGuesser`, +`TestJoinRefusesOtherPages` and `TestJoinClosed` in +[`join_test.go`](../../internal/gateway/join_test.go), `TestJoinPassword` +in `internal/access`; `internal/gui/tests/lan-join.test.cjs` drives the +page and the Settings rows. + System One uses `RouteDecider` and `postDecide` in [`decide.go`](../../internal/gateway/decide.go), taking one provider prefix off at each hop and preserving the state, questions and vendor errors. diff --git a/internal/access/join.go b/internal/access/join.go new file mode 100644 index 000000000..91ab9e4cf --- /dev/null +++ b/internal/access/join.go @@ -0,0 +1,148 @@ +package access + +import ( + "crypto/pbkdf2" + "crypto/rand" + "crypto/sha256" + "crypto/subtle" + "encoding/json" + "errors" + "os" + "path/filepath" + "sync" + "time" + "unicode/utf8" + + "github.com/yetone/magpie/internal/settings" +) + +// The join password (EV_John_Liu on X): while magpie is shared, another +// computer on the network opens the gateway's /join page, types this +// password and gets a gateway key of its own, with the setup for its +// agents. Only a salted PBKDF2-SHA256 hash of it is kept, in join.json +// beside caller-keys.json: this computer's own, never synced or backed up +// with the settings, and never shown again once set. A file that can't be +// read or parsed means join is closed: a failed read is unknown, never an +// open door. + +// JoinMinLen is the fewest characters a join password may have. +const JoinMinLen = 8 + +// joinIter is PBKDF2's rounds; a variable so the tests run quickly. +var joinIter = 210_000 + +type joinFile struct { + Salt []byte `json:"salt"` + Hash []byte `json:"hash"` + Iter int `json:"iter"` + Set time.Time `json:"set"` +} + +var joinMu sync.Mutex + +// JoinPath is the file the join password's hash is kept in. +func JoinPath() string { return filepath.Join(settings.Dir(), "join.json") } + +func readJoin() (joinFile, bool) { + b, err := os.ReadFile(JoinPath()) + if err != nil { + return joinFile{}, false + } + var f joinFile + if json.Unmarshal(b, &f) != nil || len(f.Salt) < 16 || len(f.Hash) != sha256.Size || f.Iter < 1 { + return joinFile{}, false + } + return f, true +} + +// JoinOn: a join password is set, and readable. +func JoinOn() bool { + joinMu.Lock() + defer joinMu.Unlock() + _, ok := readJoin() + return ok +} + +// JoinSince is when the join password was set; zero when none is. +func JoinSince() time.Time { + joinMu.Lock() + defer joinMu.Unlock() + f, _ := readJoin() + return f.Set +} + +// SetJoinPassword sets the join password, or with "" clears it, which +// closes the join page. Keys already given out stay until each is removed +// in Gateway keys. +func SetJoinPassword(pw string) error { + joinMu.Lock() + defer joinMu.Unlock() + if pw == "" { + if err := os.Remove(JoinPath()); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return nil + } + if utf8.RuneCountInString(pw) < JoinMinLen { + return errors.New("Use a password of at least 8 characters") + } + if len(pw) > 1024 { + return errors.New("Use a password of at most 1024 bytes") + } + salt := make([]byte, 16) + if _, err := rand.Read(salt); err != nil { + return err + } + h, err := pbkdf2.Key(sha256.New, pw, salt, joinIter, sha256.Size) + if err != nil { + return err + } + b, err := json.Marshal(joinFile{Salt: salt, Hash: h, Iter: joinIter, Set: time.Now().UTC()}) + if err != nil { + return err + } + return writePrivate(JoinPath(), b) +} + +// JoinPasswordOK: pw is the join password. None set, or a file that can't +// be read, lets no password in. +func JoinPasswordOK(pw string) bool { + joinMu.Lock() + f, ok := readJoin() + joinMu.Unlock() + if !ok || pw == "" || len(pw) > 1024 { + return false + } + h, err := pbkdf2.Key(sha256.New, pw, f.Salt, f.Iter, sha256.Size) + return err == nil && subtle.ConstantTimeCompare(h, f.Hash) == 1 +} + +// writePrivate writes b to path through a temp file renamed over it, +// readable by this user alone. +func writePrivate(path string, b []byte) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".tmp-*") + if err != nil { + return err + } + name := tmp.Name() + defer os.Remove(name) + if err := tmp.Chmod(0o600); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(append(b, '\n')); err != nil { + tmp.Close() + return err + } + if err := tmp.Sync(); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(name, path) +} diff --git a/internal/access/join_test.go b/internal/access/join_test.go new file mode 100644 index 000000000..8e4de91a5 --- /dev/null +++ b/internal/access/join_test.go @@ -0,0 +1,51 @@ +package access + +import ( + "os" + "strings" + "testing" +) + +func init() { joinIter = 1000 } + +func TestJoinPassword(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + if JoinOn() || JoinPasswordOK("") || JoinPasswordOK("anything") { + t.Fatal("open with no password") + } + if err := SetJoinPassword("short"); err == nil { + t.Fatal("a 5-character password was taken") + } + if err := SetJoinPassword("long enough pw"); err != nil { + t.Fatal(err) + } + if !JoinOn() || !JoinPasswordOK("long enough pw") || JoinPasswordOK("long enough pW") || JoinPasswordOK("") { + t.Fatal("password check") + } + b, err := os.ReadFile(JoinPath()) + if err != nil { + t.Fatal(err) + } + if string(b) == "" || strings.Contains(string(b), "long enough") { + t.Fatalf("join.json holds the password: %s", b) + } + if fi, _ := os.Stat(JoinPath()); fi.Mode().Perm() != 0o600 && os.PathSeparator == '/' { + t.Errorf("mode %v", fi.Mode()) + } + // a file that can't be parsed shuts the door + if err := os.WriteFile(JoinPath(), []byte(`{"salt":"","hash":"","iter":0}`), 0o600); err != nil { + t.Fatal(err) + } + if JoinOn() || JoinPasswordOK("long enough pw") || JoinPasswordOK("") { + t.Fatal("a broken join.json let a password in") + } + if err := SetJoinPassword("long enough pw"); err != nil { + t.Fatal(err) + } + if err := SetJoinPassword(""); err != nil { + t.Fatal(err) + } + if JoinOn() || JoinPasswordOK("long enough pw") { + t.Fatal("still open after clearing") + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 759d48a46..813719ea2 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1046,6 +1046,11 @@ func (s *Server) routes() *routeMux { mux.HandleFunc("POST "+provider.RemoteProvePath, s.prove) mux.HandleFunc("GET "+KeyPagePath, s.keyPage) mux.HandleFunc("GET "+keyPageData, s.keyInfo) + // the join page, where another computer that knows the join password + // gets a gateway key of its own (join.go) + mux.HandleFunc("GET "+JoinPagePath, s.joinPage) + mux.HandleFunc("GET "+joinData, s.joinOpen) + mux.HandleFunc("POST "+joinData, s.joinKey) // the Claude Code processes the Claude subscription runs, for magpie // claude-code runs (loopback only) mux.HandleFunc("GET "+ClaudeRunsPath, s.claudeRuns) diff --git a/internal/gateway/join.go b/internal/gateway/join.go new file mode 100644 index 000000000..74663165a --- /dev/null +++ b/internal/gateway/join.go @@ -0,0 +1,195 @@ +package gateway + +import ( + "encoding/json" + "io" + "log" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/provider" +) + +// JoinPagePath is the join page (EV_John_Liu on X): on a magpie shared on +// the network with a join password set (Settings → Network and sharing → +// Join with a password), another computer opens
/join, types the +// password and a name for itself, and gets a gateway key of its own, made +// then and listed in Gateway keys under that name, where it is limited or +// removed as any other key. The page then shows that key's setup for +// Claude Code, Codex, another magpie or any OpenAI-compatible app, as the +// key page (/me) does: it is the same page. +const JoinPagePath = "/join" + +// joinData is the join's own route: GET says whether joining is open, +// POST {password, name} makes the key. +const joinData = "/v1/magpie/join" + +// joinPageOpen: r asks for the join page itself, the key page's bytes, +// which lanGuard serves to another machine without a key while magpie is +// shared. +func joinPageOpen(r *http.Request) bool { + return r.URL.Path == JoinPagePath && r.URL.RawPath == "" && (r.Method == http.MethodGet || r.Method == http.MethodHead) +} + +// joinAsked: r is the join's route, which carries a password, not a key: +// the handler judges it (joinKey). +func joinAsked(r *http.Request) bool { + return r.URL.Path == joinData && r.URL.RawPath == "" && (r.Method == http.MethodGet || r.Method == http.MethodPost) +} + +// The join's own bucket, apart from tooManyAuthFails': each try from +// another machine takes a token, a right password too (each makes a key), +// so a guesser gets joinBurst tries and then one each joinRefill — 360 an +// hour against a password of 8 characters or more — and a flood of tries +// makes no flood of keys. A right key elsewhere is never held by it. +const ( + joinBurst = 10 + joinRefill = 10 * time.Second +) + +var joinThrottle = struct { + sync.Mutex + tokens float64 + last time.Time + now func() time.Time +}{tokens: joinBurst, now: time.Now} + +// tooManyJoins takes one try's token; over when there is none, with the +// wait until one refills. +func tooManyJoins() (over bool, retry time.Duration) { + t := &joinThrottle + t.Lock() + defer t.Unlock() + now := t.now() + if t.last.IsZero() { + t.last = now + } + t.tokens = min(joinBurst, t.tokens+now.Sub(t.last).Seconds()/joinRefill.Seconds()) + t.last = now + if t.tokens >= 1 { + t.tokens-- + return false, 0 + } + return true, time.Duration((1 - t.tokens) * float64(joinRefill)) +} + +func resetJoinThrottle() { + t := &joinThrottle + t.Lock() + t.tokens, t.last, t.now = joinBurst, time.Time{}, time.Now + t.Unlock() +} + +// joinPage serves the key page, which reads from its address that it is +// the join page. +func (s *Server) joinPage(w http.ResponseWriter, r *http.Request) { s.keyPage(w, r) } + +// joinOpen tells the page whether a password is set to join with. +func (s *Server) joinOpen(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + writeJSON(w, http.StatusOK, map[string]bool{"open": access.JoinOn()}) +} + +// joinRefusal: why a browser's join isn't one its own page sent, or "". +// A browser's POST carries an Origin, which must be the page's own address +// (the Host it called), at a name of this computer's (ownHost): an IP, +// localhost, MAGPIE_PUBLIC_URL's or its own host name. So a page elsewhere +// can't make keys through a visitor's browser, neither by its own Origin, +// by Origin "null" from a sandboxed frame, at a localhost subdomain WebKit +// asks the DNS for, nor by a name of its own rebound to this computer. A +// request no browser sent (curl, a script) carries none of a browser's +// marks and is judged on the password alone. +func joinRefusal(r *http.Request) string { + if !fromBrowser(r) { + return "" + } + if !ownHost(r.Host) { + return "open the join page at this computer's address (an IP, or MAGPIE_PUBLIC_URL's name), not " + r.Host + } + origin := r.Header.Get("Origin") + if origin == "" || origin == "null" { + return "a browser joins from the join page itself" + } + u, err := url.Parse(origin) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Path != "" || + hostPort(u.Host, u.Scheme) != hostPort(r.Host, u.Scheme) { + return "a browser joins from the join page itself, not " + origin + } + if site := r.Header.Get("Sec-Fetch-Site"); site != "" && site != "same-origin" { + return "a browser joins from the join page itself" + } + return "" +} + +// joinKey makes a gateway key for a computer that knows the join password. +// Neither the password nor the key is logged; the key goes back in the +// body alone, never cached. +func (s *Server) joinKey(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + if why := joinRefusal(r); why != "" { + log.Printf("refused %s %s from %s: %s", r.Method, r.URL.Path, r.RemoteAddr, why) + writeError(w, provider.Chat, http.StatusForbidden, why) + return + } + if !access.JoinOn() { + writeError(w, provider.Chat, http.StatusNotFound, "joining with a password is off on this magpie") + return + } + if !local(r) { + if over, retry := tooManyJoins(); over { + w.Header().Set("Retry-After", strconv.Itoa(int(retry.Seconds())+1)) + writeError(w, provider.Chat, http.StatusTooManyRequests, "too many tries to join; slow down") + return + } + } + var in struct { + Password string `json:"password"` + Name string `json:"name"` + } + b, _ := io.ReadAll(io.LimitReader(r.Body, 8<<10)) + if json.Unmarshal(b, &in) != nil { + writeError(w, provider.Chat, http.StatusBadRequest, `send {"password": "…", "name": "this computer's name"}`) + return + } + if !access.JoinPasswordOK(in.Password) { + log.Printf("refused %s %s from %s: wrong join password", r.Method, r.URL.Path, r.RemoteAddr) + writeError(w, provider.Chat, http.StatusUnauthorized, "wrong password") + return + } + name := joinKeyName(in.Name, clientIP(r)) + secret, err := access.Update("add-key", access.Change{Name: name}) + if err != nil { + writeError(w, provider.Chat, http.StatusInternalServerError, err.Error()) + return + } + who, _ := access.Authenticate(secret) + log.Printf("made gateway key %s (%s) for a computer that joined from %s", who.KeyID, name, r.RemoteAddr) + writeJSON(w, http.StatusCreated, map[string]string{"key": secret, "id": who.KeyID, "name": name}) +} + +// joinKeyName is the name typed, one line of at most 120 characters, or +// "Joined from
". +func joinKeyName(typed, ip string) string { + name := strings.Join(strings.Fields(strings.Map(func(r rune) rune { + if r < 32 || r == 127 { + return ' ' + } + return r + }, typed)), " ") + if utf8.RuneCountInString(name) > 120 { + name = string([]rune(name)[:119]) + "…" + } + if name == "" { + name = "Joined from " + ip + if ip == "" { + name = "Joined" + } + } + return name +} diff --git a/internal/gateway/join_test.go b/internal/gateway/join_test.go new file mode 100644 index 000000000..3c210f36d --- /dev/null +++ b/internal/gateway/join_test.go @@ -0,0 +1,261 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "log" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/settings" +) + +const joinPw = "correct horse battery" + +// joinGateway is a shared gateway with a join password set, its join +// bucket full and on a clock the test moves. +func joinGateway(t *testing.T) (http.Handler, *time.Time) { + t.Helper() + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + newCaller(t) + if err := access.SetJoinPassword(joinPw); err != nil { + t.Fatal(err) + } + resetJoinThrottle() + now := time.Date(2026, 11, 10, 12, 0, 0, 0, time.UTC) + joinThrottle.Lock() + joinThrottle.now = func() time.Time { return now } + joinThrottle.Unlock() + t.Cleanup(resetJoinThrottle) + return lanGuard(New().Handler()), &now +} + +type joinReq struct { + from, host, body string + header map[string]string +} + +func (q joinReq) do(h http.Handler) *httptest.ResponseRecorder { + r := httptest.NewRequest("POST", joinData, strings.NewReader(q.body)) + r.RemoteAddr = q.from + if q.from == "" { + r.RemoteAddr = "192.168.1.9:5000" + } + r.Host = q.host + if q.host == "" { + r.Host = "192.168.1.5:3425" + } + r.Header.Set("Content-Type", "application/json") + for k, v := range q.header { + r.Header.Set(k, v) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +func joinBody(pw, name string) string { + b, _ := json.Marshal(map[string]string{"password": pw, "name": name}) + return string(b) +} + +// the join page's own POST, as a browser sends it +var joinPageHeaders = map[string]string{ + "Origin": "http://192.168.1.5:3425", + "Sec-Fetch-Site": "same-origin", + "Sec-Fetch-Mode": "cors", + "User-Agent": "Mozilla/5.0", +} + +// EV_John_Liu on X: another computer on the network opens /join without a +// key, types the password, and gets a gateway key of its own, named for +// it, which works at once and stops when removed in Gateway keys. +func TestJoinMakesARevocableKey(t *testing.T) { + h, _ := joinGateway(t) + var logs bytes.Buffer + was := log.Writer() + log.SetOutput(&logs) + t.Cleanup(func() { log.SetOutput(was) }) + + page := keyPageReq{method: "GET", path: JoinPagePath, from: "192.168.1.9:5000", host: "192.168.1.5:3425"}.do(h) + if page.Code != 200 || !strings.Contains(page.Body.String(), `id="join"`) { + t.Fatal("join page", page.Code) + } + open := keyPageReq{method: "GET", path: joinData, from: "192.168.1.9:5000", host: "192.168.1.5:3425"}.do(h) + if open.Code != 200 || strings.TrimSpace(open.Body.String()) != `{"open":true}` { + t.Fatal("open", open.Code, open.Body.String()) + } + + w := joinReq{body: joinBody(joinPw, "Studio\nMac mini"), header: joinPageHeaders}.do(h) + if w.Code != http.StatusCreated { + t.Fatal(w.Code, w.Body.String()) + } + if cc := w.Header().Get("Cache-Control"); cc != "no-store" { + t.Error("Cache-Control", cc) + } + var got struct{ Key, ID, Name string } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || got.Key == "" { + t.Fatal(err, w.Body.String()) + } + if got.Name != "Studio Mac mini" { + t.Errorf("name %q", got.Name) + } + keys, _ := access.List() + found := false + for _, k := range keys { + found = found || (k.ID == got.ID && k.Name == "Studio Mac mini") + } + if !found { + t.Fatalf("no key %s in %+v", got.ID, keys) + } + + me := keyPageReq{method: "GET", path: keyPageData, from: "192.168.1.9:5000", host: "192.168.1.5:3425", header: map[string]string{"Authorization": "Bearer " + got.Key}}.do(h) + if me.Code != 200 { + t.Fatal("the new key", me.Code, me.Body.String()) + } + if _, err := access.Update("remove-key", access.Change{Key: got.ID}); err != nil { + t.Fatal(err) + } + me = keyPageReq{method: "GET", path: keyPageData, from: "192.168.1.9:5000", host: "192.168.1.5:3425", header: map[string]string{"Authorization": "Bearer " + got.Key}}.do(h) + if me.Code != 401 { + t.Fatal("a removed key", me.Code) + } + + // a name left empty is the address it joined from; curl (no browser) + // joins on the password alone + w = joinReq{body: joinBody(joinPw, "")}.do(h) + if w.Code != http.StatusCreated || !strings.Contains(w.Body.String(), `"name":"Joined from 192.168.1.9"`) { + t.Fatal(w.Code, w.Body.String()) + } + + if strings.Contains(logs.String(), got.Key) || strings.Contains(logs.String(), joinPw) { + t.Errorf("a secret in the log: %s", logs.String()) + } +} + +// A wrong password is 401, and every try from another machine takes from +// the join's bucket: past the burst it is 429 with Retry-After, the right +// password too, until the bucket refills. +func TestJoinHoldsAGuesser(t *testing.T) { + h, now := joinGateway(t) + var logs bytes.Buffer + was := log.Writer() + log.SetOutput(&logs) + t.Cleanup(func() { log.SetOutput(was) }) + for i := range joinBurst { + if w := (joinReq{body: joinBody("guess-"+string(rune('a'+i))+"-wrong", "")}).do(h); w.Code != 401 { + t.Fatal(i, w.Code, w.Body.String()) + } + } + w := joinReq{body: joinBody(joinPw, "")}.do(h) + if w.Code != http.StatusTooManyRequests || w.Header().Get("Retry-After") == "" { + t.Fatal("past the burst", w.Code, w.Header()) + } + if strings.Contains(w.Body.String(), `"key"`) { + t.Fatal("a key past the burst", w.Body.String()) + } + if strings.Contains(logs.String(), "guess-") { + t.Errorf("a password in the log: %s", logs.String()) + } + *now = now.Add(joinRefill) + if w := (joinReq{body: joinBody(joinPw, "")}).do(h); w.Code != http.StatusCreated { + t.Fatal("after a refill", w.Code, w.Body.String()) + } + if w := (joinReq{body: joinBody(joinPw, "")}).do(h); w.Code != http.StatusTooManyRequests { + t.Fatal("one token a refill", w.Code) + } +} + +// A page elsewhere can't make keys through a visitor's browser: Origin +// null, another site, a *.localhost name, a name of its own rebound to +// this computer, a cross-site fetch and a browser's POST with no Origin +// are refused, before the password is judged; none makes a key. +func TestJoinRefusesOtherPages(t *testing.T) { + h, _ := joinGateway(t) + browser := func(extra map[string]string) map[string]string { + m := map[string]string{"User-Agent": "Mozilla/5.0", "Sec-Fetch-Mode": "cors"} + for k, v := range extra { + m[k] = v + } + return m + } + for name, q := range map[string]joinReq{ + "null": {header: browser(map[string]string{"Origin": "null"})}, + "another site": {header: browser(map[string]string{"Origin": "https://evil.example"})}, + "localhost sub": {header: browser(map[string]string{"Origin": "http://evil.localhost:3425"})}, + "localhost host": {host: "evil.localhost:3425", from: "127.0.0.1:5000", + header: browser(map[string]string{"Origin": "http://evil.localhost:3425"})}, + "rebound": {host: "evil.example:3425", from: "127.0.0.1:5000", + header: browser(map[string]string{"Origin": "http://evil.example:3425"})}, + "rebound remote": {host: "evil.example:3425", + header: browser(map[string]string{"Origin": "http://evil.example:3425"})}, + "cross-site": {header: browser(map[string]string{"Origin": "http://192.168.1.5:3425", "Sec-Fetch-Site": "cross-site"})}, + "no Origin": {header: browser(nil)}, + "other port": {header: browser(map[string]string{"Origin": "http://192.168.1.5:8080"})}, + } { + q.body = joinBody(joinPw, "x") + w := q.do(h) + if w.Code < 400 || strings.Contains(w.Body.String(), `"key"`) { + t.Errorf("%s: %d %s", name, w.Code, w.Body.String()) + } + } + if keys, _ := access.List(); len(keys) != 0 { + t.Errorf("keys made: %+v", keys) + } + // and the page's own POST from this computer goes through + q := joinReq{from: "127.0.0.1:5000", host: "127.0.0.1:3425", body: joinBody(joinPw, "here"), + header: browser(map[string]string{"Origin": "http://127.0.0.1:3425", "Sec-Fetch-Site": "same-origin"})} + if w := q.do(h); w.Code != http.StatusCreated { + t.Fatal("own page", w.Code, w.Body.String()) + } +} + +// With no password set, or magpie not shared, nothing joins. +func TestJoinClosed(t *testing.T) { + h, _ := joinGateway(t) + if err := access.SetJoinPassword(""); err != nil { + t.Fatal(err) + } + if w := (joinReq{body: joinBody(joinPw, "")}).do(h); w.Code != 404 { + t.Error("no password", w.Code, w.Body.String()) + } + open := keyPageReq{method: "GET", path: joinData, from: "192.168.1.9:5000", host: "192.168.1.5:3425"}.do(h) + if strings.TrimSpace(open.Body.String()) != `{"open":false}` { + t.Error("open", open.Body.String()) + } + if err := access.SetJoinPassword(joinPw); err != nil { + t.Fatal(err) + } + s := settings.Load() + s.LAN = false + if err := settings.Save(s); err != nil { + t.Fatal(err) + } + if w := (joinReq{body: joinBody(joinPw, "")}).do(h); w.Code == http.StatusCreated { + t.Error("not shared", w.Code, w.Body.String()) + } + if keys, _ := access.List(); len(keys) != 0 { + t.Errorf("keys made: %+v", keys) + } +} + +func TestJoinKeyName(t *testing.T) { + long := strings.Repeat("é", 200) + for in, want := range map[string]string{ + " Studio\tMac\x00 ": "Studio Mac", + "": "Joined from 10.0.0.2", + long: strings.Repeat("é", 119) + "…", + } { + if got := joinKeyName(in, "10.0.0.2"); got != want { + t.Errorf("%q: %q", in, got) + } + } + if got := joinKeyName("", ""); got != "Joined" { + t.Error(got) + } +} diff --git a/internal/gateway/key_slots_test.go b/internal/gateway/key_slots_test.go index 9fd78e645..af07588d6 100644 --- a/internal/gateway/key_slots_test.go +++ b/internal/gateway/key_slots_test.go @@ -29,7 +29,7 @@ var keySlotFree = []string{ "POST " + RestartPath, "POST " + provider.RemoteUpdatePath, "POST /v1/messages/count_tokens", "POST " + claudeMCPPath + "{token}", "/mcp/{name}", "/mcp/run/{name}", SearchMCPPath, VisionMCPPath, ImageMCPPath, BrowserMCPPath, MemoryMCPPath, ImageMCPFiles + "{name}", ToolsMCPPath, ToolsMCPOne + "{plugin}", - HubMCPPath + "{agent}", HubMCPAll, "/", + HubMCPPath + "{agent}", HubMCPAll, "/", "POST " + joinData, } // Every route is judged for a key's MaxConcurrency: held (keySlotRoutes) diff --git a/internal/gateway/keypage.html b/internal/gateway/keypage.html index d1ce4d9da..f163f8d05 100644 --- a/internal/gateway/keypage.html +++ b/internal/gateway/keypage.html @@ -79,6 +79,10 @@ pre { margin: 0; background: var(--code); border-radius: 8px; padding: 12px 14px .models button .mono { overflow-wrap: anywhere; } .models button[aria-checked=true] { background: color-mix(in srgb, var(--accent) 12%, transparent); } .empty { color: var(--sub); padding: 6px 2px; } +#join .field + input { margin-bottom: 2px; } +#once { margin-bottom: 4px; } +.once-row { margin-top: 6px; } +.once-row code { background: var(--code); border-radius: 6px; padding: 6px 8px; overflow-wrap: anywhere; } [hidden] { display: none !important; } @media (max-width: 480px) { main { padding-top: 24px; } @@ -105,6 +109,21 @@ pre { margin: 0; background: var(--code); border-radius: 8px; padding: 12px 14px + +