]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/net/http/client_test.go
crypto/tls: remove RSA KEX ciphers from the default list
[gostls13.git] / src / net / http / client_test.go
index 01d605c35194f88e954c2b348458f5e7aae9c478..7459b9cb6ed1df3a42d4ed54a54abc8748b3dffd 100644 (file)
@@ -13,6 +13,7 @@ import (
        "encoding/base64"
        "errors"
        "fmt"
+       "internal/testenv"
        "io"
        "log"
        "net"
@@ -21,6 +22,7 @@ import (
        "net/http/httptest"
        "net/url"
        "reflect"
+       "runtime"
        "strconv"
        "strings"
        "sync"
@@ -58,18 +60,9 @@ func pedanticReadAll(r io.Reader) (b []byte, err error) {
        }
 }
 
-type chanWriter chan string
-
-func (w chanWriter) Write(p []byte) (n int, err error) {
-       w <- string(p)
-       return len(p), nil
-}
-
-func TestClient(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
-       ts := httptest.NewServer(robotsTxtHandler)
-       defer ts.Close()
+func TestClient(t *testing.T) { run(t, testClient) }
+func testClient(t *testing.T, mode testMode) {
+       ts := newClientServerTest(t, mode, robotsTxtHandler).ts
 
        c := ts.Client()
        r, err := c.Get(ts.URL)
@@ -85,14 +78,9 @@ func TestClient(t *testing.T) {
        }
 }
 
-func TestClientHead_h1(t *testing.T) { testClientHead(t, h1Mode) }
-func TestClientHead_h2(t *testing.T) { testClientHead(t, h2Mode) }
-
-func testClientHead(t *testing.T, h2 bool) {
-       defer afterTest(t)
-       cst := newClientServerTest(t, h2, robotsTxtHandler)
-       defer cst.close()
-
+func TestClientHead(t *testing.T) { run(t, testClientHead) }
+func testClientHead(t *testing.T, mode testMode) {
+       cst := newClientServerTest(t, mode, robotsTxtHandler)
        r, err := cst.c.Head(cst.ts.URL)
        if err != nil {
                t.Fatal(err)
@@ -198,11 +186,10 @@ func TestPostFormRequestFormat(t *testing.T) {
        }
 }
 
-func TestClientRedirects(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
+func TestClientRedirects(t *testing.T) { run(t, testClientRedirects) }
+func testClientRedirects(t *testing.T, mode testMode) {
        var ts *httptest.Server
-       ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                n, _ := strconv.Atoi(r.FormValue("n"))
                // Test Referer header. (7 is arbitrary position to test at)
                if n == 7 {
@@ -215,8 +202,7 @@ func TestClientRedirects(t *testing.T) {
                        return
                }
                fmt.Fprintf(w, "n=%d", n)
-       }))
-       defer ts.Close()
+       })).ts
 
        c := ts.Client()
        _, err := c.Get(ts.URL)
@@ -297,13 +283,11 @@ func TestClientRedirects(t *testing.T) {
 }
 
 // Tests that Client redirects' contexts are derived from the original request's context.
-func TestClientRedirectContext(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
-       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+func TestClientRedirectsContext(t *testing.T) { run(t, testClientRedirectsContext) }
+func testClientRedirectsContext(t *testing.T, mode testMode) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                Redirect(w, r, "/", StatusTemporaryRedirect)
-       }))
-       defer ts.Close()
+       })).ts
 
        ctx, cancel := context.WithCancel(context.Background())
        c := ts.Client()
@@ -371,7 +355,9 @@ func TestPostRedirects(t *testing.T) {
                `POST /?code=404 "c404"`,
        }
        want := strings.Join(wantSegments, "\n")
-       testRedirectsByMethod(t, "POST", postRedirectTests, want)
+       run(t, func(t *testing.T, mode testMode) {
+               testRedirectsByMethod(t, mode, "POST", postRedirectTests, want)
+       })
 }
 
 func TestDeleteRedirects(t *testing.T) {
@@ -408,17 +394,18 @@ func TestDeleteRedirects(t *testing.T) {
                `DELETE /?code=404 "c404"`,
        }
        want := strings.Join(wantSegments, "\n")
-       testRedirectsByMethod(t, "DELETE", deleteRedirectTests, want)
+       run(t, func(t *testing.T, mode testMode) {
+               testRedirectsByMethod(t, mode, "DELETE", deleteRedirectTests, want)
+       })
 }
 
-func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, want string) {
-       defer afterTest(t)
+func testRedirectsByMethod(t *testing.T, mode testMode, method string, table []redirectTest, want string) {
        var log struct {
                sync.Mutex
                bytes.Buffer
        }
        var ts *httptest.Server
-       ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                log.Lock()
                slurp, _ := io.ReadAll(r.Body)
                fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
@@ -431,11 +418,10 @@ func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, wa
                if v := urlQuery.Get("code"); v != "" {
                        location := ts.URL
                        if final := urlQuery.Get("next"); final != "" {
-                               splits := strings.Split(final, ",")
-                               first, rest := splits[0], splits[1:]
+                               first, rest, _ := strings.Cut(final, ",")
                                location = fmt.Sprintf("%s?code=%s", location, first)
-                               if len(rest) > 0 {
-                                       location = fmt.Sprintf("%s&next=%s", location, strings.Join(rest, ","))
+                               if rest != "" {
+                                       location = fmt.Sprintf("%s&next=%s", location, rest)
                                }
                        }
                        code, _ := strconv.Atoi(v)
@@ -444,8 +430,7 @@ func testRedirectsByMethod(t *testing.T, method string, table []redirectTest, wa
                        }
                        w.WriteHeader(code)
                }
-       }))
-       defer ts.Close()
+       })).ts
 
        c := ts.Client()
        for _, tt := range table {
@@ -490,12 +475,11 @@ func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) {
        }
 }
 
-func TestClientRedirectUseResponse(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
+func TestClientRedirectUseResponse(t *testing.T) { run(t, testClientRedirectUseResponse) }
+func testClientRedirectUseResponse(t *testing.T, mode testMode) {
        const body = "Hello, world."
        var ts *httptest.Server
-       ts = httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                if strings.Contains(r.URL.Path, "/other") {
                        io.WriteString(w, "wrong body")
                } else {
@@ -503,8 +487,7 @@ func TestClientRedirectUseResponse(t *testing.T) {
                        w.WriteHeader(StatusFound)
                        io.WriteString(w, body)
                }
-       }))
-       defer ts.Close()
+       })).ts
 
        c := ts.Client()
        c.CheckRedirect = func(req *Request, via []*Request) error {
@@ -530,40 +513,40 @@ func TestClientRedirectUseResponse(t *testing.T) {
        }
 }
 
-// Issue 17773: don't follow a 308 (or 307) if the response doesn't
+// Issues 17773 and 49281: don't follow a 3xx if the response doesn't
 // have a Location header.
-func TestClientRedirect308NoLocation(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
-       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
-               w.Header().Set("Foo", "Bar")
-               w.WriteHeader(308)
-       }))
-       defer ts.Close()
-       c := ts.Client()
-       res, err := c.Get(ts.URL)
-       if err != nil {
-               t.Fatal(err)
-       }
-       res.Body.Close()
-       if res.StatusCode != 308 {
-               t.Errorf("status = %d; want %d", res.StatusCode, 308)
-       }
-       if got := res.Header.Get("Foo"); got != "Bar" {
-               t.Errorf("Foo header = %q; want Bar", got)
+func TestClientRedirectNoLocation(t *testing.T) { run(t, testClientRedirectNoLocation) }
+func testClientRedirectNoLocation(t *testing.T, mode testMode) {
+       for _, code := range []int{301, 308} {
+               t.Run(fmt.Sprint(code), func(t *testing.T) {
+                       setParallel(t)
+                       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+                               w.Header().Set("Foo", "Bar")
+                               w.WriteHeader(code)
+                       }))
+                       res, err := cst.c.Get(cst.ts.URL)
+                       if err != nil {
+                               t.Fatal(err)
+                       }
+                       res.Body.Close()
+                       if res.StatusCode != code {
+                               t.Errorf("status = %d; want %d", res.StatusCode, code)
+                       }
+                       if got := res.Header.Get("Foo"); got != "Bar" {
+                               t.Errorf("Foo header = %q; want Bar", got)
+                       }
+               })
        }
 }
 
 // Don't follow a 307/308 if we can't resent the request body.
-func TestClientRedirect308NoGetBody(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
+func TestClientRedirect308NoGetBody(t *testing.T) { run(t, testClientRedirect308NoGetBody) }
+func testClientRedirect308NoGetBody(t *testing.T, mode testMode) {
        const fakeURL = "https://localhost:1234/" // won't be hit
-       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                w.Header().Set("Location", fakeURL)
                w.WriteHeader(308)
-       }))
-       defer ts.Close()
+       })).ts
        req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
        if err != nil {
                t.Fatal(err)
@@ -654,12 +637,10 @@ func (j *TestJar) Cookies(u *url.URL) []*Cookie {
        return j.perURL[u.Host]
 }
 
-func TestRedirectCookiesJar(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
+func TestRedirectCookiesJar(t *testing.T) { run(t, testRedirectCookiesJar) }
+func testRedirectCookiesJar(t *testing.T, mode testMode) {
        var ts *httptest.Server
-       ts = httptest.NewServer(echoCookiesRedirectHandler)
-       defer ts.Close()
+       ts = newClientServerTest(t, mode, echoCookiesRedirectHandler).ts
        c := ts.Client()
        c.Jar = new(TestJar)
        u, _ := url.Parse(ts.URL)
@@ -691,9 +672,9 @@ func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
        }
 }
 
-func TestJarCalls(t *testing.T) {
-       defer afterTest(t)
-       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+func TestJarCalls(t *testing.T) { run(t, testJarCalls, []testMode{http1Mode}) }
+func testJarCalls(t *testing.T, mode testMode) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                pathSuffix := r.RequestURI[1:]
                if r.RequestURI == "/nosetcookie" {
                        return // don't set cookies for this path
@@ -702,8 +683,7 @@ func TestJarCalls(t *testing.T) {
                if r.RequestURI == "/" {
                        Redirect(w, r, "http://secondhost.fake/secondpath", 302)
                }
-       }))
-       defer ts.Close()
+       })).ts
        jar := new(RecordingJar)
        c := ts.Client()
        c.Jar = jar
@@ -746,26 +726,22 @@ func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
        return nil
 }
 
-func (j *RecordingJar) logf(format string, args ...interface{}) {
+func (j *RecordingJar) logf(format string, args ...any) {
        j.mu.Lock()
        defer j.mu.Unlock()
        fmt.Fprintf(&j.log, format, args...)
 }
 
-func TestStreamingGet_h1(t *testing.T) { testStreamingGet(t, h1Mode) }
-func TestStreamingGet_h2(t *testing.T) { testStreamingGet(t, h2Mode) }
-
-func testStreamingGet(t *testing.T, h2 bool) {
-       defer afterTest(t)
+func TestStreamingGet(t *testing.T) { run(t, testStreamingGet) }
+func testStreamingGet(t *testing.T, mode testMode) {
        say := make(chan string)
-       cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                w.(Flusher).Flush()
                for str := range say {
                        w.Write([]byte(str))
                        w.(Flusher).Flush()
                }
        }))
-       defer cst.close()
 
        c := cst.c
        res, err := c.Get(cst.ts.URL)
@@ -806,11 +782,10 @@ func (c *writeCountingConn) Write(p []byte) (int, error) {
 
 // TestClientWrites verifies that client requests are buffered and we
 // don't send a TCP packet per line of the http request + body.
-func TestClientWrites(t *testing.T) {
-       defer afterTest(t)
-       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
-       }))
-       defer ts.Close()
+func TestClientWrites(t *testing.T) { run(t, testClientWrites, []testMode{http1Mode}) }
+func testClientWrites(t *testing.T, mode testMode) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+       })).ts
 
        writes := 0
        dialer := func(netz string, addr string) (net.Conn, error) {
@@ -842,14 +817,15 @@ func TestClientWrites(t *testing.T) {
 }
 
 func TestClientInsecureTransport(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
-       ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       run(t, testClientInsecureTransport, []testMode{https1Mode, http2Mode})
+}
+func testClientInsecureTransport(t *testing.T, mode testMode) {
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                w.Write([]byte("Hello"))
        }))
-       errc := make(chanWriter, 10) // but only expecting 1
-       ts.Config.ErrorLog = log.New(errc, "", 0)
-       defer ts.Close()
+       ts := cst.ts
+       errLog := new(strings.Builder)
+       ts.Config.ErrorLog = log.New(errLog, "", 0)
 
        // TODO(bradfitz): add tests for skipping hostname checks too?
        // would require a new cert for testing, and probably
@@ -868,15 +844,10 @@ func TestClientInsecureTransport(t *testing.T) {
                }
        }
 
-       select {
-       case v := <-errc:
-               if !strings.Contains(v, "TLS handshake error") {
-                       t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
-               }
-       case <-time.After(5 * time.Second):
-               t.Errorf("timeout waiting for logged error")
+       cst.close()
+       if !strings.Contains(errLog.String(), "TLS handshake error") {
+               t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", errLog)
        }
-
 }
 
 func TestClientErrorWithRequestURI(t *testing.T) {
@@ -893,15 +864,15 @@ func TestClientErrorWithRequestURI(t *testing.T) {
 }
 
 func TestClientWithCorrectTLSServerName(t *testing.T) {
-       defer afterTest(t)
-
+       run(t, testClientWithCorrectTLSServerName, []testMode{https1Mode, http2Mode})
+}
+func testClientWithCorrectTLSServerName(t *testing.T, mode testMode) {
        const serverName = "example.com"
-       ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                if r.TLS.ServerName != serverName {
                        t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
                }
-       }))
-       defer ts.Close()
+       })).ts
 
        c := ts.Client()
        c.Transport.(*Transport).TLSClientConfig.ServerName = serverName
@@ -911,11 +882,13 @@ func TestClientWithCorrectTLSServerName(t *testing.T) {
 }
 
 func TestClientWithIncorrectTLSServerName(t *testing.T) {
-       defer afterTest(t)
-       ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
-       defer ts.Close()
-       errc := make(chanWriter, 10) // but only expecting 1
-       ts.Config.ErrorLog = log.New(errc, "", 0)
+       run(t, testClientWithIncorrectTLSServerName, []testMode{https1Mode, http2Mode})
+}
+func testClientWithIncorrectTLSServerName(t *testing.T, mode testMode) {
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {}))
+       ts := cst.ts
+       errLog := new(strings.Builder)
+       ts.Config.ErrorLog = log.New(errLog, "", 0)
 
        c := ts.Client()
        c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver"
@@ -926,13 +899,10 @@ func TestClientWithIncorrectTLSServerName(t *testing.T) {
        if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
                t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
        }
-       select {
-       case v := <-errc:
-               if !strings.Contains(v, "TLS handshake error") {
-                       t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
-               }
-       case <-time.After(5 * time.Second):
-               t.Errorf("timeout waiting for logged error")
+
+       cst.close()
+       if !strings.Contains(errLog.String(), "TLS handshake error") {
+               t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", errLog)
        }
 }
 
@@ -946,11 +916,12 @@ func TestClientWithIncorrectTLSServerName(t *testing.T) {
 //
 // The httptest.Server has a cert with "example.com" as its name.
 func TestTransportUsesTLSConfigServerName(t *testing.T) {
-       defer afterTest(t)
-       ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       run(t, testTransportUsesTLSConfigServerName, []testMode{https1Mode, http2Mode})
+}
+func testTransportUsesTLSConfigServerName(t *testing.T, mode testMode) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                w.Write([]byte("Hello"))
-       }))
-       defer ts.Close()
+       })).ts
 
        c := ts.Client()
        tr := c.Transport.(*Transport)
@@ -966,15 +937,16 @@ func TestTransportUsesTLSConfigServerName(t *testing.T) {
 }
 
 func TestResponseSetsTLSConnectionState(t *testing.T) {
-       defer afterTest(t)
-       ts := httptest.NewTLSServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       run(t, testResponseSetsTLSConnectionState, []testMode{https1Mode})
+}
+func testResponseSetsTLSConnectionState(t *testing.T, mode testMode) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                w.Write([]byte("Hello"))
-       }))
-       defer ts.Close()
+       })).ts
 
        c := ts.Client()
        tr := c.Transport.(*Transport)
-       tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
+       tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA}
        tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite
        tr.Dial = func(netw, addr string) (net.Conn, error) {
                return net.Dial(netw, ts.Listener.Addr().String())
@@ -987,7 +959,7 @@ func TestResponseSetsTLSConnectionState(t *testing.T) {
        if res.TLS == nil {
                t.Fatal("Response didn't set TLS Connection State.")
        }
-       if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
+       if got, want := res.TLS.CipherSuite, tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
                t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
        }
 }
@@ -996,10 +968,11 @@ func TestResponseSetsTLSConnectionState(t *testing.T) {
 // to determine that the server is speaking HTTP.
 // See golang.org/issue/11111.
 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
-       defer afterTest(t)
-       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {}))
+       run(t, testHTTPSClientDetectsHTTPServer, []testMode{http1Mode})
+}
+func testHTTPSClientDetectsHTTPServer(t *testing.T, mode testMode) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {})).ts
        ts.Config.ErrorLog = quietLog
-       defer ts.Close()
 
        _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
        if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
@@ -1008,22 +981,13 @@ func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
 }
 
 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
-func TestClientHeadContentLength_h1(t *testing.T) {
-       testClientHeadContentLength(t, h1Mode)
-}
-
-func TestClientHeadContentLength_h2(t *testing.T) {
-       testClientHeadContentLength(t, h2Mode)
-}
-
-func testClientHeadContentLength(t *testing.T, h2 bool) {
-       defer afterTest(t)
-       cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
+func TestClientHeadContentLength(t *testing.T) { run(t, testClientHeadContentLength) }
+func testClientHeadContentLength(t *testing.T, mode testMode) {
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                if v := r.FormValue("cl"); v != "" {
                        w.Header().Set("Content-Length", v)
                }
        }))
-       defer cst.close()
        tests := []struct {
                suffix string
                want   int64
@@ -1051,11 +1015,10 @@ func testClientHeadContentLength(t *testing.T, h2 bool) {
        }
 }
 
-func TestEmptyPasswordAuth(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
+func TestEmptyPasswordAuth(t *testing.T) { run(t, testEmptyPasswordAuth) }
+func testEmptyPasswordAuth(t *testing.T, mode testMode) {
        gopher := "gopher"
-       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                auth := r.Header.Get("Authorization")
                if strings.HasPrefix(auth, "Basic ") {
                        encoded := auth[6:]
@@ -1071,7 +1034,7 @@ func TestEmptyPasswordAuth(t *testing.T) {
                } else {
                        t.Errorf("Invalid auth %q", auth)
                }
-       }))
+       })).ts
        defer ts.Close()
        req, err := NewRequest("GET", ts.URL, nil)
        if err != nil {
@@ -1200,70 +1163,83 @@ func TestStripPasswordFromError(t *testing.T) {
        }
 }
 
-func TestClientTimeout_h1(t *testing.T) { testClientTimeout(t, h1Mode) }
-func TestClientTimeout_h2(t *testing.T) { testClientTimeout(t, h2Mode) }
-
-func testClientTimeout(t *testing.T, h2 bool) {
-       setParallel(t)
-       defer afterTest(t)
-       testDone := make(chan struct{}) // closed in defer below
-
-       sawRoot := make(chan bool, 1)
-       sawSlow := make(chan bool, 1)
-       cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
+func TestClientTimeout(t *testing.T) { run(t, testClientTimeout) }
+func testClientTimeout(t *testing.T, mode testMode) {
+       var (
+               mu           sync.Mutex
+               nonce        string // a unique per-request string
+               sawSlowNonce bool   // true if the handler saw /slow?nonce=<nonce>
+       )
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+               _ = r.ParseForm()
                if r.URL.Path == "/" {
-                       sawRoot <- true
-                       Redirect(w, r, "/slow", StatusFound)
+                       Redirect(w, r, "/slow?nonce="+r.Form.Get("nonce"), StatusFound)
                        return
                }
                if r.URL.Path == "/slow" {
-                       sawSlow <- true
+                       mu.Lock()
+                       if r.Form.Get("nonce") == nonce {
+                               sawSlowNonce = true
+                       } else {
+                               t.Logf("mismatched nonce: received %s, want %s", r.Form.Get("nonce"), nonce)
+                       }
+                       mu.Unlock()
+
                        w.Write([]byte("Hello"))
                        w.(Flusher).Flush()
-                       <-testDone
+                       <-r.Context().Done()
                        return
                }
        }))
-       defer cst.close()
-       defer close(testDone) // before cst.close, to unblock /slow handler
-
-       // 200ms should be long enough to get a normal request (the /
-       // handler), but not so long that it makes the test slow.
-       const timeout = 200 * time.Millisecond
-       cst.c.Timeout = timeout
 
-       res, err := cst.c.Get(cst.ts.URL)
-       if err != nil {
-               if strings.Contains(err.Error(), "Client.Timeout") {
-                       t.Skipf("host too slow to get fast resource in %v", timeout)
+       // Try to trigger a timeout after reading part of the response body.
+       // The initial timeout is empirically usually long enough on a decently fast
+       // machine, but if we undershoot we'll retry with exponentially longer
+       // timeouts until the test either passes or times out completely.
+       // This keeps the test reasonably fast in the typical case but allows it to
+       // also eventually succeed on arbitrarily slow machines.
+       timeout := 10 * time.Millisecond
+       nextNonce := 0
+       for ; ; timeout *= 2 {
+               if timeout <= 0 {
+                       // The only way we can feasibly hit this while the test is running is if
+                       // the request fails without actually waiting for the timeout to occur.
+                       t.Fatalf("timeout overflow")
+               }
+               if deadline, ok := t.Deadline(); ok && !time.Now().Add(timeout).Before(deadline) {
+                       t.Fatalf("failed to produce expected timeout before test deadline")
+               }
+               t.Logf("attempting test with timeout %v", timeout)
+               cst.c.Timeout = timeout
+
+               mu.Lock()
+               nonce = fmt.Sprint(nextNonce)
+               nextNonce++
+               sawSlowNonce = false
+               mu.Unlock()
+               res, err := cst.c.Get(cst.ts.URL + "/?nonce=" + nonce)
+               if err != nil {
+                       if strings.Contains(err.Error(), "Client.Timeout") {
+                               // Timed out before handler could respond.
+                               t.Logf("timeout before response received")
+                               continue
+                       }
+                       if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
+                               testenv.SkipFlaky(t, 43120)
+                       }
+                       t.Fatal(err)
                }
-               t.Fatal(err)
-       }
-
-       select {
-       case <-sawRoot:
-               // good.
-       default:
-               t.Fatal("handler never got / request")
-       }
 
-       select {
-       case <-sawSlow:
-               // good.
-       default:
-               t.Fatal("handler never got /slow request")
-       }
+               mu.Lock()
+               ok := sawSlowNonce
+               mu.Unlock()
+               if !ok {
+                       t.Fatal("handler never got /slow request, but client returned response")
+               }
 
-       errc := make(chan error, 1)
-       go func() {
-               _, err := io.ReadAll(res.Body)
-               errc <- err
+               _, err = io.ReadAll(res.Body)
                res.Body.Close()
-       }()
 
-       const failTime = 5 * time.Second
-       select {
-       case err := <-errc:
                if err == nil {
                        t.Fatal("expected error from ReadAll")
                }
@@ -1274,25 +1250,23 @@ func testClientTimeout(t *testing.T, h2 bool) {
                        t.Errorf("net.Error.Timeout = false; want true")
                }
                if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
+                       if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
+                               testenv.SkipFlaky(t, 43120)
+                       }
                        t.Errorf("error string = %q; missing timeout substring", got)
                }
-       case <-time.After(failTime):
-               t.Errorf("timeout after %v waiting for timeout of %v", failTime, timeout)
+
+               break
        }
 }
 
-func TestClientTimeout_Headers_h1(t *testing.T) { testClientTimeout_Headers(t, h1Mode) }
-func TestClientTimeout_Headers_h2(t *testing.T) { testClientTimeout_Headers(t, h2Mode) }
-
 // Client.Timeout firing before getting to the body
-func testClientTimeout_Headers(t *testing.T, h2 bool) {
-       setParallel(t)
-       defer afterTest(t)
+func TestClientTimeout_Headers(t *testing.T) { run(t, testClientTimeout_Headers) }
+func testClientTimeout_Headers(t *testing.T, mode testMode) {
        donec := make(chan bool, 1)
-       cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                <-donec
        }), optQuietLog)
-       defer cst.close()
        // Note that we use a channel send here and not a close.
        // The race detector doesn't know that we're waiting for a timeout
        // and thinks that the waitgroup inside httptest.Server is added to concurrently
@@ -1319,24 +1293,24 @@ func testClientTimeout_Headers(t *testing.T, h2 bool) {
                t.Error("net.Error.Timeout = false; want true")
        }
        if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
+               if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
+                       testenv.SkipFlaky(t, 43120)
+               }
                t.Errorf("error string = %q; missing timeout substring", got)
        }
 }
 
 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
 // returned.
-func TestClientTimeoutCancel(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
-
+func TestClientTimeoutCancel(t *testing.T) { run(t, testClientTimeoutCancel) }
+func testClientTimeoutCancel(t *testing.T, mode testMode) {
        testDone := make(chan struct{})
        ctx, cancel := context.WithCancel(context.Background())
 
-       cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                w.(Flusher).Flush()
                <-testDone
        }))
-       defer cst.close()
        defer close(testDone)
 
        cst.c.Timeout = 1 * time.Hour
@@ -1353,19 +1327,36 @@ func TestClientTimeoutCancel(t *testing.T) {
        }
 }
 
-func TestClientRedirectEatsBody_h1(t *testing.T) { testClientRedirectEatsBody(t, h1Mode) }
-func TestClientRedirectEatsBody_h2(t *testing.T) { testClientRedirectEatsBody(t, h2Mode) }
-func testClientRedirectEatsBody(t *testing.T, h2 bool) {
-       setParallel(t)
-       defer afterTest(t)
+// Issue 49366: if Client.Timeout is set but not hit, no error should be returned.
+func TestClientTimeoutDoesNotExpire(t *testing.T) { run(t, testClientTimeoutDoesNotExpire) }
+func testClientTimeoutDoesNotExpire(t *testing.T, mode testMode) {
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+               w.Write([]byte("body"))
+       }))
+
+       cst.c.Timeout = 1 * time.Hour
+       req, _ := NewRequest("GET", cst.ts.URL, nil)
+       res, err := cst.c.Do(req)
+       if err != nil {
+               t.Fatal(err)
+       }
+       if _, err = io.Copy(io.Discard, res.Body); err != nil {
+               t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err)
+       }
+       if err = res.Body.Close(); err != nil {
+               t.Fatalf("res.Body.Close() = %v, want nil", err)
+       }
+}
+
+func TestClientRedirectEatsBody_h1(t *testing.T) { run(t, testClientRedirectEatsBody) }
+func testClientRedirectEatsBody(t *testing.T, mode testMode) {
        saw := make(chan string, 2)
-       cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                saw <- r.RemoteAddr
                if r.URL.Path == "/" {
                        Redirect(w, r, "/foo", StatusFound) // which includes a body
                }
        }))
-       defer cst.close()
 
        res, err := cst.c.Get(cst.ts.URL)
        if err != nil {
@@ -1406,24 +1397,32 @@ func (f eofReaderFunc) Read(p []byte) (n int, err error) {
 
 func TestReferer(t *testing.T) {
        tests := []struct {
-               lastReq, newReq string // from -> to URLs
-               want            string
+               lastReq, newReq, explicitRef string // from -> to URLs, explicitly set Referer value
+               want                         string
        }{
                // don't send user:
-               {"http://gopher@test.com", "http://link.com", "http://test.com"},
-               {"https://gopher@test.com", "https://link.com", "https://test.com"},
+               {lastReq: "http://gopher@test.com", newReq: "http://link.com", want: "http://test.com"},
+               {lastReq: "https://gopher@test.com", newReq: "https://link.com", want: "https://test.com"},
 
                // don't send a user and password:
-               {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
-               {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
+               {lastReq: "http://gopher:go@test.com", newReq: "http://link.com", want: "http://test.com"},
+               {lastReq: "https://gopher:go@test.com", newReq: "https://link.com", want: "https://test.com"},
 
                // nothing to do:
-               {"http://test.com", "http://link.com", "http://test.com"},
-               {"https://test.com", "https://link.com", "https://test.com"},
+               {lastReq: "http://test.com", newReq: "http://link.com", want: "http://test.com"},
+               {lastReq: "https://test.com", newReq: "https://link.com", want: "https://test.com"},
 
                // https to http doesn't send a referer:
-               {"https://test.com", "http://link.com", ""},
-               {"https://gopher:go@test.com", "http://link.com", ""},
+               {lastReq: "https://test.com", newReq: "http://link.com", want: ""},
+               {lastReq: "https://gopher:go@test.com", newReq: "http://link.com", want: ""},
+
+               // https to http should remove an existing referer:
+               {lastReq: "https://test.com", newReq: "http://link.com", explicitRef: "https://foo.com", want: ""},
+               {lastReq: "https://gopher:go@test.com", newReq: "http://link.com", explicitRef: "https://foo.com", want: ""},
+
+               // don't override an existing referer:
+               {lastReq: "https://test.com", newReq: "https://link.com", explicitRef: "https://foo.com", want: "https://foo.com"},
+               {lastReq: "https://gopher:go@test.com", newReq: "https://link.com", explicitRef: "https://foo.com", want: "https://foo.com"},
        }
        for _, tt := range tests {
                l, err := url.Parse(tt.lastReq)
@@ -1434,7 +1433,7 @@ func TestReferer(t *testing.T) {
                if err != nil {
                        t.Fatal(err)
                }
-               r := ExportRefererForURL(l, n)
+               r := ExportRefererForURL(l, n, tt.explicitRef)
                if r != tt.want {
                        t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
                }
@@ -1465,18 +1464,24 @@ func TestClientRedirectResponseWithoutRequest(t *testing.T) {
 }
 
 // Issue 4800: copy (some) headers when Client follows a redirect.
-func TestClientCopyHeadersOnRedirect(t *testing.T) {
+// Issue 35104: Since both URLs have the same host (localhost)
+// but different ports, sensitive headers like Cookie and Authorization
+// are preserved.
+func TestClientCopyHeadersOnRedirect(t *testing.T) { run(t, testClientCopyHeadersOnRedirect) }
+func testClientCopyHeadersOnRedirect(t *testing.T, mode testMode) {
        const (
                ua   = "some-agent/1.2"
                xfoo = "foo-val"
        )
        var ts2URL string
-       ts1 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       ts1 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                want := Header{
                        "User-Agent":      []string{ua},
                        "X-Foo":           []string{xfoo},
                        "Referer":         []string{ts2URL},
                        "Accept-Encoding": []string{"gzip"},
+                       "Cookie":          []string{"foo=bar"},
+                       "Authorization":   []string{"secretpassword"},
                }
                if !reflect.DeepEqual(r.Header, want) {
                        t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
@@ -1486,20 +1491,20 @@ func TestClientCopyHeadersOnRedirect(t *testing.T) {
                } else {
                        w.Header().Set("Result", "ok")
                }
-       }))
-       defer ts1.Close()
-       ts2 := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       })).ts
+       ts2 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                Redirect(w, r, ts1.URL, StatusFound)
-       }))
-       defer ts2.Close()
+       })).ts
        ts2URL = ts2.URL
 
        c := ts1.Client()
        c.CheckRedirect = func(r *Request, via []*Request) error {
                want := Header{
-                       "User-Agent": []string{ua},
-                       "X-Foo":      []string{xfoo},
-                       "Referer":    []string{ts2URL},
+                       "User-Agent":    []string{ua},
+                       "X-Foo":         []string{xfoo},
+                       "Referer":       []string{ts2URL},
+                       "Cookie":        []string{"foo=bar"},
+                       "Authorization": []string{"secretpassword"},
                }
                if !reflect.DeepEqual(r.Header, want) {
                        t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
@@ -1526,22 +1531,24 @@ func TestClientCopyHeadersOnRedirect(t *testing.T) {
 }
 
 // Issue 22233: copy host when Client follows a relative redirect.
-func TestClientCopyHostOnRedirect(t *testing.T) {
+func TestClientCopyHostOnRedirect(t *testing.T) { run(t, testClientCopyHostOnRedirect) }
+func testClientCopyHostOnRedirect(t *testing.T, mode testMode) {
        // Virtual hostname: should not receive any request.
-       virtual := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       virtual := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                t.Errorf("Virtual host received request %v", r.URL)
                w.WriteHeader(403)
                io.WriteString(w, "should not see this response")
-       }))
+       })).ts
        defer virtual.Close()
        virtualHost := strings.TrimPrefix(virtual.URL, "http://")
+       virtualHost = strings.TrimPrefix(virtualHost, "https://")
        t.Logf("Virtual host is %v", virtualHost)
 
        // Actual hostname: should not receive any request.
        const wantBody = "response body"
        var tsURL string
        var tsHost string
-       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                switch r.URL.Path {
                case "/":
                        // Relative redirect.
@@ -1573,10 +1580,10 @@ func TestClientCopyHostOnRedirect(t *testing.T) {
                        t.Errorf("Serving unexpected path %q", r.URL.Path)
                        w.WriteHeader(404)
                }
-       }))
-       defer ts.Close()
+       })).ts
        tsURL = ts.URL
        tsHost = strings.TrimPrefix(ts.URL, "http://")
+       tsHost = strings.TrimPrefix(tsHost, "https://")
        t.Logf("Server host is %v", tsHost)
 
        c := ts.Client()
@@ -1596,7 +1603,8 @@ func TestClientCopyHostOnRedirect(t *testing.T) {
 }
 
 // Issue 17494: cookies should be altered when Client follows redirects.
-func TestClientAltersCookiesOnRedirect(t *testing.T) {
+func TestClientAltersCookiesOnRedirect(t *testing.T) { run(t, testClientAltersCookiesOnRedirect) }
+func testClientAltersCookiesOnRedirect(t *testing.T, mode testMode) {
        cookieMap := func(cs []*Cookie) map[string][]string {
                m := make(map[string][]string)
                for _, c := range cs {
@@ -1605,7 +1613,7 @@ func TestClientAltersCookiesOnRedirect(t *testing.T) {
                return m
        }
 
-       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                var want map[string][]string
                got := cookieMap(r.Cookies())
 
@@ -1660,8 +1668,7 @@ func TestClientAltersCookiesOnRedirect(t *testing.T) {
                if !reflect.DeepEqual(got, want) {
                        t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
                }
-       }))
-       defer ts.Close()
+       })).ts
 
        jar, _ := cookiejar.New(nil)
        c := ts.Client()
@@ -1701,18 +1708,30 @@ func TestShouldCopyHeaderOnRedirect(t *testing.T) {
                {"cookie", "http://foo.com/", "http://bar.com/", false},
                {"cookie2", "http://foo.com/", "http://bar.com/", false},
                {"authorization", "http://foo.com/", "http://bar.com/", false},
+               {"authorization", "http://foo.com/", "https://foo.com/", true},
+               {"authorization", "http://foo.com:1234/", "http://foo.com:4321/", true},
                {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
 
                // But subdomains should work:
                {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
                {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
                {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
-               {"www-authenticate", "http://foo.com/", "https://foo.com/", false},
+               {"www-authenticate", "http://foo.com/", "https://foo.com/", true},
                {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
                {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
                {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
                {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
-               {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", false},
+               {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", true},
+
+               {"authorization", "http://foo.com/", "http://foo.com/", true},
+               {"authorization", "http://foo.com/", "http://sub.foo.com/", true},
+               {"authorization", "http://foo.com/", "http://notfoo.com/", false},
+               {"authorization", "http://foo.com/", "https://foo.com/", true},
+               {"authorization", "http://foo.com:80/", "http://foo.com/", true},
+               {"authorization", "http://foo.com:80/", "http://sub.foo.com/", true},
+               {"authorization", "http://foo.com:443/", "https://foo.com/", true},
+               {"authorization", "http://foo.com:443/", "https://sub.foo.com/", true},
+               {"authorization", "http://foo.com:1234/", "http://foo.com/", true},
        }
        for i, tt := range tests {
                u0, err := url.Parse(tt.initialURL)
@@ -1733,10 +1752,8 @@ func TestShouldCopyHeaderOnRedirect(t *testing.T) {
        }
 }
 
-func TestClientRedirectTypes(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
-
+func TestClientRedirectTypes(t *testing.T) { run(t, testClientRedirectTypes) }
+func testClientRedirectTypes(t *testing.T, mode testMode) {
        tests := [...]struct {
                method       string
                serverStatus int
@@ -1781,11 +1798,10 @@ func TestClientRedirectTypes(t *testing.T) {
 
        handlerc := make(chan HandlerFunc, 1)
 
-       ts := httptest.NewServer(HandlerFunc(func(rw ResponseWriter, req *Request) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) {
                h := <-handlerc
                h(rw, req)
-       }))
-       defer ts.Close()
+       })).ts
 
        c := ts.Client()
        for i, tt := range tests {
@@ -1841,18 +1857,16 @@ func (b issue18239Body) Close() error {
 
 // Issue 18239: make sure the Transport doesn't retry requests with bodies
 // if Request.GetBody is not defined.
-func TestTransportBodyReadError(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
-       ts := httptest.NewServer(HandlerFunc(func(w ResponseWriter, r *Request) {
+func TestTransportBodyReadError(t *testing.T) { run(t, testTransportBodyReadError) }
+func testTransportBodyReadError(t *testing.T, mode testMode) {
+       ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                if r.URL.Path == "/ping" {
                        return
                }
                buf := make([]byte, 1)
                n, err := r.Body.Read(buf)
                w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
-       }))
-       defer ts.Close()
+       })).ts
        c := ts.Client()
        tr := c.Transport.(*Transport)
 
@@ -1936,22 +1950,13 @@ func TestClientPropagatesTimeoutToContext(t *testing.T) {
        c.Get("https://example.tld/")
 }
 
-func TestClientDoCanceledVsTimeout_h1(t *testing.T) {
-       testClientDoCanceledVsTimeout(t, h1Mode)
-}
-
-func TestClientDoCanceledVsTimeout_h2(t *testing.T) {
-       testClientDoCanceledVsTimeout(t, h2Mode)
-}
-
 // Issue 33545: lock-in the behavior promised by Client.Do's
 // docs about request cancellation vs timing out.
-func testClientDoCanceledVsTimeout(t *testing.T, h2 bool) {
-       defer afterTest(t)
-       cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
+func TestClientDoCanceledVsTimeout(t *testing.T) { run(t, testClientDoCanceledVsTimeout) }
+func testClientDoCanceledVsTimeout(t *testing.T, mode testMode) {
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                w.Write([]byte("Hello, World!"))
        }))
-       defer cst.close()
 
        cases := []string{"timeout", "canceled"}
 
@@ -2027,13 +2032,11 @@ func TestClientPopulatesNilResponseBody(t *testing.T) {
 }
 
 // Issue 40382: Client calls Close multiple times on Request.Body.
-func TestClientCallsCloseOnlyOnce(t *testing.T) {
-       setParallel(t)
-       defer afterTest(t)
-       cst := newClientServerTest(t, h1Mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+func TestClientCallsCloseOnlyOnce(t *testing.T) { run(t, testClientCallsCloseOnlyOnce) }
+func testClientCallsCloseOnlyOnce(t *testing.T, mode testMode) {
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
                w.WriteHeader(StatusNoContent)
        }))
-       defer cst.close()
 
        // Issue occurred non-deterministically: needed to occur after a successful
        // write (into TCP buffer) but before end of body.
@@ -2082,3 +2085,45 @@ func (b *issue40382Body) Close() error {
        }
        return nil
 }
+
+func TestProbeZeroLengthBody(t *testing.T) { run(t, testProbeZeroLengthBody) }
+func testProbeZeroLengthBody(t *testing.T, mode testMode) {
+       reqc := make(chan struct{})
+       cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+               close(reqc)
+               if _, err := io.Copy(w, r.Body); err != nil {
+                       t.Errorf("error copying request body: %v", err)
+               }
+       }))
+
+       bodyr, bodyw := io.Pipe()
+       var gotBody string
+       var wg sync.WaitGroup
+       wg.Add(1)
+       go func() {
+               defer wg.Done()
+               req, _ := NewRequest("GET", cst.ts.URL, bodyr)
+               res, err := cst.c.Do(req)
+               b, err := io.ReadAll(res.Body)
+               if err != nil {
+                       t.Error(err)
+               }
+               gotBody = string(b)
+       }()
+
+       select {
+       case <-reqc:
+               // Request should be sent after trying to probe the request body for 200ms.
+       case <-time.After(60 * time.Second):
+               t.Errorf("request not sent after 60s")
+       }
+
+       // Write the request body and wait for the request to complete.
+       const content = "body"
+       bodyw.Write([]byte(content))
+       bodyw.Close()
+       wg.Wait()
+       if gotBody != content {
+               t.Fatalf("server got body %q, want %q", gotBody, content)
+       }
+}