From a334fe091cb94bb7868c75cbf783f23ff353ec82 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 6 Oct 2026 20:29:45 +0800 Subject: [PATCH] =?UTF-8?q?gateway:=20a=20request=20a=20proxy=20or=20tunne?= =?UTF-8?q?l=20on=20this=20computer=20forwards=20to=20loopback=20is=20answ?= =?UTF-8?q?ered=20as=20one=20from=20another=20machine,=20and=20needs=20the?= =?UTF-8?q?=20gateway=20key=20(#1022,=20znjhahaha:=20asked=20for=20a=20Clo?= =?UTF-8?q?udflare=20Tunnel=20in=20magpie,=20with=20the=20gateway=20key=20?= =?UTF-8?q?checked=20for=20requests=20through=20it)=20=E2=80=94=20local()?= =?UTF-8?q?=20was=20the=20request's=20address=20alone,=20so=20cloudflared,?= =?UTF-8?q?=20ngrok,=20Tailscale=20serve=20or=20funnel,=20frp's=20HTTP=20p?= =?UTF-8?q?roxy,=20or=20a=20Caddy=20or=20nginx=20here,=20all=20reaching=20?= =?UTF-8?q?127.0.0.1:3425=20for=20clients=20anywhere,=20were=20taken=20for?= =?UTF-8?q?=20this=20computer's=20agents:=20whoever=20had=20the=20tunnel's?= =?UTF-8?q?=20address=20used=20the=20user's=20subscriptions=20with=20any?= =?UTF-8?q?=20token,=20read=20/v1/magpie/quotas=20(the=20accounts=20and=20?= =?UTF-8?q?their=20balances)=20and=20the=20remote=20cards,=20and=20their?= =?UTF-8?q?=20usage=20was=20counted=20as=20local,=20all=20without=20sharin?= =?UTF-8?q?g=20on.=20reference.md=20said=20a=20proxy=20here=20had=20to=20s?= =?UTF-8?q?ign=20its=20clients=20in=20itself;=20a=20quick=20tunnel=20signs?= =?UTF-8?q?=20in=20nobody.=20A=20request=20on=20loopback=20carrying=20a=20?= =?UTF-8?q?forwarding=20header=20(Forwarded,=20X-Forwarded-For,=20X-Real-I?= =?UTF-8?q?P,=20Cf-Connecting-IP,=20True-Client-IP,=20Tailscale-User-Login?= =?UTF-8?q?),=20which=20no=20agent=20sends,=20is=20now=20proxied,=20and=20?= =?UTF-8?q?local()=20is=20false=20for=20it,=20so=20every=20check=20built?= =?UTF-8?q?=20on=20local()=20takes=20it=20as=20from=20the=20network:=20lan?= =?UTF-8?q?Guard=20refuses=20it=20while=20magpie=20isn't=20shared,=20sayin?= =?UTF-8?q?g=20it=20came=20through=20a=20proxy=20or=20tunnel=20and=20that?= =?UTF-8?q?=20Settings=20=E2=86=92=20Share=20on=20local=20network=20and=20?= =?UTF-8?q?a=20gateway=20key=20let=20it=20in;=20shared,=20it=20needs=20an?= =?UTF-8?q?=20enabled=20gateway=20key=20and=20is=20then=20sharedWith,=20as?= =?UTF-8?q?=20a=20LAN=20client=20is,=20for=20the=20model=20APIs,=20quotas,?= =?UTF-8?q?=20remote=20cards,=20concurrency,=20session=20route=20and=20MCP?= =?UTF-8?q?=20sign-ins;=20the=20Omarchy=20theme=20and=20the=20Codex=20titl?= =?UTF-8?q?e=20link=20stay=20this=20machine's=20only,=20and=20its=20usage?= =?UTF-8?q?=20is=20no=20longer=20marked=20local.=20A=20gateway=20MAGPIE=5F?= =?UTF-8?q?ADDR=20opens=20to=20the=20network=20stays=20open=20to=20a=20tun?= =?UTF-8?q?nel=20as=20to=20anyone;=20one=20MAGPIE=5FADDR=20keeps=20on=20lo?= =?UTF-8?q?opback=20is=20closed=20to=20it.=20MAGPIE=5FTRUST=5FPROXY=3D1=20?= =?UTF-8?q?says=20a=20proxy=20here=20signs=20its=20clients=20in=20itself?= =?UTF-8?q?=20and=20keeps=20what=20it=20forwards=20local,=20as=20before=20?= =?UTF-8?q?(listed=20in=20agentenv=5Ftest's=20notAnAgent).=20A=20tunnel=20?= =?UTF-8?q?forwarding=20bare=20TCP=20(frp=20tcp,=20ssh=20-R,=20socat)=20ad?= =?UTF-8?q?ds=20no=20header=20and=20can't=20be=20told=20from=20an=20agent:?= =?UTF-8?q?=20reference.md=20says=20to=20point=20one=20at=20the=20LAN=20ad?= =?UTF-8?q?dress=20with=20sharing=20on.=20Running=20cloudflared=20from=20m?= =?UTF-8?q?agpie=20with=20a=20pasted=20Tunnel=20Token=20is=20not=20done=20?= =?UTF-8?q?here:=20magpie=20would=20have=20to=20download=20or=20run=20a=20?= =?UTF-8?q?program=20it=20doesn't=20ship;=20reference.md=20says=20how=20to?= =?UTF-8?q?=20serve=20magpie=20through=20a=20Cloudflare=20Tunnel=20today.?= =?UTF-8?q?=20TestProxiedLoopbackNeedsTheKey=20(from=20127.0.0.1=20with=20?= =?UTF-8?q?cloudflared's,=20ngrok's,=20nginx's,=20RFC=207239's,=20Akamai's?= =?UTF-8?q?=20and=20Tailscale=20serve's=20headers:=20refused=20unshared,?= =?UTF-8?q?=20401=20shared=20without=20a=20key,=20with=20magpie's=20token?= =?UTF-8?q?=20or=20a=20wrong=20key,=20let=20in=20with=20the=20key=20under?= =?UTF-8?q?=20its=20identity,=20a=20disabled=20key=20refused;=20an=20agent?= =?UTF-8?q?=20on=20loopback=20let=20in=20with=20any=20token;=20MAGPIE=5FTR?= =?UTF-8?q?UST=5FPROXY;=20MAGPIE=5FADDR=20on=20loopback=20and=20open)=20an?= =?UTF-8?q?d=20TestProxiedLoopbackRoutes=20(quotas,=20quotas=20history,=20?= =?UTF-8?q?models,=20Omarchy=20and=20/mcp=20through=20a=20tunnel,=20unshar?= =?UTF-8?q?ed=20and=20shared,=20with=20and=20without=20the=20key)=20fail?= =?UTF-8?q?=20on=20main=20(200=20for=20every=20tunnel=20unshared)=20and=20?= =?UTF-8?q?pass=20-race=20-count=3D10=20with=20TestLANGuard,=20TestQuotasO?= =?UTF-8?q?verLAN,=20TestManagedLANGuard=20and=20TestExplicitOpenGatewayAc?= =?UTF-8?q?ceptsAllRemoteTokens;=20go=20test=20-race=20-tags=20nogui=20./i?= =?UTF-8?q?nternal/gateway=20(579=20s,=20under=20-timeout=2030m)=20and=20g?= =?UTF-8?q?o=20test=20-tags=20nogui=20./internal/...=20under=20a=20temp=20?= =?UTF-8?q?HOME=20pass;=20go=20vet=20(darwin,=20windows),=20gofmt=20-l,=20?= =?UTF-8?q?linux=20and=20windows=20(nogui)=20builds=20pass.=20No=20GUI=20c?= =?UTF-8?q?hange.=20Not=20tried=20with=20a=20real=20cloudflared=20(not=20i?= =?UTF-8?q?nstalled=20here);=20its=20Cf-Connecting-IP=20and=20X-Forwarded-?= =?UTF-8?q?For=20are=20what=20Cloudflare=20documents=20it=20sends.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/reference.md | 28 +++++- internal/agent/agentenv_test.go | 1 + internal/gateway/lan.go | 43 ++++++++- internal/gateway/lan_proxy_test.go | 142 +++++++++++++++++++++++++++++ 4 files changed, 206 insertions(+), 8 deletions(-) create mode 100644 internal/gateway/lan_proxy_test.go diff --git a/docs/reference.md b/docs/reference.md index 3ea942b26..ac7788b9d 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -336,6 +336,23 @@ Only a valid, enabled key is attributed to its named identity. Without sharing, an explicitly exposed `MAGPIE_ADDR` keeps its original open access, including old `sk-magpie-…` tokens, without key authentication. +A request that reaches loopback through a proxy or tunnel on this computer +(Cloudflare Tunnel's `cloudflared`, ngrok, Tailscale serve or funnel, frp's +HTTP proxy, Caddy, nginx) is someone else's, and is answered as one from +another machine (#1022): it carries a forwarding header (`Forwarded`, +`X-Forwarded-For`, `X-Real-IP`, `Cf-Connecting-IP`, `True-Client-IP`, +`Tailscale-User-Login`), which no agent sends. Without sharing it is refused; +with sharing it needs an enabled gateway key, as from the network. This +covers every route: the model APIs, quotas, MCP sign-ins. To serve magpie +through a Cloudflare Tunnel, turn on **Settings → Share on local network**, +add a gateway key for each client, point the tunnel's service at +`http://127.0.0.1:3425`, and give clients the tunnel's address with that key. +A tunnel that forwards bare TCP (frp's `tcp`, `ssh -R`, socat) adds no header +and can't be told from an agent here: point it at this computer's LAN +address with sharing on, not at loopback. A proxy here that signs its +clients in itself can be trusted with `MAGPIE_TRUST_PROXY=1`, which keeps +what it forwards local, as before. + **Usage → Overview → Gateway keys** groups calls by the client's key, never the provider's credential. **Usage → Requests** offers the same filter; CSV includes `caller_key_id` and `caller_key_name`. Deleted keys keep their @@ -803,9 +820,10 @@ Settings → Share on local network and use an enabled gateway key its own — a reverse proxy's `https://magpie.example.com` — is the address `magpie web` prints for its own page too, so the proxy must forward `/v1` and `/v1beta` to the gateway's port and the rest to the page's. When the -proxy and magpie run on the same machine, requests forwarded over loopback -are treated as local and need no key, so the proxy must authenticate those -clients itself. +proxy and magpie run on the same machine, a request it forwards over +loopback carries a forwarding header and needs a gateway key as one from +the network does (see [Providers and the gateway](#providers-and-the-gateway)); a proxy that +authenticates its clients itself can be trusted with `MAGPIE_TRUST_PROXY=1`. It exposes: @@ -1144,8 +1162,8 @@ configure providers. Turn on *Share on local network*, then create a gateway key for each remote agent host. After that, change the gateway mapping to `3425:3425` (or bind it only to the NAS interface or VPN address) and recreate the container so remote agents can reach it. For Internet access, prefer a -VPN such as Tailscale or WireGuard; if a reverse proxy is used, it must -authenticate clients itself when it forwards to Magpie over loopback. +VPN such as Tailscale or WireGuard; a reverse proxy or tunnel forwarding to +Magpie over loopback needs a gateway key from its clients, as the network does. ### Developing diff --git a/internal/agent/agentenv_test.go b/internal/agent/agentenv_test.go index 73891f005..d581f739c 100644 --- a/internal/agent/agentenv_test.go +++ b/internal/agent/agentenv_test.go @@ -30,6 +30,7 @@ var notAnAgent = map[string]string{ "MAGPIE_ADDR": "magpie's own", "MAGPIE_DEBUG": "magpie's own debug flag", "MAGPIE_PUBLIC_URL": "magpie's own public URL", + "MAGPIE_TRUST_PROXY": "magpie's own: a proxy here signs its clients in (#1022)", "MAGPIE_EFFORT_UPDATES": "magpie's own switch for effort updates (#617)", "MAGPIE_SITE_ORIGIN": "a site origin magpie's Omarchy theme answers, to try the site locally", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "Claude Code's behaviour flag, not an agent's folder", diff --git a/internal/gateway/lan.go b/internal/gateway/lan.go index 6d64ac062..f9eb86649 100644 --- a/internal/gateway/lan.go +++ b/internal/gateway/lan.go @@ -195,7 +195,19 @@ func lanGuard(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { remote := !local(r) shared := settings.Load().LAN - if remote && !shared && os.Getenv("MAGPIE_ADDR") == "" { + // a gateway MAGPIE_ADDR opens to the network lets anyone in, through + // a proxy too; listening on loopback, it is reached from elsewhere + // only through one, and that stays closed unless shared + closed := os.Getenv("MAGPIE_ADDR") == "" + if proxied(r) { + closed = !OpenToAnyone() + } + if remote && !shared && closed { + if proxied(r) { + log.Printf("refused %s %s through a proxy or tunnel: magpie isn't shared", r.Method, r.URL.Path) + http.Error(w, "this request came through a proxy or tunnel (it carries a forwarding header such as X-Forwarded-For or Cf-Connecting-IP), so magpie answers it as one from another machine: only while Settings → Share on local network is on, with an enabled gateway key (Gateway → Gateway keys) sent as Authorization: Bearer or x-api-key", http.StatusForbidden) + return + } http.Error(w, "magpie isn't shared on the local network", http.StatusForbidden) return } @@ -351,12 +363,37 @@ func refusedKey(key string) string { return which + " is not an enabled magpie gateway key: it is disabled, removed or mistyped" } -// local is a request from this computer. +// local is a request from this computer: one that reached the gateway on +// loopback and wasn't passed on by a proxy or tunnel running here. func local(r *http.Request) bool { host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return false } ip := net.ParseIP(host) - return ip != nil && ip.IsLoopback() + return ip != nil && ip.IsLoopback() && !proxied(r) +} + +// forwardHeaders are what a proxy or tunnel adds to a request it passes +// on: cloudflared (Cf-Connecting-IP, and X-Forwarded-For beside it), +// ngrok, Tailscale serve and funnel, frp's and Caddy's and nginx's HTTP +// proxies. An agent calling magpie sends none of them. +var forwardHeaders = []string{"Forwarded", "X-Forwarded-For", "X-Real-IP", "Cf-Connecting-IP", "True-Client-IP", "Tailscale-User-Login"} + +// proxied: the request came to loopback through a proxy or tunnel on this +// computer (#1022, znjhahaha: a Cloudflare Tunnel to 127.0.0.1:3425), so it +// is someone else's, from wherever the proxy reaches, and is treated as +// from another machine: answered only while magpie is shared, with an +// enabled gateway key. MAGPIE_TRUST_PROXY=1 says a proxy here signs its +// clients in itself, and keeps what it forwards local, as before. +func proxied(r *http.Request) bool { + if trustProxy() { + return false + } + return slices.ContainsFunc(forwardHeaders, func(h string) bool { return r.Header.Get(h) != "" }) +} + +func trustProxy() bool { + v, _ := strconv.ParseBool(strings.TrimSpace(os.Getenv("MAGPIE_TRUST_PROXY"))) + return v } diff --git a/internal/gateway/lan_proxy_test.go b/internal/gateway/lan_proxy_test.go new file mode 100644 index 000000000..6896716d7 --- /dev/null +++ b/internal/gateway/lan_proxy_test.go @@ -0,0 +1,142 @@ +package gateway + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/access" + "github.com/yetone/magpie/internal/settings" +) + +// A tunnel or proxy on this computer (cloudflared, ngrok, Tailscale serve, +// frp, Caddy) reaches the gateway on loopback for clients anywhere (#1022). +// What it forwards carries a forwarding header, and is answered as from +// another machine: refused while magpie isn't shared, and with sharing on +// only with an enabled gateway key — on every route, the model calls, the +// quotas, the MCP sign-ins. An agent on loopback without those headers is +// let in as before, with any token. +func TestProxiedLoopbackNeedsTheKey(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + t.Setenv("MAGPIE_TRUST_PROXY", "") + reached := "" + h := lanGuard(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reached = access.Caller(r.Context()).KeyID + "|" + r.Header.Get("Authorization") + })) + call := func(path string, hdr ...string) (int, string) { + reached = "" + r := httptest.NewRequest("POST", path, nil) + r.RemoteAddr = "127.0.0.1:51234" + for i := 0; i+1 < len(hdr); i += 2 { + r.Header.Set(hdr[i], hdr[i+1]) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code, w.Body.String() + } + // what each puts on a request it passes on + tunnels := map[string][]string{ + "cloudflared": {"Cf-Connecting-IP", "203.0.113.9", "X-Forwarded-For", "203.0.113.9", "Cf-Ray", "8c1f-SJC"}, + "ngrok": {"X-Forwarded-For", "198.51.100.4", "X-Forwarded-Proto", "https"}, + "nginx": {"X-Real-IP", "198.51.100.4"}, + "RFC 7239": {"Forwarded", "for=198.51.100.4;proto=https"}, + "Akamai": {"True-Client-IP", "198.51.100.4"}, + "Tailscale serve": {"Tailscale-User-Login", "someone@example.com"}, + } + + if c, _ := call("/v1/messages", "Authorization", "Bearer magpie"); c != 200 || reached != "|Bearer magpie" { + t.Fatal("an agent on loopback:", c, reached) + } + for name, hdr := range tunnels { + c, body := call("/v1/messages", append([]string{"Authorization", "Bearer magpie"}, hdr...)...) + if c != http.StatusForbidden || reached != "" || !strings.Contains(body, "proxy or tunnel") || !strings.Contains(body, "Share on local network") { + t.Fatalf("%s, magpie not shared: %d %q reached=%q", name, c, body, reached) + } + } + + keys, secrets := newCaller(t, "Tunnel client") // shares magpie + for name, hdr := range tunnels { + for _, bad := range [][]string{nil, {"Authorization", "Bearer magpie"}, {"x-api-key", "sk-magpie-wrong"}} { + if c, _ := call("/v1/messages", append(append([]string{}, bad...), hdr...)...); c != http.StatusUnauthorized || reached != "" { + t.Fatalf("%s with %v: %d reached=%q", name, bad, c, reached) + } + } + if c, _ := call("/v1/messages", append([]string{"Authorization", "Bearer " + secrets[0]}, hdr...)...); c != 200 || reached != keys[0].ID+"|Bearer magpie" { + t.Fatalf("%s with the key: %d reached=%q", name, c, reached) + } + } + if c, _ := call("/v1/messages", "Authorization", "Bearer anything"); c != 200 { + t.Fatal("an agent on loopback, shared:", c) + } + access.Update("off-key", access.Change{Key: keys[0].ID}) + if c, _ := call("/v1/messages", "Authorization", "Bearer "+secrets[0], "Cf-Connecting-IP", "203.0.113.9"); c != http.StatusUnauthorized { + t.Fatal("a disabled key through the tunnel:", c) + } + + // a proxy that signs its own clients in is said to be trusted + t.Setenv("MAGPIE_TRUST_PROXY", "1") + s := settings.Load() + s.LAN = false + settings.Save(s) + if c, _ := call("/v1/messages", "Authorization", "Bearer magpie", "X-Forwarded-For", "10.0.0.2"); c != 200 { + t.Fatal("MAGPIE_TRUST_PROXY:", c) + } + t.Setenv("MAGPIE_TRUST_PROXY", "") + + // MAGPIE_ADDR on loopback is closed to a tunnel; one open to the + // network is open to it as to everyone else + t.Setenv("MAGPIE_ADDR", "127.0.0.1:4555") + if c, _ := call("/v1/messages", "Cf-Connecting-IP", "203.0.113.9"); c != http.StatusForbidden { + t.Fatal("MAGPIE_ADDR on loopback, through a tunnel:", c) + } + t.Setenv("MAGPIE_ADDR", "0.0.0.0:4555") + if c, _ := call("/v1/messages", "Cf-Connecting-IP", "203.0.113.9"); c != 200 { + t.Fatal("MAGPIE_ADDR open, through a tunnel:", c) + } +} + +// The gateway's own routes that answer this computer only — quotas, the +// MCP sign-ins, the Omarchy theme — don't take a tunnel's request for one. +func TestProxiedLoopbackRoutes(t *testing.T) { + fresh(t) + t.Setenv("MAGPIE_ADDR", "") + t.Setenv("MAGPIE_TRUST_PROXY", "") + h := lanGuard(New().Handler()) + call := func(method, path string, hdr ...string) int { + r := httptest.NewRequest(method, path, nil) + r.RemoteAddr = "127.0.0.1:51234" + for i := 0; i+1 < len(hdr); i += 2 { + r.Header.Set(hdr[i], hdr[i+1]) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code + } + cf := []string{"Cf-Connecting-IP", "203.0.113.9", "Host", "magpie.example.com"} + if c := call("GET", "/v1/magpie/quotas"); c != 200 { + t.Fatal("quotas on loopback:", c) + } + for _, p := range []string{"/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/models", "/v1/magpie/omarchy"} { + if c := call("GET", p, cf...); c != http.StatusForbidden { + t.Fatal(p, "through a tunnel, not shared:", c) + } + } + if c := call("POST", "/mcp/docs", cf...); c != http.StatusForbidden { + t.Fatal("MCP through a tunnel, not shared:", c) + } + _, secrets := newCaller(t, "Tunnel client") + if c := call("GET", "/v1/magpie/quotas", cf...); c != http.StatusUnauthorized { + t.Fatal("quotas through a tunnel without the key:", c) + } + if c := call("GET", "/v1/magpie/quotas", append([]string{"x-api-key", secrets[0]}, cf...)...); c != 200 { + t.Fatal("quotas through a tunnel with the key:", c) + } + if c := call("GET", "/v1/magpie/omarchy", append([]string{"x-api-key", secrets[0]}, cf...)...); c != http.StatusForbidden { + t.Fatal("the Omarchy theme is this machine's only:", c) + } + if c := call("POST", "/mcp/docs", cf...); c != http.StatusUnauthorized { + t.Fatal("MCP through a tunnel without the key:", c) + } +}