File
Blob: tun/client/proxy_forwarded_test.go
| 1 | package client |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/tls" |
| 6 | "encoding/json" |
| 7 | "net" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "testing" |
| 11 | "time" |
| 12 | |
| 13 | "go.miragespace.co/specter/gateway" |
| 14 | "go.miragespace.co/specter/spec/protocol" |
| 15 | "go.miragespace.co/specter/spec/tun" |
| 16 | "go.miragespace.co/specter/util/bufconn" |
| 17 | "go.miragespace.co/specter/util/pipe" |
| 18 | |
| 19 | "github.com/quic-go/quic-go" |
| 20 | "github.com/stretchr/testify/require" |
| 21 | "github.com/zhangyunhao116/skipmap" |
| 22 | "go.uber.org/atomic" |
| 23 | "go.uber.org/zap/zaptest" |
| 24 | ) |
| 25 | |
| 26 | type forwardedRequest struct { |
| 27 | Host string |
| 28 | URI string |
| 29 | Headers http.Header |
| 30 | } |
| 31 | |
| 32 | func captureForwardedRequest(w http.ResponseWriter, r *http.Request) { |
| 33 | w.Header().Set("X-Request-ID", "upstream-request-id") |
| 34 | _ = json.NewEncoder(w).Encode(forwardedRequest{Host: r.Host, URI: r.RequestURI, Headers: r.Header}) |
| 35 | } |
| 36 | |
| 37 | // Supply the same private stream entrypoint used by authenticated server |
| 38 | // delegations, while retaining actual HTTP serialization between both proxies. |
| 39 | type forwardedTunnelServer struct { |
| 40 | client *Client |
| 41 | } |
| 42 | |
| 43 | func (s *forwardedTunnelServer) DialClient(ctx context.Context, link *protocol.Link) (net.Conn, error) { |
| 44 | local, remote := bufconn.BufferedPipe(8192) |
| 45 | if err := s.client.handleIncomingDelegation(ctx, link, forwardedPeerConn{local}); err != nil { |
| 46 | remote.Close() |
| 47 | return nil, err |
| 48 | } |
| 49 | return remote, nil |
| 50 | } |
| 51 | |
| 52 | func (*forwardedTunnelServer) Identity() *protocol.Node { |
| 53 | return &protocol.Node{Address: "192.0.2.20:443"} |
| 54 | } |
| 55 | |
| 56 | func (*forwardedTunnelServer) DialInternal(context.Context, *protocol.Node) (net.Conn, error) { |
| 57 | return nil, tun.ErrLookupFailed |
| 58 | } |
| 59 | |
| 60 | type forwardedPeerConn struct{ net.Conn } |
| 61 | |
| 62 | func (forwardedPeerConn) RemoteAddr() net.Addr { |
| 63 | return &net.TCPAddr{IP: net.ParseIP("192.0.2.20"), Port: 443} |
| 64 | } |
| 65 | |
| 66 | func TestGatewayClientForwardedContext(t *testing.T) { |
| 67 | der, _, key := testMakeRSACert(require.New(t)) |
| 68 | tlsConfig := &tls.Config{ |
| 69 | Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}, |
| 70 | NextProtos: []string{"h2", "http/1.1", "h3"}, |
| 71 | } |
| 72 | |
| 73 | for _, tc := range []struct { |
| 74 | target, mode, proto string |
| 75 | }{ |
| 76 | {"http", "", "http/1.1"}, |
| 77 | {"http", "target", "h2"}, |
| 78 | {"http", "hostname", "http/1.1"}, |
| 79 | {"pipe", "custom", "h2"}, |
| 80 | {"pipe", "legacy-override", "http/1.1"}, |
| 81 | } { |
| 82 | t.Run(tc.target+"/"+tc.mode+"/"+tc.proto, func(t *testing.T) { |
| 83 | pipeTarget := tc.target == "pipe" |
| 84 | mode, proto := tc.mode, tc.proto |
| 85 | as := require.New(t) |
| 86 | var target string |
| 87 | if pipeTarget { |
| 88 | path, address := randomPipeTarget(t, "forwarded-*") |
| 89 | target = address |
| 90 | listener, err := pipe.ListenPipe(path) |
| 91 | as.NoError(err) |
| 92 | server := &http.Server{Handler: http.HandlerFunc(captureForwardedRequest)} |
| 93 | go server.Serve(listener) |
| 94 | t.Cleanup(func() { server.Close() }) |
| 95 | } else { |
| 96 | server := httptest.NewServer(http.HandlerFunc(captureForwardedRequest)) |
| 97 | target = server.URL |
| 98 | t.Cleanup(server.Close) |
| 99 | } |
| 100 | |
| 101 | // HTTP/1 routes by SNI; HTTP/2 routes by authority for coalescing. |
| 102 | hostname := "tls.example.com" |
| 103 | if proto == "h2" { |
| 104 | hostname = "visitor.example.com" |
| 105 | } |
| 106 | tunnel := Tunnel{Hostname: hostname, Target: target, ProxyHeaderMode: mode} |
| 107 | if mode == "custom" || mode == "legacy-override" { |
| 108 | tunnel.ProxyHeaderHost = "backend.example.com:9000" |
| 109 | } |
| 110 | if mode == "legacy-override" { |
| 111 | tunnel.ProxyHeaderMode = "" |
| 112 | } |
| 113 | cfg := &Config{Tunnels: []Tunnel{tunnel}} |
| 114 | as.NoError(cfg.validate()) |
| 115 | c := &Client{ |
| 116 | ClientConfig: ClientConfig{Logger: zaptest.NewLogger(t), Configuration: cfg}, |
| 117 | forwarder: &forwarder{ |
| 118 | logger: zaptest.NewLogger(t), |
| 119 | rootDomain: atomic.NewString("example.com"), |
| 120 | routes: skipmap.NewString[*route](), |
| 121 | }, |
| 122 | } |
| 123 | c.setRoutes(cfg.Tunnels) |
| 124 | t.Cleanup(c.closeAll) |
| 125 | |
| 126 | listener, err := tls.Listen("tcp", "127.0.0.1:0", tlsConfig) |
| 127 | as.NoError(err) |
| 128 | t.Cleanup(func() { listener.Close() }) |
| 129 | quicListener, err := quic.ListenAddr("127.0.0.1:0", tlsConfig, nil) |
| 130 | as.NoError(err) |
| 131 | t.Cleanup(func() { quicListener.Close() }) |
| 132 | gw := gateway.New(gateway.GatewayConfig{ |
| 133 | Logger: c.Logger, |
| 134 | TunnelServer: &forwardedTunnelServer{client: c}, |
| 135 | H2Listener: listener, |
| 136 | H3Listener: quicListener, |
| 137 | GatewayPort: 8443, |
| 138 | Options: gateway.Options{TransportBufferSize: 8192, ProxyBufferSize: 8192}, |
| 139 | }) |
| 140 | gw.MustStart(t.Context()) |
| 141 | t.Cleanup(gw.Close) |
| 142 | |
| 143 | transport := &http.Transport{ |
| 144 | ForceAttemptHTTP2: proto == "h2", |
| 145 | DialTLSContext: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 146 | dialer := &tls.Dialer{Config: &tls.Config{ |
| 147 | InsecureSkipVerify: true, |
| 148 | ServerName: "tls.example.com", |
| 149 | NextProtos: []string{proto}, |
| 150 | }} |
| 151 | return dialer.DialContext(ctx, "tcp", listener.Addr().String()) |
| 152 | }, |
| 153 | } |
| 154 | t.Cleanup(transport.CloseIdleConnections) |
| 155 | visitor := &http.Client{Transport: transport, Timeout: 5 * time.Second} |
| 156 | req, err := http.NewRequestWithContext(t.Context(), "GET", "https://visitor.example.com:8443/a%2Fb?q=one%2Ftwo", nil) |
| 157 | as.NoError(err) |
| 158 | req.Header = http.Header{ |
| 159 | "Forwarded": {"for=198.51.100.1;proto=http;host=attacker.example"}, |
| 160 | "X-Forwarded-For": {"198.51.100.1, 198.51.100.2", "198.51.100.3"}, |
| 161 | "X-Forwarded-Host": {"attacker.example:1234", "second.example"}, |
| 162 | "X-Forwarded-Proto": {"http", "ftp"}, |
| 163 | "X-Request-Id": {"visitor-request-id"}, |
| 164 | "X-Real-Ip": {"198.51.100.4"}, |
| 165 | "True-Client-Ip": {"198.51.100.5"}, |
| 166 | } |
| 167 | if proto == "http/1.1" { |
| 168 | req.Header.Set("Connection", "X-Forwarded-For, x-forwarded-host, X-Forwarded-Proto, X-Request-ID") |
| 169 | } |
| 170 | resp, err := visitor.Do(req) |
| 171 | as.NoError(err) |
| 172 | defer resp.Body.Close() |
| 173 | as.Equal(http.StatusOK, resp.StatusCode) |
| 174 | as.Equal(proto == "h2", resp.ProtoMajor == 2) |
| 175 | var received forwardedRequest |
| 176 | as.NoError(json.NewDecoder(resp.Body).Decode(&received)) |
| 177 | requestIDs := received.Headers.Values("X-Request-ID") |
| 178 | if len(requestIDs) != 1 || requestIDs[0] == "" || requestIDs[0] == "visitor-request-id" { |
| 179 | t.Fatalf("upstream request IDs = %v, want one gateway-generated ID", requestIDs) |
| 180 | } |
| 181 | requestID := requestIDs[0] |
| 182 | if responseIDs := resp.Header.Values("X-Request-ID"); len(responseIDs) != 1 || responseIDs[0] != requestID { |
| 183 | t.Fatalf("response request IDs = %v, want %q", responseIDs, requestID) |
| 184 | } |
| 185 | |
| 186 | expectedHost := cfg.Tunnels[0].parsed.Host |
| 187 | if pipeTarget { |
| 188 | expectedHost = "pipe" |
| 189 | } |
| 190 | if mode == "hostname" { |
| 191 | expectedHost = hostname |
| 192 | } else if mode == "custom" || mode == "legacy-override" { |
| 193 | expectedHost = tunnel.ProxyHeaderHost |
| 194 | } |
| 195 | as.Equal(expectedHost, received.Host) |
| 196 | as.Equal("/a%2Fb?q=one%2Ftwo", received.URI) |
| 197 | as.Equal([]string{"127.0.0.1"}, received.Headers.Values("X-Forwarded-For")) |
| 198 | as.Equal([]string{hostname + ":8443"}, received.Headers.Values("X-Forwarded-Host")) |
| 199 | as.Equal([]string{"https"}, received.Headers.Values("X-Forwarded-Proto")) |
| 200 | for _, header := range []string{"Forwarded", "X-Real-IP", "True-Client-IP", "Connection"} { |
| 201 | as.Empty(received.Headers.Values(header), header) |
| 202 | } |
| 203 | }) |
| 204 | } |
| 205 | } |