|
| 1 | +package domainfront |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + stdtls "crypto/tls" |
| 6 | + "crypto/x509" |
| 7 | + "errors" |
| 8 | + "io" |
| 9 | + "log/slog" |
| 10 | + "net" |
| 11 | + "net/http" |
| 12 | + "testing" |
| 13 | + "time" |
| 14 | + |
| 15 | + utls "github.com/refraction-networking/utls" |
| 16 | + "github.com/stretchr/testify/assert" |
| 17 | + "github.com/stretchr/testify/require" |
| 18 | + "golang.org/x/net/http2" |
| 19 | +) |
| 20 | + |
| 21 | +// dialPipeH2 stands up an HTTP/2 server on one end of a net.Pipe (TLS with |
| 22 | +// ALPN "h2") and returns a handshaken utls client connection to it — the same |
| 23 | +// connection type dialFront produces in production. No real network is used. |
| 24 | +func dialPipeH2(t *testing.T, handler http.Handler) *utls.UConn { |
| 25 | + t.Helper() |
| 26 | + ca, caKey := newTestCA(t) |
| 27 | + leaf := newTestLeafCert(t, ca, caKey, "cdn.example.com") |
| 28 | + roots := x509.NewCertPool() |
| 29 | + roots.AddCert(ca) |
| 30 | + |
| 31 | + // Bound both handshakes so a broken pairing fails fast on the deadline |
| 32 | + // rather than hanging until the `go test` timeout. net.Pipe honors |
| 33 | + // deadlines, so HandshakeContext can interrupt a stalled handshake. |
| 34 | + // Cancel at test end (not on return): the returned conn is used after this |
| 35 | + // helper returns, and cancelling the handshake context while the conn is |
| 36 | + // still in use poisons it (sets a past deadline) on some Go versions. |
| 37 | + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 38 | + t.Cleanup(cancel) |
| 39 | + |
| 40 | + clientRaw, serverRaw := net.Pipe() |
| 41 | + go func() { |
| 42 | + srv := stdtls.Server(serverRaw, &stdtls.Config{ |
| 43 | + Certificates: []stdtls.Certificate{leaf}, |
| 44 | + NextProtos: []string{"h2"}, |
| 45 | + }) |
| 46 | + if err := srv.HandshakeContext(ctx); err != nil { |
| 47 | + serverRaw.Close() |
| 48 | + return |
| 49 | + } |
| 50 | + (&http2.Server{}).ServeConn(srv, &http2.ServeConnOpts{Handler: handler}) |
| 51 | + }() |
| 52 | + |
| 53 | + uconn := utls.UClient(clientRaw, &utls.Config{ |
| 54 | + RootCAs: roots, |
| 55 | + ServerName: "cdn.example.com", |
| 56 | + NextProtos: []string{"h2"}, |
| 57 | + }, utls.HelloGolang) |
| 58 | + require.NoError(t, uconn.HandshakeContext(ctx)) |
| 59 | + require.Equal(t, "h2", negotiatedProtocol(uconn), "handshake should negotiate h2") |
| 60 | + // Close the conn at test end so the server goroutine's ServeConn unblocks |
| 61 | + // (it otherwise reads the pipe until close). Tests that complete a request |
| 62 | + // already tear the conn down via resp.Body.Close; this also covers tests |
| 63 | + // that never send one (e.g. an upgrade rejected before any round-trip). |
| 64 | + t.Cleanup(func() { _ = uconn.Close(); _ = serverRaw.Close() }) |
| 65 | + return uconn |
| 66 | +} |
| 67 | + |
| 68 | +// TestDoRequest_HTTP2 verifies that when the TLS handshake negotiates h2, |
| 69 | +// doRequest frames the fronted request as HTTP/2 and the fronted host lands in |
| 70 | +// the :authority pseudo-header (the h2 equivalent of the Host header that drives |
| 71 | +// CDN routing). |
| 72 | +func TestDoRequest_HTTP2(t *testing.T) { |
| 73 | + type observed struct { |
| 74 | + authority, path, hdr string |
| 75 | + proto int |
| 76 | + } |
| 77 | + seen := make(chan observed, 1) |
| 78 | + conn := dialPipeH2(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 79 | + seen <- observed{r.Host, r.URL.Path, r.Header.Get("X-Probe"), r.ProtoMajor} |
| 80 | + w.WriteHeader(http.StatusOK) |
| 81 | + io.WriteString(w, "h2-fronted-ok") |
| 82 | + })) |
| 83 | + |
| 84 | + req, err := http.NewRequest(http.MethodGet, "https://config.example.com/api/data", nil) |
| 85 | + require.NoError(t, err) |
| 86 | + req.Header.Set("X-Probe", "carried") |
| 87 | + |
| 88 | + resp, err := (&roundTripper{}).doRequest(req, conn, "cdn.example.com", nil) |
| 89 | + require.NoError(t, err) |
| 90 | + |
| 91 | + body, err := io.ReadAll(resp.Body) |
| 92 | + require.NoError(t, err) |
| 93 | + require.NoError(t, resp.Body.Close()) // tears down the h2 conn |
| 94 | + |
| 95 | + assert.Equal(t, http.StatusOK, resp.StatusCode) |
| 96 | + assert.Equal(t, 2, resp.ProtoMajor, "response should be HTTP/2") |
| 97 | + assert.Equal(t, "h2-fronted-ok", string(body)) |
| 98 | + |
| 99 | + got := <-seen |
| 100 | + assert.Equal(t, "cdn.example.com", got.authority, ":authority must be the fronted host, not the origin") |
| 101 | + assert.Equal(t, "/api/data", got.path, "path must be preserved from the original request") |
| 102 | + assert.Equal(t, 2, got.proto, "server must see an HTTP/2 request") |
| 103 | + assert.Equal(t, "carried", got.hdr, "caller headers must propagate") |
| 104 | +} |
| 105 | + |
| 106 | +// TestVerifyWithPost_HTTP2 covers the front-vetting path over an h2 connection. |
| 107 | +// Vetting gates whether a front becomes usable, so it must speak h2 just like |
| 108 | +// request traffic — otherwise every h2 edge (CloudFront, Aliyun) fails to vet. |
| 109 | +func TestVerifyWithPost_HTTP2(t *testing.T) { |
| 110 | + gotMethod := make(chan string, 1) |
| 111 | + conn := dialPipeH2(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 112 | + gotMethod <- r.Method |
| 113 | + w.WriteHeader(http.StatusAccepted) // 202: the contract verifyWithPost checks |
| 114 | + })) |
| 115 | + |
| 116 | + c := &Client{log: slog.Default()} |
| 117 | + ok := c.verifyWithPost(conn, "https://cdn.example.com/ping") |
| 118 | + |
| 119 | + assert.True(t, ok, "a 202 over h2 should vet successfully") |
| 120 | + assert.Equal(t, http.MethodPost, <-gotMethod) |
| 121 | +} |
| 122 | + |
| 123 | +// TestStripConnHeaders verifies the RFC 7540 §8.1.2.2 transformation: the |
| 124 | +// connection-specific headers and any header named in Connection are removed, |
| 125 | +// while ordinary headers are preserved. |
| 126 | +func TestStripConnHeaders(t *testing.T) { |
| 127 | + req, err := http.NewRequest(http.MethodGet, "https://x/y", nil) |
| 128 | + require.NoError(t, err) |
| 129 | + req.Header.Set("Connection", "keep-alive, X-Hop") |
| 130 | + req.Header.Set("X-Hop", "drop") // named in Connection |
| 131 | + req.Header.Set("Keep-Alive", "timeout=5") |
| 132 | + req.Header.Set("Transfer-Encoding", "chunked") |
| 133 | + req.Header.Set("Upgrade", "h2c") |
| 134 | + req.Header.Set("X-Keep", "stay") |
| 135 | + |
| 136 | + stripConnHeaders(req) |
| 137 | + |
| 138 | + for _, h := range []string{"Connection", "X-Hop", "Keep-Alive", "Transfer-Encoding", "Upgrade"} { |
| 139 | + assert.Emptyf(t, req.Header.Get(h), "%s must be stripped", h) |
| 140 | + } |
| 141 | + assert.Equal(t, "stay", req.Header.Get("X-Keep"), "non-connection headers must remain") |
| 142 | +} |
| 143 | + |
| 144 | +// TestSendOverConn_H2_RejectsUpgrade verifies an upgrade request over an h2 |
| 145 | +// front is rejected with errH2UpgradeUnsupported (so RoundTrip can retry onto |
| 146 | +// an http/1.1 front) and never reaches the server. |
| 147 | +func TestSendOverConn_H2_RejectsUpgrade(t *testing.T) { |
| 148 | + reached := make(chan struct{}, 1) |
| 149 | + conn := dialPipeH2(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 150 | + reached <- struct{}{} |
| 151 | + w.WriteHeader(http.StatusOK) |
| 152 | + })) |
| 153 | + req, err := http.NewRequest(http.MethodGet, "https://cdn.example.com/ws", nil) |
| 154 | + require.NoError(t, err) |
| 155 | + req.Header.Set("Connection", "Upgrade") |
| 156 | + req.Header.Set("Upgrade", "websocket") |
| 157 | + |
| 158 | + _, err = sendOverConn(conn, req, false) |
| 159 | + require.ErrorIs(t, err, errH2UpgradeUnsupported) |
| 160 | + select { |
| 161 | + case <-reached: |
| 162 | + t.Fatal("server must not be reached for an upgrade rejected over h2") |
| 163 | + default: |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +// TestSendOverConn_H2_StripsForbiddenHeaders verifies that connection-specific |
| 168 | +// headers (which x/net/http2 would otherwise reject) are stripped before h2 |
| 169 | +// framing, so an otherwise-valid request still succeeds. |
| 170 | +func TestSendOverConn_H2_StripsForbiddenHeaders(t *testing.T) { |
| 171 | + gotHop := make(chan string, 1) |
| 172 | + conn := dialPipeH2(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 173 | + gotHop <- r.Header.Get("X-Hop") |
| 174 | + w.WriteHeader(http.StatusOK) |
| 175 | + })) |
| 176 | + req, err := http.NewRequest(http.MethodGet, "https://cdn.example.com/x", nil) |
| 177 | + require.NoError(t, err) |
| 178 | + // Transfer-Encoding: gzip and a non-close/keep-alive Connection token both |
| 179 | + // make x/net/http2 reject the request unless stripped first. |
| 180 | + req.Header.Set("Transfer-Encoding", "gzip") |
| 181 | + req.Header.Set("Connection", "X-Hop") |
| 182 | + req.Header.Set("X-Hop", "should-be-stripped") |
| 183 | + |
| 184 | + resp, err := sendOverConn(conn, req, true) |
| 185 | + require.NoError(t, err) |
| 186 | + require.NoError(t, resp.Body.Close()) |
| 187 | + assert.Equal(t, http.StatusOK, resp.StatusCode) |
| 188 | + assert.Empty(t, <-gotHop, "Connection-named header must be stripped before h2") |
| 189 | +} |
| 190 | + |
| 191 | +// errCloser is a test io.Closer that records call count and returns a fixed err. |
| 192 | +type errCloser struct { |
| 193 | + err error |
| 194 | + calls int |
| 195 | +} |
| 196 | + |
| 197 | +func (c *errCloser) Close() error { c.calls++; return c.err } |
| 198 | + |
| 199 | +// TestH2Body_Close covers the connection-teardown semantics: the underlying h2 |
| 200 | +// connection is closed exactly once, its error surfaces when the body close |
| 201 | +// itself succeeds, and a body-close error takes precedence. |
| 202 | +func TestH2Body_Close(t *testing.T) { |
| 203 | + t.Run("propagates cc error when body close ok", func(t *testing.T) { |
| 204 | + cc := &errCloser{err: assert.AnError} |
| 205 | + b := &h2Body{ReadCloser: io.NopCloser(nil), cc: cc} |
| 206 | + assert.Equal(t, assert.AnError, b.Close()) |
| 207 | + assert.Equal(t, 1, cc.calls) |
| 208 | + }) |
| 209 | + |
| 210 | + t.Run("body error takes precedence over cc error", func(t *testing.T) { |
| 211 | + bodyErr := errors.New("body boom") |
| 212 | + cc := &errCloser{err: assert.AnError} |
| 213 | + b := &h2Body{ReadCloser: errReadCloser{bodyErr}, cc: cc} |
| 214 | + assert.Equal(t, bodyErr, b.Close()) |
| 215 | + assert.Equal(t, 1, cc.calls, "cc still closed even when body close fails") |
| 216 | + }) |
| 217 | + |
| 218 | + t.Run("closes the connection only once", func(t *testing.T) { |
| 219 | + cc := &errCloser{} |
| 220 | + b := &h2Body{ReadCloser: io.NopCloser(nil), cc: cc} |
| 221 | + assert.NoError(t, b.Close()) |
| 222 | + assert.NoError(t, b.Close()) |
| 223 | + assert.Equal(t, 1, cc.calls) |
| 224 | + }) |
| 225 | +} |
| 226 | + |
| 227 | +type errReadCloser struct{ err error } |
| 228 | + |
| 229 | +func (e errReadCloser) Read([]byte) (int, error) { return 0, e.err } |
| 230 | +func (e errReadCloser) Close() error { return e.err } |
| 231 | + |
| 232 | +func TestHasConnectionUpgrade(t *testing.T) { |
| 233 | + mk := func(vals ...string) *http.Request { |
| 234 | + r, _ := http.NewRequest(http.MethodGet, "https://x/", nil) |
| 235 | + for _, v := range vals { |
| 236 | + r.Header.Add("Connection", v) |
| 237 | + } |
| 238 | + return r |
| 239 | + } |
| 240 | + assert.True(t, hasConnectionUpgrade(mk("upgrade"))) |
| 241 | + assert.True(t, hasConnectionUpgrade(mk("keep-alive, Upgrade")), "token in a comma list") |
| 242 | + assert.True(t, hasConnectionUpgrade(mk("keep-alive", "Upgrade")), "multiple header values") |
| 243 | + assert.False(t, hasConnectionUpgrade(mk("keep-alive"))) |
| 244 | + assert.False(t, hasConnectionUpgrade(mk())) |
| 245 | +} |
0 commit comments