Files
magpie/internal/gui/web.go
T
yetone 7a9490638d gateway, gui, settings: an IP / CIDR allow list for the gateway, from MAGPIE_ALLOW_IPS or Settings beside Share on local network (lc on Discord)
What changed: lc runs magpie in Docker on a public host and asked that
only some addresses reach it at all. With a list set, a request from an
address outside it is refused 403 ("magpie answers only the addresses on
its allow list ..., and this request came from <addr>: add it there to
let it in") before its gateway key is looked at, so a leaked key is no use from
elsewhere. No list is as before.
- internal/settings/allowips.go: SplitAllowIPs, ParseAllowIP (an IP or a
  CIDR range, v4 or v6; zones dropped, v4-mapped unmapped), CleanAllowIPs.
  Settings gets AllowIPs (allowIPs).
- internal/gateway/allow.go: MAGPIE_ALLOW_IPS (comma or space separated)
  sets the list in place of Settings'. The address judged is the
  connection's own (r.RemoteAddr); X-Forwarded-For and the rest are never
  believed (magpie has no trusted-proxy list; MAGPIE_TRUST_PROXY never
  reads forwarding headers, and this follows it). Loopback and this
  computer's own interface addresses always pass. An entry that doesn't
  read lets nothing in and is logged once, so a typo never opens magpie
  to every address. lanGuard checks it after the OAuth callback and
  before the rebound-Host and key checks; `magpie web` is wrapped with
  AllowGuard too.
- GUI: Settings > Network shows an "Allowed addresses" row under Share on local
  network when sharing is on, the page is open from another computer, or
  the env var is set (then read-only, saying so). POST
  /api/settings/allowips saves it, refuses it while the env var is set,
  refuses an entry that doesn't read, and refuses a list that would shut
  out the address the page itself is open from (KeepsOut). The generic
  settings save keeps AllowIPs. Strings in zh, zh-TW, ja and de.
- Docs: the Docker page (en, zh, ja) lists MAGPIE_ALLOW_IPS with a note
  that a request from the host itself arrives from the bridge's gateway
  (172.17.0.1), that Docker Desktop and rootless Docker show clients as
  one address of their own, and that behind a proxy every request comes
  from the proxy; docs/reference.md and docs/subsystems/gateway-routing.md
  describe it. The READMEs list no env vars, so they are unchanged.

Why: a gateway key is the only lock on a public host; an allow list keeps
everyone else from even trying it.

Run (machine load average 75-140 from other sessions, so the large
packages ran in slices of their top-level tests, each slice
-timeout 9m, private GOCACHE, sandbox HOME):
- New tests: internal/gateway/allow_test.go TestAllowList (allowed,
  denied, CIDR v4/v6, IPv6 literal, link-local with zone, v4-mapped,
  loopback and own address always in, on the list still needs a key,
  a typo shuts everything out, env over settings), TestAllowListServed
  (a real connection from loopback passes lanGuard under a list naming
  nothing of this computer's; a request from elsewhere is 403 naming its
  address and MAGPIE_ALLOW_IPS), TestKeepsOut; internal/settings/allowips_test.go
  TestCleanAllowIPs; internal/gui/allowips_settings_test.go
  TestAllowIPsSetting; internal/gui/tests/allow-ips.test.cjs (14/14 in
  chromium and webkit, at a 390px panel, en and zh, keys in zh, zh-TW,
  ja and de). Broken by
  hand: with lanGuard's check removed TestAllowList and TestAllowListServed
  FAIL; with KeepsOut skipped TestAllowIPsSetting FAILs; with renderAllow
  not called the GUI test has 5 failures. Restored, all pass.
- internal/gui/settings_keep_test.go gains AllowIPs:
  TestSettingsSaveKeepsWhatItDoesNotSend failed without it, as it should
  for a new field.
- go test -tags nogui: every package ok. internal/gateway (4 slices),
  internal/agent (4), internal/provider (3), internal/gui (2),
  internal/plugin (2), the rest whole. GUI Network-settings test files
  (11) 98/98 and i18n-keys ok, both engines.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok; linux and windows builds ok.
- Not tried: a real Docker container on a public host (the bridge note
  is from Docker's docs, not checked here); behind a real reverse proxy.
2026-10-12 23:21:41 +08:00

269 lines
9.8 KiB
Go

package gui
import (
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/klauspost/compress/gzhttp"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/update"
)
// `magpie web` serves the window's page to a browser, for a computer that
// can't show the app — no desktop, WSL, a server reached over SSH — with
// the gateway beside it as the app has. What is the desktop's (the panel,
// the tray, the Dock) does nothing there; a folder is named, not opened.
// webHost is the Windows a browser tab stands for.
type webHost struct{ quit func() }
func (webHost) HidePanel() {}
func (webHost) ShowMain(string) {}
func (h webHost) Quit() { h.quit() }
func (webHost) OpenURL(string) {} // the page opens links itself
func (webHost) Copy(string) bool { return false }
func (webHost) FitPanel(int, Glide) {}
func (webHost) TintPanel([4]uint8, int) bool { return false }
func (webHost) TintTitleBar([4]uint8, bool) bool { return false }
func (webHost) SetTextSize(int) {} // the browser zooms its own tab
func (webHost) OpenFolder(path string) error {
return errors.New("in the browser magpie can't open folders: it is " + tilde(path))
}
func (webHost) ChooseFolder(string) (string, error) {
return "", errors.New("in the browser magpie can't show a folder picker: type the folder's path")
}
// Web is a started `magpie web`: its address and the link that signs a
// browser in.
type Web struct {
Addr, Link string
key string
srv *http.Server
quit chan struct{}
}
// webReexec is set when the page's restart to update has put the new
// version in: Wait then runs it in this one's place.
var webReexec atomic.Bool
// webRunKey hands a run's own key to the version it restarts into, so the
// browser's cookie still opens the page (#111).
const webRunKey = "MAGPIE_WEB_RUNKEY"
// StartWeb serves the page on addr (host:port), as the given version of
// magpie, which keeps itself up to date as the app does. Every request needs the
// key the link carries, taken once into a cookie other sites' pages can't
// send with a POST (every change is one), so neither a page elsewhere nor
// anyone else on the network reaches the settings and keys behind it.
func StartWeb(addr, version string) (*Web, error) {
Version = version
key, fixed, err := webKey()
if err != nil {
return nil, err
}
var keep time.Duration
if fixed {
keep = webCookieAge
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return nil, err
}
w := &Web{Addr: ln.Addr().String(), key: key, quit: make(chan struct{})}
host, port, _ := net.SplitHostPort(w.Addr)
if ip := net.ParseIP(host); ip == nil || ip.IsUnspecified() {
host = "127.0.0.1"
}
var once sync.Once
quit := func() { once.Do(func() { close(w.quit) }) }
w.Link = "http://" + net.JoinHostPort(host, port) + "/?k=" + url.QueryEscape(key)
w.srv = &http.Server{
Handler: gateway.AllowGuard(webHandler(port, key, keep, Handler(webHost{quit}, startBackend()))),
ReadHeaderTimeout: 30 * time.Second,
}
go w.srv.Serve(ln)
updates.start()
news.start()
return w, nil
}
// Wait returns once the page's Quit is used. After a restart to update it
// runs the new version in this one's place, with the same arguments and
// key, so the page open in the browser finds it where it was.
func (w *Web) Wait() error {
<-w.quit
time.Sleep(200 * time.Millisecond) // the answer to the Quit gets out
w.srv.Close()
if !webReexec.Load() {
return nil
}
exe, err := update.Executable()
if err != nil {
return err
}
return update.Reexec(exe, os.Args[1:], append(os.Environ(), webRunKey+"="+w.key))
}
// webKeyMin is the shortest MAGPIE_WEB_KEY taken: it is all that stands
// between the network and the keys behind the page.
const webKeyMin = 16
// webCookieAge is how long a browser keeps a fixed key's cookie (the most
// Chrome allows); a run's own key lives in a cookie that goes with the
// browser session, as the key goes with the run.
const webCookieAge = 400 * 24 * time.Hour
// webKey is the key the link carries: a new one each run, unless
// MAGPIE_WEB_KEY names one — for a page kept running as a service, which
// browsers then stay signed in to across restarts. fixed says which.
func webKey() (key string, fixed bool, err error) {
if k := os.Getenv(webRunKey); k != "" {
os.Unsetenv(webRunKey) // the run's alone, not its children's
if len(k) == 32 && strings.Trim(k, "0123456789abcdef") == "" && os.Getenv("MAGPIE_WEB_KEY") == "" {
return k, false, nil
}
}
if k := os.Getenv("MAGPIE_WEB_KEY"); k != "" {
if len(k) < webKeyMin {
return "", false, fmt.Errorf("MAGPIE_WEB_KEY is %d characters; it needs at least %d", len(k), webKeyMin)
}
// a cookie can't hold a space, ; " \ or a comma: the browser would
// be sent one that isn't the key, and turned away
if strings.Trim(k, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") != "" {
return "", false, errors.New("MAGPIE_WEB_KEY takes letters, digits and - . _ ~ only (openssl rand -hex 16 makes one)")
}
return k, true, nil
}
b := make([]byte, 16)
rand.Read(b)
return hex.EncodeToString(b), false, nil
}
// webGuard lets through requests with the key: in the link's k, which it
// trades for a cookie (kept for keep, or the browser session when 0) and
// a clean address, or in that cookie.
func webGuard(cookie, key string, keep time.Duration, next http.Handler) http.Handler {
same := func(v string) bool { return subtle.ConstantTimeCompare([]byte(v), []byte(key)) == 1 }
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if q := r.URL.Query(); q.Has("k") {
if !same(q.Get("k")) {
http.Error(rw, "this link's key is not this magpie web's: use the link it printed when it started", http.StatusUnauthorized)
return
}
http.SetCookie(rw, &http.Cookie{Name: cookie, Value: key, Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode, MaxAge: int(keep / time.Second)})
q.Del("k")
u := *r.URL
u.RawQuery = q.Encode()
http.Redirect(rw, r, u.RequestURI(), http.StatusSeeOther)
return
}
if c, err := r.Cookie(cookie); err != nil || !same(c.Value) {
http.Error(rw, "open the link magpie web printed when it started: it carries the key", http.StatusUnauthorized)
return
}
next.ServeHTTP(rw, r)
})
}
// NetworkLinks are the links to the page, served on port, that other
// machines open; key is the link's "/?k=…". MAGPIE_PUBLIC_URL with a port
// of its own names the host the container's ports are published on, so
// the page is at that host on its own port; one without (a reverse proxy's
// https://magpie.example.com, #372) is where the page is, path and all.
func NetworkLinks(port, key string) []string {
if u, err := url.Parse(gateway.PublicURL()); err == nil && u.Host != "" && u.Port() == "" {
return []string{strings.TrimRight(u.String(), "/") + key}
}
var out []string
for _, a := range LANAddrs() {
out = append(out, "http://"+net.JoinHostPort(a, port)+key)
}
return out
}
// LANAddrs are this computer's addresses on the local network, for the
// links to print when the page is served there: MAGPIE_PUBLIC_URL's host
// when set (in a container, whose own addresses the network can't reach).
func LANAddrs() []string {
if h := gateway.PublicHost(); h != "" {
return []string{h}
}
var out []string
as, _ := net.InterfaceAddrs()
for _, a := range as {
n, ok := a.(*net.IPNet)
if !ok || n.IP.IsLoopback() || n.IP.To4() == nil || !n.IP.IsPrivate() {
continue
}
out = append(out, n.IP.String())
}
return out
}
// webHandler is what `magpie web` on port serves: the page and its API
// behind the key, compressed for the browser.
func webHandler(port, key string, keep time.Duration, page http.Handler) http.Handler {
return webCompressed(webGuard("magpie_web_"+port, key, keep, page))
}
// webCompressed gzips what `magpie web` sends a browser that takes it: the
// page's scripts, styles and SVG icons, and the API's JSON. They went out
// as they are, about 4 MB for a first load before any data, and the
// routing trace's JSON grows with every account a request could go to; a
// browser over a 3 Mbps link to a server waited for all of it (akic404 on
// Discord). They shrink to about a quarter, the JSON to a twentieth.
// Pictures already compressed go as they are.
//
// The app's own window gets the page from inside the process, with no
// network between, so only `magpie web` compresses.
//
// A gzipped file's ETag says so ("…-gzip"), as a validator of other bytes;
// asked for again with it, the file is still a 304. A few bytes of padding
// keyed to the content keep a response's compressed size from telling
// exactly what it holds (BREACH): the page carries keys.
func webCompressed(next http.Handler) http.Handler {
wrap, err := gzhttp.NewWrapper(
gzhttp.ContentTypeFilter(compressible),
gzhttp.SuffixETag(gzipETag),
gzhttp.RandomJitter(32, 0, false),
)
if err != nil {
return next
}
gz := wrap(next)
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
if tag := r.Header.Get("If-None-Match"); strings.Contains(tag, gzipETag+`"`) {
r.Header.Set("If-None-Match", strings.ReplaceAll(tag, gzipETag+`"`, `"`))
}
gz.ServeHTTP(rw, r)
})
}
// gzipETag ends the ETag of a gzipped response.
const gzipETag = "-gzip"
// compressible: text, scripts, JSON and SVG; not PNG, WebP, ICO or JPEG.
func compressible(ct string) bool {
ct = strings.ToLower(strings.TrimSpace(ct))
if i := strings.IndexByte(ct, ';'); i >= 0 {
ct = strings.TrimSpace(ct[:i])
}
return strings.HasPrefix(ct, "text/") || strings.HasSuffix(ct, "javascript") ||
strings.HasSuffix(ct, "json") || ct == "image/svg+xml"
}
// isWeb: the page is served to a browser by `magpie web`.
func isWeb(w Windows) bool { _, ok := w.(webHost); return ok }