gateway: what a proxy says of the caller reaches no vendor, ChatGPT backend or MCP server

Behind Tailscale Serve, a Cloudflare Tunnel or another reverse proxy,
the request magpie gets carries what the proxy says of the caller:
Tailscale-User-Login, -Name and -Profile-Pic (the user's email, name
and picture), True-Client-IP, X-Forwarded-*, Cf-*. The native route
dropped X-Forwarded-*, Forwarded, Cf-*, X-Real-Ip and Via, but not
True-Client-IP or any Tailscale-*, even though lanGuard itself reads
True-Client-IP and Tailscale-User-Login as forwarded
(forwardHeaders). The Codex passthrough and relay to the ChatGPT
backend (copyHeaders) and the MCP proxy dropped none of them.

proxyIdentity names them once: every forwardHeaders entry; any
X-Forwarded-*, Cf-* and Tailscale-*; Forwarded, Via, X-Real-Ip,
True-Client-Ip, X-Client-Ip and X-Original-Forwarded-For.
nativeHeaderDropped, copyHeaders and the MCP proxy's header loop all
skip them. The caller's other headers still go on. Checked and left
as they are: a provider's PassHeaders (names the user chose), Codex's
allow-listed codexHeader, the Codex websocket's headers and passOnCaller.

Tests: TestNativeAnyDropsProxyIdentity (native route, under
MAGPIE_TRUST_PROXY) and TestPassthroughDropsProxyIdentity (Codex relay
through copyHeaders, and /mcp/<server>). Each sends twelve identity
headers and checks that none arrive and that X-Custom still does.

Broken by hand: with native.go, codex_backend.go and mcp.go at their
parent, both tests are red. The native vendor was told True-Client-IP
and the three Tailscale-User-* headers. The ChatGPT backend and the
MCP server were told all twelve.

Run on mote at the pushed head 883690a0b (this commit and the one before,
on origin/main 9a0aab32c): gofmt -l clean, go vet, GOOS=windows go vet
and GOOS=linux -tags nogui go vet all clean. go test ./... -timeout 45m
-count=1: 84 packages ok, including internal/gateway. 3 red, each filed
and none in this change's path:
- TestMainWindowCorners/macOS_26_SDK (gui, macOS 27, #3949)
- TestRenewLoginsKeepsClaudeReading (provider, #5481). It is red 3 of 3
  at the base 49c9491b7 without either commit.
- TestHostEndedEndsWhatItsPluginStarted/own_end (plugin, a 30s wait in
  a full run; passes 3 of 3 alone at this head, #5515)
Rebased then onto origin/main 303a31dd6 (which fixed #5481) and run
again at that tree: gofmt and the three vets clean, and internal/gateway,
internal/provider, internal/plugin and internal/netproxy all ok.
Rebased on 19c45d5d4, which changes gateway.go (kept_error), Codex's
usage_limit_reached, Cursor's mover min, sessions and the GUI; ran
gofmt, go vet ./internal/..., GOOS=windows go vet of gateway and
provider, and go test ./internal/gateway ./internal/provider: both ok.
Rebased on 94d4866b5, which changes only internal/sessions; ran gofmt,
go vet of gateway, provider and sessions, and this change's own tests
(-run Redirect|DropsProxyIdentity|SameOrigin|Keyed): ok.
Rebased on cd77c725d, which changes only internal/provider's check-in;
ran gofmt, go vet of gateway and provider, and this change's own
tests again: ok.
Not tried: a real Tailscale Serve or Cloudflare Tunnel in front of
magpie.
This commit is contained in:
yetone
2026-11-06 19:50:19 +08:00
parent c57a5f7f58
commit 7d196b6797
5 changed files with 171 additions and 9 deletions
+11 -3
View File
@@ -834,9 +834,17 @@ OpenAI shape can't carry. GET, POST, PUT, PATCH and DELETE
base's. The mux redirects an unencoded `..` before the route sees it.
- **Headers.** The caller's auth (`Authorization`, `Proxy-Authorization`,
`x-api-key`, `api-key`, `x-goog-api-key`, `Cookie`), the browser's and
a proxy's (`Origin`, `Referer`, `Sec-*`, `X-Forwarded-*`, `Forwarded`,
`Cf-*`), the hop's own and `X-Magpie-*` are dropped (`nativeDropped`),
the gateway key's `?key=` too (`nativeQuery`); the rest go as they came.
a proxy's, the hop's own and `X-Magpie-*` are dropped
(`nativeHeaderDropped`), the gateway key's `?key=` too (`nativeQuery`);
the rest go as they came. What a proxy says of the caller is
`proxyIdentity`: every name lanGuard reads as forwarded
(`forwardHeaders`: `Forwarded`, `X-Forwarded-For`, `X-Real-IP`,
`Cf-Connecting-IP`, `True-Client-IP`, `Tailscale-User-Login`), any
`X-Forwarded-*`, `Cf-*` and `Tailscale-*` (Tailscale Serve's user
login, name and picture), `Via`, `X-Client-IP` and
`X-Original-Forwarded-For`. The Codex passthrough and relay to the
ChatGPT backend (`copyHeaders`) and the MCP proxy drop the same; see
`TestNativeAnyDropsProxyIdentity` and `TestPassthroughDropsProxyIdentity`.
`Sign` puts in the provider's key as it takes one, and magpie's
User-Agent goes in (`stampUA`). The answer's hop headers, `Set-Cookie`,
`Alt-Svc` and HSTS don't come back (`nativeAnswerDropped`).
+3 -1
View File
@@ -2075,7 +2075,9 @@ func threadSource(meta string) string {
func copyHeaders(dst, src http.Header) {
for k, vs := range src {
if !hopHeader(k) && http.CanonicalHeaderKey(k) != "Host" && http.CanonicalHeaderKey(k) != AccountHeader {
// what a proxy in front of magpie says of the caller isn't the
// ChatGPT backend's (proxyIdentity)
if !hopHeader(k) && !proxyIdentity(k) && http.CanonicalHeaderKey(k) != "Host" && http.CanonicalHeaderKey(k) != AccountHeader {
dst[k] = vs
}
}
+2 -1
View File
@@ -107,7 +107,8 @@ func (s *Server) mcpProxy(w http.ResponseWriter, r *http.Request) {
return nil, err
}
for k, v := range r.Header {
if mcpHop[http.CanonicalHeaderKey(k)] {
// nor what a proxy in front of magpie says of the caller
if mcpHop[http.CanonicalHeaderKey(k)] || proxyIdentity(k) {
continue
}
// the gateway's own key, which the caller check put there
+23 -4
View File
@@ -47,6 +47,7 @@ import (
"net/http"
"net/url"
"regexp"
"slices"
"strings"
"time"
@@ -290,18 +291,36 @@ func nativeQuery(raw string) string {
// nativeDropped are the caller's headers that never go to the vendor:
// its auth (a gateway key in any place callerKeys reads one, and any
// other credential), the browser's and a proxy's, the hop's own, and
// magpie's. The rest go as they came.
// magpie's; and what a proxy says of the caller (proxyIdentity). The rest
// go as they came.
var nativeDropped = map[string]bool{
"Authorization": true, "Proxy-Authorization": true, "X-Api-Key": true, "Api-Key": true, "X-Goog-Api-Key": true, "Cookie": true,
"Host": true, "Origin": true, "Referer": true, "Forwarded": true, "X-Real-Ip": true, "Via": true,
"Host": true, "Origin": true, "Referer": true,
"Connection": true, "Proxy-Connection": true, "Keep-Alive": true, "Te": true, "Trailer": true, "Transfer-Encoding": true, "Upgrade": true,
"Content-Length": true, "Accept-Encoding": true, "User-Agent": true,
}
func nativeHeaderDropped(k string) bool {
k = http.CanonicalHeaderKey(k)
return nativeDropped[k] || strings.HasPrefix(k, "X-Forwarded-") || strings.HasPrefix(k, "X-Magpie-") ||
strings.HasPrefix(k, "Sec-") || strings.HasPrefix(k, "Cf-")
return nativeDropped[k] || proxyIdentity(k) || strings.HasPrefix(k, "X-Magpie-") || strings.HasPrefix(k, "Sec-")
}
// proxyIdentity says k is what a proxy or tunnel in front of magpie says
// of the caller: its address (every forwardHeaders entry, X-Forwarded-*,
// Cloudflare's Cf-*) or who it is (Tailscale Serve's Tailscale-User-Login,
// the user's email, -Name and -Profile-Pic). It is for magpie to judge a
// request by (proxied), never for a vendor or a server magpie passes the
// request on to.
func proxyIdentity(k string) bool {
k = http.CanonicalHeaderKey(k)
if slices.ContainsFunc(forwardHeaders, func(h string) bool { return http.CanonicalHeaderKey(h) == k }) {
return true
}
switch k {
case "Forwarded", "Via", "X-Real-Ip", "True-Client-Ip", "X-Client-Ip", "X-Original-Forwarded-For":
return true
}
return strings.HasPrefix(k, "X-Forwarded-") || strings.HasPrefix(k, "Cf-") || strings.HasPrefix(k, "Tailscale-")
}
// nativeAnswerDropped are the vendor's answer headers that don't come
+132
View File
@@ -0,0 +1,132 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/mcpauth/mcpauthtest"
"github.com/yetone/magpie/internal/provider"
)
// identityHeaders are what a proxy or tunnel in front of magpie says of
// the caller: where it is, and with Tailscale Serve who (the user's
// email, name and picture).
var identityHeaders = []string{
"Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto", "X-Real-IP", "Via",
"Cf-Connecting-IP", "Cf-Ipcountry", "True-Client-IP",
"Tailscale-User-Login", "Tailscale-User-Name", "Tailscale-User-Profile-Pic",
}
// identityHeadersOn is a request's headers: every identity header, and
// one of the caller's own that goes on.
func identityHeadersOn() []string {
var hdr []string
for _, k := range identityHeaders {
hdr = append(hdr, k, "ident-"+k)
}
return append(hdr, "X-Custom", "kept")
}
func leakedIdentity(h http.Header) []string {
var out []string
for _, k := range identityHeaders {
if h.Get(k) != "" {
out = append(out, k+": "+h.Get(k))
}
}
return out
}
// A request through a proxy in front of magpie (Tailscale Serve, a
// Cloudflare Tunnel) reaches the vendor on the native route without what
// the proxy said of the caller: not its address, and not the Tailscale
// user's email, name or picture. The caller's own headers still go on.
func TestNativeAnyDropsProxyIdentity(t *testing.T) {
fresh(t)
// the proxy here signs its clients in itself (lan.go's trustProxy)
t.Setenv("MAGPIE_TRUST_PROXY", "1")
up := newVendorAPI(t)
saveVendor(t, provider.Provider{ID: "vendor", Name: "Vendor", Chat: up.URL + "/v1", Key: "vk", Models: []string{"m"}})
h := nativeServe(t)
rec := nativeDo(h, "POST", "http://127.0.0.1:3425"+NativePath+"vendor/v1/x", "127.0.0.1:50000", `{"model":"m"}`, identityHeadersOn()...)
if rec.Code != 201 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
seen := up.asked()
if len(seen) != 1 || seen[0].header.Get("X-Custom") != "kept" {
t.Fatalf("vendor asked %+v", seen)
}
if l := leakedIdentity(seen[0].header); len(l) > 0 {
t.Fatalf("the vendor was told %v", l)
}
}
// The same on the routes that pass the caller's headers on as they came:
// the Codex relay to the ChatGPT backend (copyHeaders, which the
// gateway's Codex passthrough and its model list share), and /mcp/<server>
// to a remote MCP server.
func TestPassthroughDropsProxyIdentity(t *testing.T) {
fresh(t)
t.Setenv("MAGPIE_TRUST_PROXY", "1")
var mu sync.Mutex
var got http.Header
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
got = r.Header.Clone()
mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "event: response.completed\ndata: {\"type\":\"response.completed\"}\n\n")
}))
defer up.Close()
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
hdr := map[string]string{"Authorization": "Bearer chatgpt-token", "Content-Type": "application/json"}
on := identityHeadersOn()
for i := 0; i+1 < len(on); i += 2 {
hdr[on[i]] = on[i+1]
}
rec := relayDo(CodexRelay(), "POST", "127.0.0.1:3425", CodexPath+"/responses", `{"model":"gpt-5.5","input":"hi","stream":true}`, hdr)
if rec.Code != 200 {
t.Fatalf("relay: %d %s", rec.Code, rec.Body)
}
mu.Lock()
if got.Get("X-Custom") != "kept" {
t.Errorf("relay: the caller's own header didn't go on: %v", got)
}
if l := leakedIdentity(got); len(l) > 0 {
t.Errorf("relay: the ChatGPT backend was told %v", l)
}
mu.Unlock()
f := mcpauthtest.New(t)
f.SignIn(t, "neon")
gw := httptest.NewServer(New().Handler())
defer gw.Close()
req, _ := http.NewRequest("POST", gw.URL+"/mcp/neon", strings.NewReader(`{"jsonrpc":"2.0","id":1,"method":"initialize"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
req.Header.Set("Authorization", "Bearer "+Token)
for i := 0; i+1 < len(on); i += 2 {
req.Header.Set(on[i], on[i+1])
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("mcp: %d %s", resp.StatusCode, b)
}
if f.Seen.Get("X-Custom") != "kept" {
t.Errorf("mcp: the caller's own header didn't go on: %v", f.Seen)
}
if l := leakedIdentity(f.Seen); len(l) > 0 {
t.Errorf("mcp: the MCP server was told %v", l)
}
}