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