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