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.
This commit is contained in:
+23
-5
@@ -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
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
+40
-3
@@ -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 <key> 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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user