Files
magpie/internal/gateway/lan_proxy_test.go
T
yetone a334fe091c gateway: a request a proxy or tunnel on this computer forwards to loopback is answered as one from another machine, and needs the gateway key (#1022, znjhahaha: asked for a Cloudflare Tunnel in magpie, with the gateway key checked for requests through it) — local() was the request's address alone, so cloudflared, ngrok, Tailscale serve or funnel, frp's HTTP proxy, or a Caddy or nginx here, all reaching 127.0.0.1:3425 for clients anywhere, were taken for this computer's agents: whoever had the tunnel's address used the user's subscriptions with any token, read /v1/magpie/quotas (the accounts and their balances) and the remote cards, and their usage was counted as local, all without sharing on. reference.md said a proxy here had to sign its clients in itself; a quick tunnel signs in nobody. A request on loopback carrying a forwarding header (Forwarded, X-Forwarded-For, X-Real-IP, Cf-Connecting-IP, True-Client-IP, Tailscale-User-Login), which no agent sends, is now proxied, and local() is false for it, so every check built on local() takes it as from the network: lanGuard refuses it while magpie isn't shared, saying it came through a proxy or tunnel and that Settings → Share on local network and a gateway key let it in; shared, it needs an enabled gateway key and is then sharedWith, as a LAN client is, for the model APIs, quotas, remote cards, concurrency, session route and MCP sign-ins; the Omarchy theme and the Codex title link stay this machine's only, and its usage is no longer marked local. A gateway MAGPIE_ADDR opens to the network stays open to a tunnel as to anyone; one MAGPIE_ADDR keeps on loopback is closed to it. MAGPIE_TRUST_PROXY=1 says a proxy here signs its clients in itself and keeps what it forwards local, as before (listed in agentenv_test's notAnAgent). A tunnel forwarding bare TCP (frp tcp, ssh -R, socat) adds no header and can't be told from an agent: reference.md says to point one at the LAN address with sharing on. Running cloudflared from magpie with a pasted Tunnel Token is not done here: magpie would have to download or run a program it doesn't ship; reference.md says how to serve magpie through a Cloudflare Tunnel today. TestProxiedLoopbackNeedsTheKey (from 127.0.0.1 with cloudflared's, ngrok's, nginx's, RFC 7239's, Akamai's and Tailscale serve's headers: refused unshared, 401 shared without a key, with magpie's token or a wrong key, let in with the key under its identity, a disabled key refused; an agent on loopback let in with any token; MAGPIE_TRUST_PROXY; MAGPIE_ADDR on loopback and open) and TestProxiedLoopbackRoutes (quotas, quotas history, models, Omarchy and /mcp through a tunnel, unshared and shared, with and without the key) fail on main (200 for every tunnel unshared) and pass -race -count=10 with TestLANGuard, TestQuotasOverLAN, TestManagedLANGuard and TestExplicitOpenGatewayAcceptsAllRemoteTokens; go test -race -tags nogui ./internal/gateway (579 s, under -timeout 30m) and go test -tags nogui ./internal/... under a temp HOME pass; go vet (darwin, windows), gofmt -l, linux and windows (nogui) builds pass. No GUI change. Not tried with a real cloudflared (not installed here); its Cf-Connecting-IP and X-Forwarded-For are what Cloudflare documents it sends.
2026-10-06 20:35:18 +08:00

143 lines
5.9 KiB
Go

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)
}
}