carlos / platform Public

edge: tunnelled apps see the client the hub saw (#1348)

A fleet or -tunnel app behind the hub saw the hub's address as its
client: the box's edge wrote the tunnel's peer into X-Forwarded-For. The
hub already writes the chain itself (tunnelRewrite), so the box now
passes the hub's chain to the app when every entry is an IP address, as
it already did for a linked request, and the gate's attempt limiter keys
on the chain's last entry. Off a tunnel nothing changes.

linkVisitor becomes hubVisitor, since every tunnelled request reads it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 4171cb10a36ae35d34fc15af5f9d2bbae3b943b4 parent d3266e8
4 files changed, +289 −13
  • internal/edge/edge.go +18 −8
  • internal/edge/homemap.go +14 −2
  • internal/edge/tunnel_client_addr_test.go +253 −0
  • internal/gate/gate.go +4 −3
diff --git a/internal/edge/edge.go b/internal/edge/edge.go
index b2fd30d8f..3546f9996 100644
--- a/internal/edge/edge.go
+++ b/internal/edge/edge.go
@@ -1937,7 +1937,7 @@ func linkedRequest(ctx context.Context) bool {
// Host and X-Forwarded-Host want.PublicHost with X-Forwarded-Proto
// https (linkedBackend, setForwarded).
// - The visitor: when the hub's X-Forwarded-For is well formed
-// (linkVisitor: every entry an IP), the chain goes to the app
+// (hubVisitor: every entry an IP), the chain goes to the app
// (setForwarded) and the gate's attempt limiter keys on its last entry,
// the client the hub observed (gate.WithClientAddr), not on the
// tunnel's address every visitor shares. A malformed or missing header
@@ -1953,7 +1953,7 @@ func linkedRequest(ctx context.Context) bool {
// the request.
func (e *Edge) ServeLinked(w http.ResponseWriter, r *http.Request, want LinkedTarget) {
ctx := gate.WithPublicHost(withLinkPin(r.Context(), want), want.PublicHost)
- if visitor, _, ok := linkVisitor(r.Header); ok {
+ if visitor, _, ok := hubVisitor(r.Header); ok {
ctx = gate.WithClientAddr(ctx, visitor)
}
r = r.WithContext(ctx)
@@ -1961,16 +1961,18 @@ func (e *Edge) ServeLinked(w http.ResponseWriter, r *http.Request, want LinkedTa
e.ServeHTTP(w, r)
}
-// linkVisitor is a linked request's visitor: the last X-Forwarded-For entry,
-// the client address the hub observed and appended (the hub never passes a
-// client's own X-Forwarded-For on), and the whole chain, normalized. Only a
-// linked request is read this way (ServeLinked, setForwarded): on every
-// other ingress the header is the client's to forge. It accepts the header
+// hubVisitor is the visitor of a request a hub delivered over a tunnel, a
+// linked one included: the last X-Forwarded-For entry, the client address
+// the hub observed (the hub writes the chain itself in tunnelRewrite and
+// never passes a client's own X-Forwarded-For on), and the whole chain,
+// normalized. Only a tunnelled request is read this way (ServeLinked,
+// ServeHTTP's gate key, setForwarded; #1348): on every other ingress the
+// header is the client's to forge. It accepts the header
// only when every entry, on every line, is an IP address; anything else
// (no header, an empty one, an empty or malformed entry anywhere) is false,
// and the request keeps the connection peer as its client, as any request
// does.
-func linkVisitor(h http.Header) (visitor, chain string, ok bool) {
+func hubVisitor(h http.Header) (visitor, chain string, ok bool) {
lines := h.Values("X-Forwarded-For")
if len(lines) == 0 {
return "", "", false
@@ -2263,6 +2265,14 @@ func (e *Edge) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} else {
r, hopped = e.acceptHop(r, host)
}
+ // A request a tunnel delivered is keyed by the gate's attempt limiter on
+ // the client the hub observed, not on the tunnel's address every visitor
+ // shares (#1348), as ServeLinked keys a linked one.
+ if !pinned && fromTunnel(r.Context()) {
+ if visitor, _, ok := hubVisitor(r.Header); ok {
+ r = r.WithContext(gate.WithClientAddr(r.Context(), visitor))
+ }
+ }
// A probe-burst notice from another edge (burst_notice.go) is answered
// here, ahead of every route, so it never reaches a tenant's app. Only a
// POST to its path carrying its header is one: anything else, that path
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index faa6375b9..85c360ca9 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -1719,12 +1719,12 @@ func setForwarded(pr *httputil.ProxyRequest) {
// A linked request (ServeLinked) reaches its app as the visitor sent it
// to the serving side: the public host (linkedBackend has already made
// it pr.In.Host, so Host and the proof agree) over https, and, when
- // linkVisitor accepts it, the hub's X-Forwarded-For chain (normalized),
+ // hubVisitor accepts it, the hub's X-Forwarded-For chain (normalized),
// whose last entry is the client the hub observed. A chain it refuses
// never reaches the app: SetXForwarded's value, the connection peer,
// stays. It is never a door call or a hop.
if want, pinned := linkPinFrom(pr.In.Context()); pinned {
- if _, chain, ok := linkVisitor(pr.In.Header); ok {
+ if _, chain, ok := hubVisitor(pr.In.Header); ok {
pr.Out.Header.Set("X-Forwarded-For", chain)
}
pr.Out.Header.Set("X-Forwarded-Host", want.PublicHost)
@@ -1739,6 +1739,18 @@ func setForwarded(pr *httputil.ProxyRequest) {
pr.Out.Header.Set("X-Forwarded-Proto", "https")
return
}
+ // A request a tunnel delivered (#1348) came from the hub this box
+ // dialled, whose own setForwarded wrote the chain (tunnelRewrite): its
+ // last entry is the client the hub observed, and the tunnel's peer, the
+ // hub, is nobody's client. So the app gets the hub's chain, as a linked
+ // request's app does, when hubVisitor accepts it; a chain it refuses
+ // leaves SetXForwarded's value, the peer. Upgrades ride this proxy too.
+ if fromTunnel(pr.In.Context()) {
+ if _, chain, ok := hubVisitor(pr.In.Header); ok {
+ pr.Out.Header.Set("X-Forwarded-For", chain)
+ }
+ return
+ }
if !hopVerified(pr.In.Context()) {
return
}
diff --git a/internal/edge/tunnel_client_addr_test.go b/internal/edge/tunnel_client_addr_test.go
new file mode 100644
index 000000000..34992685e
--- /dev/null
+++ b/internal/edge/tunnel_client_addr_test.go
@@ -0,0 +1,253 @@
+package edge
+
+import (
+ "bufio"
+ "context"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// #1348: an app behind a tunnel sees the client the hub saw, as a shared-box
+// app sees its own client. The hub writes X-Forwarded-For fresh for every
+// request it sends down a tunnel (tunnelRewrite); the box passes that chain
+// to the app instead of the tunnel's peer, which is the hub.
+
+// hubSeenClient is the address the hub's listener reports for a visitor in
+// these tests: on loopback, the visitor, the hub and the tunnel's peer are
+// all 127.0.0.1, so the hub is told a distinct one, as the PPv2 listener
+// would tell it the real client's.
+const hubSeenClient = "198.51.100.7"
+
+// tunnelAddrScene is a hub edge serving demo.example over a real
+// tunnelclient connection to a box whose own Edge proxies to a TCP app.
+// wrap is applied to the box's edge as the box's agent would apply its
+// channel handler. It returns the hub's URL and what the app saw.
+func tunnelAddrScene(t *testing.T, wrap func(http.Handler) http.Handler) (hubURL string, seen func() []string) {
+ t.Helper()
+ var mu sync.Mutex
+ var xff []string
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ got := strings.Join(r.Header.Values("X-Forwarded-For"), ", ")
+ mu.Lock()
+ xff = append(xff, got)
+ mu.Unlock()
+ if r.Header.Get("Upgrade") == "websocket" {
+ conn, rw, err := http.NewResponseController(w).Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ defer conn.Close()
+ fmt.Fprintf(rw, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Seen-For: %s\r\n\r\n", got)
+ rw.Flush()
+ return
+ }
+ io.WriteString(w, "app")
+ }))
+ t.Cleanup(app.Close)
+ boxReg := openReg(t)
+ if err := boxReg.Upsert(registry.Route{Host: "demo.example", Kind: "service", Addr: app.Listener.Addr().String(), Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ box, err := New(boxReg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(box.probers.Stop)
+
+ hubReg := tunnelRoute(t, registry.Route{Host: "demo.example", Kind: "instance", Status: "ready", Tunnel: "pi-box"})
+ hub, err := New(hubReg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(hub.probers.Stop)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Host == "demo.example" {
+ r.RemoteAddr = net.JoinHostPort(hubSeenClient, "40000")
+ }
+ hub.ServeHTTP(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ u, _ := url.Parse(srv.URL)
+ th := NewTunnelHub(u.Hostname(), map[string]string{"pi-box": "sekrit"})
+ hub.EnableTunnels(th)
+ if err := hub.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(startFakeRemoteHost(t, srv.URL, "pi-box", "sekrit", wrap(box)))
+ waitForTunnelState(t, th, "pi-box", "connected", e2eReconnectBound)
+ return srv.URL, func() []string {
+ mu.Lock()
+ defer mu.Unlock()
+ return append([]string(nil), xff...)
+ }
+}
+
+func TestTunnelledAppSeesTheClientTheHubSaw(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ wrap func(http.Handler) http.Handler
+ }{
+ {"static channel", func(h http.Handler) http.Handler { return h }},
+ {"fleet channel", MarkFleetChannel},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ hubURL, seen := tunnelAddrScene(t, c.wrap)
+ req, _ := http.NewRequest("GET", hubURL+"/", nil)
+ req.Host = "demo.example"
+ req.Header.Set("X-Forwarded-For", "6.6.6.6") // a visitor's forgery at the hub
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != 200 {
+ t.Fatalf("through the tunnel: %d", resp.StatusCode)
+ }
+ if got := seen(); len(got) != 1 || got[0] != hubSeenClient {
+ t.Fatalf("the app saw X-Forwarded-For %q, want exactly %q (the client the hub saw)", got, hubSeenClient)
+ }
+ })
+ }
+}
+
+// A WebSocket upgrade rides the same proxy on the box, so it carries the
+// same address (#471's upgrades, #1348).
+func TestTunnelledUpgradeSeesTheClientTheHubSaw(t *testing.T) {
+ hubURL, _ := tunnelAddrScene(t, MarkFleetChannel)
+ u, _ := url.Parse(hubURL)
+ conn, err := net.Dial("tcp", u.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ fmt.Fprintf(conn, "GET /cable HTTP/1.1\r\nHost: demo.example\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n"+
+ "Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nX-Forwarded-For: 6.6.6.6\r\n\r\n")
+ resp, err := http.ReadResponse(bufio.NewReader(conn), nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusSwitchingProtocols {
+ t.Fatalf("upgrade through the tunnel: %d", resp.StatusCode)
+ }
+ if got := resp.Header.Get("X-Seen-For"); got != hubSeenClient {
+ t.Fatalf("the app saw X-Forwarded-For %q on the upgrade, want %q", got, hubSeenClient)
+ }
+}
+
+// What the box believes of the hub's chain, and what the gate keys on: a
+// well-formed chain goes to the app whole and its last entry is the
+// visitor; anything else falls back to the connection's peer, as for any
+// request. Off a tunnel the chain is the client's and is never believed.
+func TestTunnelledForwardedFallback(t *testing.T) {
+ var mu sync.Mutex
+ var xff []string
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ xff = append(xff, strings.Join(r.Header.Values("X-Forwarded-For"), ", "))
+ mu.Unlock()
+ io.WriteString(w, "app")
+ }))
+ t.Cleanup(app.Close)
+ const host = "demo.example"
+ reg := openReg(t)
+ if err := reg.Upsert(registry.Route{Host: host, Kind: "service", Addr: app.Listener.Addr().String(), Status: "ready"}); err != nil {
+ t.Fatal(err)
+ }
+ e, err := New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(e.probers.Stop)
+ tunnelled := true
+ saved := fromTunnel
+ fromTunnel = func(context.Context) bool { return tunnelled }
+ t.Cleanup(func() { fromTunnel = saved })
+
+ const peer = "192.0.2.10"
+ serve := func(method, path, chain, body string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(method, "http://"+host+path, strings.NewReader(body))
+ req.RemoteAddr = peer + ":40000"
+ if chain != "-" {
+ req.Header.Set("X-Forwarded-For", chain)
+ }
+ if body != "" {
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ }
+ rec := httptest.NewRecorder()
+ e.ServeHTTP(rec, req)
+ return rec
+ }
+ cases := []struct {
+ tunnelled bool
+ chain, app string
+ }{
+ {true, "198.51.100.7", "198.51.100.7"},
+ {true, "203.0.113.5, 198.51.100.7", "203.0.113.5, 198.51.100.7"},
+ {true, " 198.51.100.7 ", "198.51.100.7"},
+ {true, "2001:db8::1", "2001:db8::1"},
+ {true, "198.51.100.7, invalid", peer},
+ {true, "invalid, 198.51.100.7", peer},
+ {true, "", peer},
+ {true, "-", peer},
+ {true, "198.51.100.7,", peer},
+ {false, "198.51.100.7", peer},
+ }
+ for _, c := range cases {
+ tunnelled = c.tunnelled
+ mu.Lock()
+ xff = nil
+ mu.Unlock()
+ if rec := serve("GET", "/", c.chain, ""); rec.Code != 200 {
+ t.Fatalf("tunnelled=%v X-Forwarded-For %q: %d", c.tunnelled, c.chain, rec.Code)
+ }
+ mu.Lock()
+ got := strings.Join(xff, "|")
+ mu.Unlock()
+ if got != c.app {
+ t.Errorf("tunnelled=%v X-Forwarded-For %q: the app saw %q, want %q", c.tunnelled, c.chain, got, c.app)
+ }
+ }
+
+ tunnelled = true
+ hash, err := gate.Hash("shop-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := reg.SetGate(host, hash); err != nil {
+ t.Fatal(err)
+ }
+ if err := e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ wrong := url.Values{"password": {"nope-nope-nope"}, "next": {"/"}}.Encode()
+ login := func(chain string) int { return serve("POST", gate.LoginPath, chain, wrong).Code }
+ // Ten attempts from one visitor the hub saw spend that visitor's bucket.
+ for i := 0; i < 10; i++ {
+ if code := login("198.51.100.7"); code != http.StatusUnauthorized {
+ t.Fatalf("attempt %d: %d, want 401", i+1, code)
+ }
+ }
+ if code := login("198.51.100.7"); code != http.StatusTooManyRequests {
+ t.Fatalf("an 11th attempt from the same visitor: %d, want 429", code)
+ }
+ // Another visitor through the same hub has its own bucket.
+ if code := login("198.51.100.9"); code != http.StatusUnauthorized {
+ t.Fatalf("another visitor through the same hub: %d, want its own 401", code)
+ }
+ // A malformed chain is keyed on the peer, which nobody has spent.
+ if code := login("x"); code != http.StatusUnauthorized {
+ t.Fatalf("a malformed chain: %d, want 401 in the peer's bucket", code)
+ }
+}
diff --git a/internal/gate/gate.go b/internal/gate/gate.go
index 5d9c9e474..39334aa23 100644
--- a/internal/gate/gate.go
+++ b/internal/gate/gate.go
@@ -211,9 +211,10 @@ type clientAddrKey struct{}
// WithClientAddr marks ctx's request as one from the visitor at addr,
// whatever its RemoteAddr says, for the attempt limiter. The edge sets it
-// only for a request a linked deployment's hub delivered (linked
-// deployments spec §6.2), whose RemoteAddr is the tunnel's, shared by every
-// visitor: addr is the client address the hub observed.
+// only for a request a hub delivered over a tunnel, a linked deployment's
+// included (linked deployments spec §6.2, #1348), whose RemoteAddr is the
+// tunnel's, shared by every visitor: addr is the client address the hub
+// observed.
func WithClientAddr(ctx context.Context, addr string) context.Context {
return context.WithValue(ctx, clientAddrKey{}, addr)
}