diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 93364e5b0..ba3091dfa 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -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`). diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index b86b34b19..286147752 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -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 } } diff --git a/internal/gateway/mcp.go b/internal/gateway/mcp.go index cb6a8a8fc..827aabbc4 100644 --- a/internal/gateway/mcp.go +++ b/internal/gateway/mcp.go @@ -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 diff --git a/internal/gateway/native.go b/internal/gateway/native.go index 9a2901569..a6373dd8c 100644 --- a/internal/gateway/native.go +++ b/internal/gateway/native.go @@ -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 diff --git a/internal/gateway/proxy_identity_test.go b/internal/gateway/proxy_identity_test.go new file mode 100644 index 000000000..7334e0997 --- /dev/null +++ b/internal/gateway/proxy_identity_test.go @@ -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/ +// 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) + } +}