]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/client_test.go
net/http: keep sensitive headers on redirects to the same host
[gostls13.git] / src / net / http / client_test.go
1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Tests for client.go
6
7 package http_test
8
9 import (
10         "bytes"
11         "context"
12         "crypto/tls"
13         "encoding/base64"
14         "errors"
15         "fmt"
16         "internal/testenv"
17         "io"
18         "log"
19         "net"
20         . "net/http"
21         "net/http/cookiejar"
22         "net/http/httptest"
23         "net/url"
24         "reflect"
25         "runtime"
26         "strconv"
27         "strings"
28         "sync"
29         "sync/atomic"
30         "testing"
31         "time"
32 )
33
34 var robotsTxtHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
35         w.Header().Set("Last-Modified", "sometime")
36         fmt.Fprintf(w, "User-agent: go\nDisallow: /something/")
37 })
38
39 // pedanticReadAll works like io.ReadAll but additionally
40 // verifies that r obeys the documented io.Reader contract.
41 func pedanticReadAll(r io.Reader) (b []byte, err error) {
42         var bufa [64]byte
43         buf := bufa[:]
44         for {
45                 n, err := r.Read(buf)
46                 if n == 0 && err == nil {
47                         return nil, fmt.Errorf("Read: n=0 with err=nil")
48                 }
49                 b = append(b, buf[:n]...)
50                 if err == io.EOF {
51                         n, err := r.Read(buf)
52                         if n != 0 || err != io.EOF {
53                                 return nil, fmt.Errorf("Read: n=%d err=%#v after EOF", n, err)
54                         }
55                         return b, nil
56                 }
57                 if err != nil {
58                         return b, err
59                 }
60         }
61 }
62
63 type chanWriter chan string
64
65 func (w chanWriter) Write(p []byte) (n int, err error) {
66         w <- string(p)
67         return len(p), nil
68 }
69
70 func TestClient(t *testing.T) { run(t, testClient) }
71 func testClient(t *testing.T, mode testMode) {
72         ts := newClientServerTest(t, mode, robotsTxtHandler).ts
73
74         c := ts.Client()
75         r, err := c.Get(ts.URL)
76         var b []byte
77         if err == nil {
78                 b, err = pedanticReadAll(r.Body)
79                 r.Body.Close()
80         }
81         if err != nil {
82                 t.Error(err)
83         } else if s := string(b); !strings.HasPrefix(s, "User-agent:") {
84                 t.Errorf("Incorrect page body (did not begin with User-agent): %q", s)
85         }
86 }
87
88 func TestClientHead(t *testing.T) { run(t, testClientHead) }
89 func testClientHead(t *testing.T, mode testMode) {
90         cst := newClientServerTest(t, mode, robotsTxtHandler)
91         r, err := cst.c.Head(cst.ts.URL)
92         if err != nil {
93                 t.Fatal(err)
94         }
95         if _, ok := r.Header["Last-Modified"]; !ok {
96                 t.Error("Last-Modified header not found.")
97         }
98 }
99
100 type recordingTransport struct {
101         req *Request
102 }
103
104 func (t *recordingTransport) RoundTrip(req *Request) (resp *Response, err error) {
105         t.req = req
106         return nil, errors.New("dummy impl")
107 }
108
109 func TestGetRequestFormat(t *testing.T) {
110         setParallel(t)
111         defer afterTest(t)
112         tr := &recordingTransport{}
113         client := &Client{Transport: tr}
114         url := "http://dummy.faketld/"
115         client.Get(url) // Note: doesn't hit network
116         if tr.req.Method != "GET" {
117                 t.Errorf("expected method %q; got %q", "GET", tr.req.Method)
118         }
119         if tr.req.URL.String() != url {
120                 t.Errorf("expected URL %q; got %q", url, tr.req.URL.String())
121         }
122         if tr.req.Header == nil {
123                 t.Errorf("expected non-nil request Header")
124         }
125 }
126
127 func TestPostRequestFormat(t *testing.T) {
128         defer afterTest(t)
129         tr := &recordingTransport{}
130         client := &Client{Transport: tr}
131
132         url := "http://dummy.faketld/"
133         json := `{"key":"value"}`
134         b := strings.NewReader(json)
135         client.Post(url, "application/json", b) // Note: doesn't hit network
136
137         if tr.req.Method != "POST" {
138                 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
139         }
140         if tr.req.URL.String() != url {
141                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
142         }
143         if tr.req.Header == nil {
144                 t.Fatalf("expected non-nil request Header")
145         }
146         if tr.req.Close {
147                 t.Error("got Close true, want false")
148         }
149         if g, e := tr.req.ContentLength, int64(len(json)); g != e {
150                 t.Errorf("got ContentLength %d, want %d", g, e)
151         }
152 }
153
154 func TestPostFormRequestFormat(t *testing.T) {
155         defer afterTest(t)
156         tr := &recordingTransport{}
157         client := &Client{Transport: tr}
158
159         urlStr := "http://dummy.faketld/"
160         form := make(url.Values)
161         form.Set("foo", "bar")
162         form.Add("foo", "bar2")
163         form.Set("bar", "baz")
164         client.PostForm(urlStr, form) // Note: doesn't hit network
165
166         if tr.req.Method != "POST" {
167                 t.Errorf("got method %q, want %q", tr.req.Method, "POST")
168         }
169         if tr.req.URL.String() != urlStr {
170                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), urlStr)
171         }
172         if tr.req.Header == nil {
173                 t.Fatalf("expected non-nil request Header")
174         }
175         if g, e := tr.req.Header.Get("Content-Type"), "application/x-www-form-urlencoded"; g != e {
176                 t.Errorf("got Content-Type %q, want %q", g, e)
177         }
178         if tr.req.Close {
179                 t.Error("got Close true, want false")
180         }
181         // Depending on map iteration, body can be either of these.
182         expectedBody := "foo=bar&foo=bar2&bar=baz"
183         expectedBody1 := "bar=baz&foo=bar&foo=bar2"
184         if g, e := tr.req.ContentLength, int64(len(expectedBody)); g != e {
185                 t.Errorf("got ContentLength %d, want %d", g, e)
186         }
187         bodyb, err := io.ReadAll(tr.req.Body)
188         if err != nil {
189                 t.Fatalf("ReadAll on req.Body: %v", err)
190         }
191         if g := string(bodyb); g != expectedBody && g != expectedBody1 {
192                 t.Errorf("got body %q, want %q or %q", g, expectedBody, expectedBody1)
193         }
194 }
195
196 func TestClientRedirects(t *testing.T) { run(t, testClientRedirects) }
197 func testClientRedirects(t *testing.T, mode testMode) {
198         var ts *httptest.Server
199         ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
200                 n, _ := strconv.Atoi(r.FormValue("n"))
201                 // Test Referer header. (7 is arbitrary position to test at)
202                 if n == 7 {
203                         if g, e := r.Referer(), ts.URL+"/?n=6"; e != g {
204                                 t.Errorf("on request ?n=7, expected referer of %q; got %q", e, g)
205                         }
206                 }
207                 if n < 15 {
208                         Redirect(w, r, fmt.Sprintf("/?n=%d", n+1), StatusTemporaryRedirect)
209                         return
210                 }
211                 fmt.Fprintf(w, "n=%d", n)
212         })).ts
213
214         c := ts.Client()
215         _, err := c.Get(ts.URL)
216         if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
217                 t.Errorf("with default client Get, expected error %q, got %q", e, g)
218         }
219
220         // HEAD request should also have the ability to follow redirects.
221         _, err = c.Head(ts.URL)
222         if e, g := `Head "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
223                 t.Errorf("with default client Head, expected error %q, got %q", e, g)
224         }
225
226         // Do should also follow redirects.
227         greq, _ := NewRequest("GET", ts.URL, nil)
228         _, err = c.Do(greq)
229         if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
230                 t.Errorf("with default client Do, expected error %q, got %q", e, g)
231         }
232
233         // Requests with an empty Method should also redirect (Issue 12705)
234         greq.Method = ""
235         _, err = c.Do(greq)
236         if e, g := `Get "/?n=10": stopped after 10 redirects`, fmt.Sprintf("%v", err); e != g {
237                 t.Errorf("with default client Do and empty Method, expected error %q, got %q", e, g)
238         }
239
240         var checkErr error
241         var lastVia []*Request
242         var lastReq *Request
243         c.CheckRedirect = func(req *Request, via []*Request) error {
244                 lastReq = req
245                 lastVia = via
246                 return checkErr
247         }
248         res, err := c.Get(ts.URL)
249         if err != nil {
250                 t.Fatalf("Get error: %v", err)
251         }
252         res.Body.Close()
253         finalURL := res.Request.URL.String()
254         if e, g := "<nil>", fmt.Sprintf("%v", err); e != g {
255                 t.Errorf("with custom client, expected error %q, got %q", e, g)
256         }
257         if !strings.HasSuffix(finalURL, "/?n=15") {
258                 t.Errorf("expected final url to end in /?n=15; got url %q", finalURL)
259         }
260         if e, g := 15, len(lastVia); e != g {
261                 t.Errorf("expected lastVia to have contained %d elements; got %d", e, g)
262         }
263
264         // Test that Request.Cancel is propagated between requests (Issue 14053)
265         creq, _ := NewRequest("HEAD", ts.URL, nil)
266         cancel := make(chan struct{})
267         creq.Cancel = cancel
268         if _, err := c.Do(creq); err != nil {
269                 t.Fatal(err)
270         }
271         if lastReq == nil {
272                 t.Fatal("didn't see redirect")
273         }
274         if lastReq.Cancel != cancel {
275                 t.Errorf("expected lastReq to have the cancel channel set on the initial req")
276         }
277
278         checkErr = errors.New("no redirects allowed")
279         res, err = c.Get(ts.URL)
280         if urlError, ok := err.(*url.Error); !ok || urlError.Err != checkErr {
281                 t.Errorf("with redirects forbidden, expected a *url.Error with our 'no redirects allowed' error inside; got %#v (%q)", err, err)
282         }
283         if res == nil {
284                 t.Fatalf("Expected a non-nil Response on CheckRedirect failure (https://golang.org/issue/3795)")
285         }
286         res.Body.Close()
287         if res.Header.Get("Location") == "" {
288                 t.Errorf("no Location header in Response")
289         }
290 }
291
292 // Tests that Client redirects' contexts are derived from the original request's context.
293 func TestClientRedirectsContext(t *testing.T) { run(t, testClientRedirectsContext) }
294 func testClientRedirectsContext(t *testing.T, mode testMode) {
295         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
296                 Redirect(w, r, "/", StatusTemporaryRedirect)
297         })).ts
298
299         ctx, cancel := context.WithCancel(context.Background())
300         c := ts.Client()
301         c.CheckRedirect = func(req *Request, via []*Request) error {
302                 cancel()
303                 select {
304                 case <-req.Context().Done():
305                         return nil
306                 case <-time.After(5 * time.Second):
307                         return errors.New("redirected request's context never expired after root request canceled")
308                 }
309         }
310         req, _ := NewRequestWithContext(ctx, "GET", ts.URL, nil)
311         _, err := c.Do(req)
312         ue, ok := err.(*url.Error)
313         if !ok {
314                 t.Fatalf("got error %T; want *url.Error", err)
315         }
316         if ue.Err != context.Canceled {
317                 t.Errorf("url.Error.Err = %v; want %v", ue.Err, context.Canceled)
318         }
319 }
320
321 type redirectTest struct {
322         suffix       string
323         want         int // response code
324         redirectBody string
325 }
326
327 func TestPostRedirects(t *testing.T) {
328         postRedirectTests := []redirectTest{
329                 {"/", 200, "first"},
330                 {"/?code=301&next=302", 200, "c301"},
331                 {"/?code=302&next=302", 200, "c302"},
332                 {"/?code=303&next=301", 200, "c303wc301"}, // Issue 9348
333                 {"/?code=304", 304, "c304"},
334                 {"/?code=305", 305, "c305"},
335                 {"/?code=307&next=303,308,302", 200, "c307"},
336                 {"/?code=308&next=302,301", 200, "c308"},
337                 {"/?code=404", 404, "c404"},
338         }
339
340         wantSegments := []string{
341                 `POST / "first"`,
342                 `POST /?code=301&next=302 "c301"`,
343                 `GET /?code=302 ""`,
344                 `GET / ""`,
345                 `POST /?code=302&next=302 "c302"`,
346                 `GET /?code=302 ""`,
347                 `GET / ""`,
348                 `POST /?code=303&next=301 "c303wc301"`,
349                 `GET /?code=301 ""`,
350                 `GET / ""`,
351                 `POST /?code=304 "c304"`,
352                 `POST /?code=305 "c305"`,
353                 `POST /?code=307&next=303,308,302 "c307"`,
354                 `POST /?code=303&next=308,302 "c307"`,
355                 `GET /?code=308&next=302 ""`,
356                 `GET /?code=302 "c307"`,
357                 `GET / ""`,
358                 `POST /?code=308&next=302,301 "c308"`,
359                 `POST /?code=302&next=301 "c308"`,
360                 `GET /?code=301 ""`,
361                 `GET / ""`,
362                 `POST /?code=404 "c404"`,
363         }
364         want := strings.Join(wantSegments, "\n")
365         run(t, func(t *testing.T, mode testMode) {
366                 testRedirectsByMethod(t, mode, "POST", postRedirectTests, want)
367         })
368 }
369
370 func TestDeleteRedirects(t *testing.T) {
371         deleteRedirectTests := []redirectTest{
372                 {"/", 200, "first"},
373                 {"/?code=301&next=302,308", 200, "c301"},
374                 {"/?code=302&next=302", 200, "c302"},
375                 {"/?code=303", 200, "c303"},
376                 {"/?code=307&next=301,308,303,302,304", 304, "c307"},
377                 {"/?code=308&next=307", 200, "c308"},
378                 {"/?code=404", 404, "c404"},
379         }
380
381         wantSegments := []string{
382                 `DELETE / "first"`,
383                 `DELETE /?code=301&next=302,308 "c301"`,
384                 `GET /?code=302&next=308 ""`,
385                 `GET /?code=308 ""`,
386                 `GET / "c301"`,
387                 `DELETE /?code=302&next=302 "c302"`,
388                 `GET /?code=302 ""`,
389                 `GET / ""`,
390                 `DELETE /?code=303 "c303"`,
391                 `GET / ""`,
392                 `DELETE /?code=307&next=301,308,303,302,304 "c307"`,
393                 `DELETE /?code=301&next=308,303,302,304 "c307"`,
394                 `GET /?code=308&next=303,302,304 ""`,
395                 `GET /?code=303&next=302,304 "c307"`,
396                 `GET /?code=302&next=304 ""`,
397                 `GET /?code=304 ""`,
398                 `DELETE /?code=308&next=307 "c308"`,
399                 `DELETE /?code=307 "c308"`,
400                 `DELETE / "c308"`,
401                 `DELETE /?code=404 "c404"`,
402         }
403         want := strings.Join(wantSegments, "\n")
404         run(t, func(t *testing.T, mode testMode) {
405                 testRedirectsByMethod(t, mode, "DELETE", deleteRedirectTests, want)
406         })
407 }
408
409 func testRedirectsByMethod(t *testing.T, mode testMode, method string, table []redirectTest, want string) {
410         var log struct {
411                 sync.Mutex
412                 bytes.Buffer
413         }
414         var ts *httptest.Server
415         ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
416                 log.Lock()
417                 slurp, _ := io.ReadAll(r.Body)
418                 fmt.Fprintf(&log.Buffer, "%s %s %q", r.Method, r.RequestURI, slurp)
419                 if cl := r.Header.Get("Content-Length"); r.Method == "GET" && len(slurp) == 0 && (r.ContentLength != 0 || cl != "") {
420                         fmt.Fprintf(&log.Buffer, " (but with body=%T, content-length = %v, %q)", r.Body, r.ContentLength, cl)
421                 }
422                 log.WriteByte('\n')
423                 log.Unlock()
424                 urlQuery := r.URL.Query()
425                 if v := urlQuery.Get("code"); v != "" {
426                         location := ts.URL
427                         if final := urlQuery.Get("next"); final != "" {
428                                 first, rest, _ := strings.Cut(final, ",")
429                                 location = fmt.Sprintf("%s?code=%s", location, first)
430                                 if rest != "" {
431                                         location = fmt.Sprintf("%s&next=%s", location, rest)
432                                 }
433                         }
434                         code, _ := strconv.Atoi(v)
435                         if code/100 == 3 {
436                                 w.Header().Set("Location", location)
437                         }
438                         w.WriteHeader(code)
439                 }
440         })).ts
441
442         c := ts.Client()
443         for _, tt := range table {
444                 content := tt.redirectBody
445                 req, _ := NewRequest(method, ts.URL+tt.suffix, strings.NewReader(content))
446                 req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(content)), nil }
447                 res, err := c.Do(req)
448
449                 if err != nil {
450                         t.Fatal(err)
451                 }
452                 if res.StatusCode != tt.want {
453                         t.Errorf("POST %s: status code = %d; want %d", tt.suffix, res.StatusCode, tt.want)
454                 }
455         }
456         log.Lock()
457         got := log.String()
458         log.Unlock()
459
460         got = strings.TrimSpace(got)
461         want = strings.TrimSpace(want)
462
463         if got != want {
464                 got, want, lines := removeCommonLines(got, want)
465                 t.Errorf("Log differs after %d common lines.\n\nGot:\n%s\n\nWant:\n%s\n", lines, got, want)
466         }
467 }
468
469 func removeCommonLines(a, b string) (asuffix, bsuffix string, commonLines int) {
470         for {
471                 nl := strings.IndexByte(a, '\n')
472                 if nl < 0 {
473                         return a, b, commonLines
474                 }
475                 line := a[:nl+1]
476                 if !strings.HasPrefix(b, line) {
477                         return a, b, commonLines
478                 }
479                 commonLines++
480                 a = a[len(line):]
481                 b = b[len(line):]
482         }
483 }
484
485 func TestClientRedirectUseResponse(t *testing.T) { run(t, testClientRedirectUseResponse) }
486 func testClientRedirectUseResponse(t *testing.T, mode testMode) {
487         const body = "Hello, world."
488         var ts *httptest.Server
489         ts = newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
490                 if strings.Contains(r.URL.Path, "/other") {
491                         io.WriteString(w, "wrong body")
492                 } else {
493                         w.Header().Set("Location", ts.URL+"/other")
494                         w.WriteHeader(StatusFound)
495                         io.WriteString(w, body)
496                 }
497         })).ts
498
499         c := ts.Client()
500         c.CheckRedirect = func(req *Request, via []*Request) error {
501                 if req.Response == nil {
502                         t.Error("expected non-nil Request.Response")
503                 }
504                 return ErrUseLastResponse
505         }
506         res, err := c.Get(ts.URL)
507         if err != nil {
508                 t.Fatal(err)
509         }
510         if res.StatusCode != StatusFound {
511                 t.Errorf("status = %d; want %d", res.StatusCode, StatusFound)
512         }
513         defer res.Body.Close()
514         slurp, err := io.ReadAll(res.Body)
515         if err != nil {
516                 t.Fatal(err)
517         }
518         if string(slurp) != body {
519                 t.Errorf("body = %q; want %q", slurp, body)
520         }
521 }
522
523 // Issues 17773 and 49281: don't follow a 3xx if the response doesn't
524 // have a Location header.
525 func TestClientRedirectNoLocation(t *testing.T) { run(t, testClientRedirectNoLocation) }
526 func testClientRedirectNoLocation(t *testing.T, mode testMode) {
527         for _, code := range []int{301, 308} {
528                 t.Run(fmt.Sprint(code), func(t *testing.T) {
529                         setParallel(t)
530                         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
531                                 w.Header().Set("Foo", "Bar")
532                                 w.WriteHeader(code)
533                         }))
534                         res, err := cst.c.Get(cst.ts.URL)
535                         if err != nil {
536                                 t.Fatal(err)
537                         }
538                         res.Body.Close()
539                         if res.StatusCode != code {
540                                 t.Errorf("status = %d; want %d", res.StatusCode, code)
541                         }
542                         if got := res.Header.Get("Foo"); got != "Bar" {
543                                 t.Errorf("Foo header = %q; want Bar", got)
544                         }
545                 })
546         }
547 }
548
549 // Don't follow a 307/308 if we can't resent the request body.
550 func TestClientRedirect308NoGetBody(t *testing.T) { run(t, testClientRedirect308NoGetBody) }
551 func testClientRedirect308NoGetBody(t *testing.T, mode testMode) {
552         const fakeURL = "https://localhost:1234/" // won't be hit
553         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
554                 w.Header().Set("Location", fakeURL)
555                 w.WriteHeader(308)
556         })).ts
557         req, err := NewRequest("POST", ts.URL, strings.NewReader("some body"))
558         if err != nil {
559                 t.Fatal(err)
560         }
561         c := ts.Client()
562         req.GetBody = nil // so it can't rewind.
563         res, err := c.Do(req)
564         if err != nil {
565                 t.Fatal(err)
566         }
567         res.Body.Close()
568         if res.StatusCode != 308 {
569                 t.Errorf("status = %d; want %d", res.StatusCode, 308)
570         }
571         if got := res.Header.Get("Location"); got != fakeURL {
572                 t.Errorf("Location header = %q; want %q", got, fakeURL)
573         }
574 }
575
576 var expectedCookies = []*Cookie{
577         {Name: "ChocolateChip", Value: "tasty"},
578         {Name: "First", Value: "Hit"},
579         {Name: "Second", Value: "Hit"},
580 }
581
582 var echoCookiesRedirectHandler = HandlerFunc(func(w ResponseWriter, r *Request) {
583         for _, cookie := range r.Cookies() {
584                 SetCookie(w, cookie)
585         }
586         if r.URL.Path == "/" {
587                 SetCookie(w, expectedCookies[1])
588                 Redirect(w, r, "/second", StatusMovedPermanently)
589         } else {
590                 SetCookie(w, expectedCookies[2])
591                 w.Write([]byte("hello"))
592         }
593 })
594
595 func TestClientSendsCookieFromJar(t *testing.T) {
596         defer afterTest(t)
597         tr := &recordingTransport{}
598         client := &Client{Transport: tr}
599         client.Jar = &TestJar{perURL: make(map[string][]*Cookie)}
600         us := "http://dummy.faketld/"
601         u, _ := url.Parse(us)
602         client.Jar.SetCookies(u, expectedCookies)
603
604         client.Get(us) // Note: doesn't hit network
605         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
606
607         client.Head(us) // Note: doesn't hit network
608         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
609
610         client.Post(us, "text/plain", strings.NewReader("body")) // Note: doesn't hit network
611         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
612
613         client.PostForm(us, url.Values{}) // Note: doesn't hit network
614         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
615
616         req, _ := NewRequest("GET", us, nil)
617         client.Do(req) // Note: doesn't hit network
618         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
619
620         req, _ = NewRequest("POST", us, nil)
621         client.Do(req) // Note: doesn't hit network
622         matchReturnedCookies(t, expectedCookies, tr.req.Cookies())
623 }
624
625 // Just enough correctness for our redirect tests. Uses the URL.Host as the
626 // scope of all cookies.
627 type TestJar struct {
628         m      sync.Mutex
629         perURL map[string][]*Cookie
630 }
631
632 func (j *TestJar) SetCookies(u *url.URL, cookies []*Cookie) {
633         j.m.Lock()
634         defer j.m.Unlock()
635         if j.perURL == nil {
636                 j.perURL = make(map[string][]*Cookie)
637         }
638         j.perURL[u.Host] = cookies
639 }
640
641 func (j *TestJar) Cookies(u *url.URL) []*Cookie {
642         j.m.Lock()
643         defer j.m.Unlock()
644         return j.perURL[u.Host]
645 }
646
647 func TestRedirectCookiesJar(t *testing.T) { run(t, testRedirectCookiesJar) }
648 func testRedirectCookiesJar(t *testing.T, mode testMode) {
649         var ts *httptest.Server
650         ts = newClientServerTest(t, mode, echoCookiesRedirectHandler).ts
651         c := ts.Client()
652         c.Jar = new(TestJar)
653         u, _ := url.Parse(ts.URL)
654         c.Jar.SetCookies(u, []*Cookie{expectedCookies[0]})
655         resp, err := c.Get(ts.URL)
656         if err != nil {
657                 t.Fatalf("Get: %v", err)
658         }
659         resp.Body.Close()
660         matchReturnedCookies(t, expectedCookies, resp.Cookies())
661 }
662
663 func matchReturnedCookies(t *testing.T, expected, given []*Cookie) {
664         if len(given) != len(expected) {
665                 t.Logf("Received cookies: %v", given)
666                 t.Errorf("Expected %d cookies, got %d", len(expected), len(given))
667         }
668         for _, ec := range expected {
669                 foundC := false
670                 for _, c := range given {
671                         if ec.Name == c.Name && ec.Value == c.Value {
672                                 foundC = true
673                                 break
674                         }
675                 }
676                 if !foundC {
677                         t.Errorf("Missing cookie %v", ec)
678                 }
679         }
680 }
681
682 func TestJarCalls(t *testing.T) { run(t, testJarCalls, []testMode{http1Mode}) }
683 func testJarCalls(t *testing.T, mode testMode) {
684         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
685                 pathSuffix := r.RequestURI[1:]
686                 if r.RequestURI == "/nosetcookie" {
687                         return // don't set cookies for this path
688                 }
689                 SetCookie(w, &Cookie{Name: "name" + pathSuffix, Value: "val" + pathSuffix})
690                 if r.RequestURI == "/" {
691                         Redirect(w, r, "http://secondhost.fake/secondpath", 302)
692                 }
693         })).ts
694         jar := new(RecordingJar)
695         c := ts.Client()
696         c.Jar = jar
697         c.Transport.(*Transport).Dial = func(_ string, _ string) (net.Conn, error) {
698                 return net.Dial("tcp", ts.Listener.Addr().String())
699         }
700         _, err := c.Get("http://firsthost.fake/")
701         if err != nil {
702                 t.Fatal(err)
703         }
704         _, err = c.Get("http://firsthost.fake/nosetcookie")
705         if err != nil {
706                 t.Fatal(err)
707         }
708         got := jar.log.String()
709         want := `Cookies("http://firsthost.fake/")
710 SetCookie("http://firsthost.fake/", [name=val])
711 Cookies("http://secondhost.fake/secondpath")
712 SetCookie("http://secondhost.fake/secondpath", [namesecondpath=valsecondpath])
713 Cookies("http://firsthost.fake/nosetcookie")
714 `
715         if got != want {
716                 t.Errorf("Got Jar calls:\n%s\nWant:\n%s", got, want)
717         }
718 }
719
720 // RecordingJar keeps a log of calls made to it, without
721 // tracking any cookies.
722 type RecordingJar struct {
723         mu  sync.Mutex
724         log bytes.Buffer
725 }
726
727 func (j *RecordingJar) SetCookies(u *url.URL, cookies []*Cookie) {
728         j.logf("SetCookie(%q, %v)\n", u, cookies)
729 }
730
731 func (j *RecordingJar) Cookies(u *url.URL) []*Cookie {
732         j.logf("Cookies(%q)\n", u)
733         return nil
734 }
735
736 func (j *RecordingJar) logf(format string, args ...any) {
737         j.mu.Lock()
738         defer j.mu.Unlock()
739         fmt.Fprintf(&j.log, format, args...)
740 }
741
742 func TestStreamingGet(t *testing.T) { run(t, testStreamingGet) }
743 func testStreamingGet(t *testing.T, mode testMode) {
744         say := make(chan string)
745         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
746                 w.(Flusher).Flush()
747                 for str := range say {
748                         w.Write([]byte(str))
749                         w.(Flusher).Flush()
750                 }
751         }))
752
753         c := cst.c
754         res, err := c.Get(cst.ts.URL)
755         if err != nil {
756                 t.Fatal(err)
757         }
758         var buf [10]byte
759         for _, str := range []string{"i", "am", "also", "known", "as", "comet"} {
760                 say <- str
761                 n, err := io.ReadFull(res.Body, buf[0:len(str)])
762                 if err != nil {
763                         t.Fatalf("ReadFull on %q: %v", str, err)
764                 }
765                 if n != len(str) {
766                         t.Fatalf("Receiving %q, only read %d bytes", str, n)
767                 }
768                 got := string(buf[0:n])
769                 if got != str {
770                         t.Fatalf("Expected %q, got %q", str, got)
771                 }
772         }
773         close(say)
774         _, err = io.ReadFull(res.Body, buf[0:1])
775         if err != io.EOF {
776                 t.Fatalf("at end expected EOF, got %v", err)
777         }
778 }
779
780 type writeCountingConn struct {
781         net.Conn
782         count *int
783 }
784
785 func (c *writeCountingConn) Write(p []byte) (int, error) {
786         *c.count++
787         return c.Conn.Write(p)
788 }
789
790 // TestClientWrites verifies that client requests are buffered and we
791 // don't send a TCP packet per line of the http request + body.
792 func TestClientWrites(t *testing.T) { run(t, testClientWrites, []testMode{http1Mode}) }
793 func testClientWrites(t *testing.T, mode testMode) {
794         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
795         })).ts
796
797         writes := 0
798         dialer := func(netz string, addr string) (net.Conn, error) {
799                 c, err := net.Dial(netz, addr)
800                 if err == nil {
801                         c = &writeCountingConn{c, &writes}
802                 }
803                 return c, err
804         }
805         c := ts.Client()
806         c.Transport.(*Transport).Dial = dialer
807
808         _, err := c.Get(ts.URL)
809         if err != nil {
810                 t.Fatal(err)
811         }
812         if writes != 1 {
813                 t.Errorf("Get request did %d Write calls, want 1", writes)
814         }
815
816         writes = 0
817         _, err = c.PostForm(ts.URL, url.Values{"foo": {"bar"}})
818         if err != nil {
819                 t.Fatal(err)
820         }
821         if writes != 1 {
822                 t.Errorf("Post request did %d Write calls, want 1", writes)
823         }
824 }
825
826 func TestClientInsecureTransport(t *testing.T) {
827         run(t, testClientInsecureTransport, []testMode{https1Mode, http2Mode})
828 }
829 func testClientInsecureTransport(t *testing.T, mode testMode) {
830         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
831                 w.Write([]byte("Hello"))
832         })).ts
833         errc := make(chanWriter, 10) // but only expecting 1
834         ts.Config.ErrorLog = log.New(errc, "", 0)
835         defer ts.Close()
836
837         // TODO(bradfitz): add tests for skipping hostname checks too?
838         // would require a new cert for testing, and probably
839         // redundant with these tests.
840         c := ts.Client()
841         for _, insecure := range []bool{true, false} {
842                 c.Transport.(*Transport).TLSClientConfig = &tls.Config{
843                         InsecureSkipVerify: insecure,
844                 }
845                 res, err := c.Get(ts.URL)
846                 if (err == nil) != insecure {
847                         t.Errorf("insecure=%v: got unexpected err=%v", insecure, err)
848                 }
849                 if res != nil {
850                         res.Body.Close()
851                 }
852         }
853
854         select {
855         case v := <-errc:
856                 if !strings.Contains(v, "TLS handshake error") {
857                         t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
858                 }
859         case <-time.After(5 * time.Second):
860                 t.Errorf("timeout waiting for logged error")
861         }
862
863 }
864
865 func TestClientErrorWithRequestURI(t *testing.T) {
866         defer afterTest(t)
867         req, _ := NewRequest("GET", "http://localhost:1234/", nil)
868         req.RequestURI = "/this/field/is/illegal/and/should/error/"
869         _, err := DefaultClient.Do(req)
870         if err == nil {
871                 t.Fatalf("expected an error")
872         }
873         if !strings.Contains(err.Error(), "RequestURI") {
874                 t.Errorf("wanted error mentioning RequestURI; got error: %v", err)
875         }
876 }
877
878 func TestClientWithCorrectTLSServerName(t *testing.T) {
879         run(t, testClientWithCorrectTLSServerName, []testMode{https1Mode, http2Mode})
880 }
881 func testClientWithCorrectTLSServerName(t *testing.T, mode testMode) {
882         const serverName = "example.com"
883         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
884                 if r.TLS.ServerName != serverName {
885                         t.Errorf("expected client to set ServerName %q, got: %q", serverName, r.TLS.ServerName)
886                 }
887         })).ts
888
889         c := ts.Client()
890         c.Transport.(*Transport).TLSClientConfig.ServerName = serverName
891         if _, err := c.Get(ts.URL); err != nil {
892                 t.Fatalf("expected successful TLS connection, got error: %v", err)
893         }
894 }
895
896 func TestClientWithIncorrectTLSServerName(t *testing.T) {
897         run(t, testClientWithIncorrectTLSServerName, []testMode{https1Mode, http2Mode})
898 }
899 func testClientWithIncorrectTLSServerName(t *testing.T, mode testMode) {
900         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {})).ts
901         errc := make(chanWriter, 10) // but only expecting 1
902         ts.Config.ErrorLog = log.New(errc, "", 0)
903
904         c := ts.Client()
905         c.Transport.(*Transport).TLSClientConfig.ServerName = "badserver"
906         _, err := c.Get(ts.URL)
907         if err == nil {
908                 t.Fatalf("expected an error")
909         }
910         if !strings.Contains(err.Error(), "127.0.0.1") || !strings.Contains(err.Error(), "badserver") {
911                 t.Errorf("wanted error mentioning 127.0.0.1 and badserver; got error: %v", err)
912         }
913         select {
914         case v := <-errc:
915                 if !strings.Contains(v, "TLS handshake error") {
916                         t.Errorf("expected an error log message containing 'TLS handshake error'; got %q", v)
917                 }
918         case <-time.After(5 * time.Second):
919                 t.Errorf("timeout waiting for logged error")
920         }
921 }
922
923 // Test for golang.org/issue/5829; the Transport should respect TLSClientConfig.ServerName
924 // when not empty.
925 //
926 // tls.Config.ServerName (non-empty, set to "example.com") takes
927 // precedence over "some-other-host.tld" which previously incorrectly
928 // took precedence. We don't actually connect to (or even resolve)
929 // "some-other-host.tld", though, because of the Transport.Dial hook.
930 //
931 // The httptest.Server has a cert with "example.com" as its name.
932 func TestTransportUsesTLSConfigServerName(t *testing.T) {
933         run(t, testTransportUsesTLSConfigServerName, []testMode{https1Mode, http2Mode})
934 }
935 func testTransportUsesTLSConfigServerName(t *testing.T, mode testMode) {
936         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
937                 w.Write([]byte("Hello"))
938         })).ts
939
940         c := ts.Client()
941         tr := c.Transport.(*Transport)
942         tr.TLSClientConfig.ServerName = "example.com" // one of httptest's Server cert names
943         tr.Dial = func(netw, addr string) (net.Conn, error) {
944                 return net.Dial(netw, ts.Listener.Addr().String())
945         }
946         res, err := c.Get("https://some-other-host.tld/")
947         if err != nil {
948                 t.Fatal(err)
949         }
950         res.Body.Close()
951 }
952
953 func TestResponseSetsTLSConnectionState(t *testing.T) {
954         run(t, testResponseSetsTLSConnectionState, []testMode{https1Mode})
955 }
956 func testResponseSetsTLSConnectionState(t *testing.T, mode testMode) {
957         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
958                 w.Write([]byte("Hello"))
959         })).ts
960
961         c := ts.Client()
962         tr := c.Transport.(*Transport)
963         tr.TLSClientConfig.CipherSuites = []uint16{tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA}
964         tr.TLSClientConfig.MaxVersion = tls.VersionTLS12 // to get to pick the cipher suite
965         tr.Dial = func(netw, addr string) (net.Conn, error) {
966                 return net.Dial(netw, ts.Listener.Addr().String())
967         }
968         res, err := c.Get("https://example.com/")
969         if err != nil {
970                 t.Fatal(err)
971         }
972         defer res.Body.Close()
973         if res.TLS == nil {
974                 t.Fatal("Response didn't set TLS Connection State.")
975         }
976         if got, want := res.TLS.CipherSuite, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA; got != want {
977                 t.Errorf("TLS Cipher Suite = %d; want %d", got, want)
978         }
979 }
980
981 // Check that an HTTPS client can interpret a particular TLS error
982 // to determine that the server is speaking HTTP.
983 // See golang.org/issue/11111.
984 func TestHTTPSClientDetectsHTTPServer(t *testing.T) {
985         run(t, testHTTPSClientDetectsHTTPServer, []testMode{http1Mode})
986 }
987 func testHTTPSClientDetectsHTTPServer(t *testing.T, mode testMode) {
988         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {})).ts
989         ts.Config.ErrorLog = quietLog
990
991         _, err := Get(strings.Replace(ts.URL, "http", "https", 1))
992         if got := err.Error(); !strings.Contains(got, "HTTP response to HTTPS client") {
993                 t.Fatalf("error = %q; want error indicating HTTP response to HTTPS request", got)
994         }
995 }
996
997 // Verify Response.ContentLength is populated. https://golang.org/issue/4126
998 func TestClientHeadContentLength(t *testing.T) { run(t, testClientHeadContentLength) }
999 func testClientHeadContentLength(t *testing.T, mode testMode) {
1000         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1001                 if v := r.FormValue("cl"); v != "" {
1002                         w.Header().Set("Content-Length", v)
1003                 }
1004         }))
1005         tests := []struct {
1006                 suffix string
1007                 want   int64
1008         }{
1009                 {"/?cl=1234", 1234},
1010                 {"/?cl=0", 0},
1011                 {"", -1},
1012         }
1013         for _, tt := range tests {
1014                 req, _ := NewRequest("HEAD", cst.ts.URL+tt.suffix, nil)
1015                 res, err := cst.c.Do(req)
1016                 if err != nil {
1017                         t.Fatal(err)
1018                 }
1019                 if res.ContentLength != tt.want {
1020                         t.Errorf("Content-Length = %d; want %d", res.ContentLength, tt.want)
1021                 }
1022                 bs, err := io.ReadAll(res.Body)
1023                 if err != nil {
1024                         t.Fatal(err)
1025                 }
1026                 if len(bs) != 0 {
1027                         t.Errorf("Unexpected content: %q", bs)
1028                 }
1029         }
1030 }
1031
1032 func TestEmptyPasswordAuth(t *testing.T) { run(t, testEmptyPasswordAuth) }
1033 func testEmptyPasswordAuth(t *testing.T, mode testMode) {
1034         gopher := "gopher"
1035         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1036                 auth := r.Header.Get("Authorization")
1037                 if strings.HasPrefix(auth, "Basic ") {
1038                         encoded := auth[6:]
1039                         decoded, err := base64.StdEncoding.DecodeString(encoded)
1040                         if err != nil {
1041                                 t.Fatal(err)
1042                         }
1043                         expected := gopher + ":"
1044                         s := string(decoded)
1045                         if expected != s {
1046                                 t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1047                         }
1048                 } else {
1049                         t.Errorf("Invalid auth %q", auth)
1050                 }
1051         })).ts
1052         defer ts.Close()
1053         req, err := NewRequest("GET", ts.URL, nil)
1054         if err != nil {
1055                 t.Fatal(err)
1056         }
1057         req.URL.User = url.User(gopher)
1058         c := ts.Client()
1059         resp, err := c.Do(req)
1060         if err != nil {
1061                 t.Fatal(err)
1062         }
1063         defer resp.Body.Close()
1064 }
1065
1066 func TestBasicAuth(t *testing.T) {
1067         defer afterTest(t)
1068         tr := &recordingTransport{}
1069         client := &Client{Transport: tr}
1070
1071         url := "http://My%20User:My%20Pass@dummy.faketld/"
1072         expected := "My User:My Pass"
1073         client.Get(url)
1074
1075         if tr.req.Method != "GET" {
1076                 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1077         }
1078         if tr.req.URL.String() != url {
1079                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1080         }
1081         if tr.req.Header == nil {
1082                 t.Fatalf("expected non-nil request Header")
1083         }
1084         auth := tr.req.Header.Get("Authorization")
1085         if strings.HasPrefix(auth, "Basic ") {
1086                 encoded := auth[6:]
1087                 decoded, err := base64.StdEncoding.DecodeString(encoded)
1088                 if err != nil {
1089                         t.Fatal(err)
1090                 }
1091                 s := string(decoded)
1092                 if expected != s {
1093                         t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1094                 }
1095         } else {
1096                 t.Errorf("Invalid auth %q", auth)
1097         }
1098 }
1099
1100 func TestBasicAuthHeadersPreserved(t *testing.T) {
1101         defer afterTest(t)
1102         tr := &recordingTransport{}
1103         client := &Client{Transport: tr}
1104
1105         // If Authorization header is provided, username in URL should not override it
1106         url := "http://My%20User@dummy.faketld/"
1107         req, err := NewRequest("GET", url, nil)
1108         if err != nil {
1109                 t.Fatal(err)
1110         }
1111         req.SetBasicAuth("My User", "My Pass")
1112         expected := "My User:My Pass"
1113         client.Do(req)
1114
1115         if tr.req.Method != "GET" {
1116                 t.Errorf("got method %q, want %q", tr.req.Method, "GET")
1117         }
1118         if tr.req.URL.String() != url {
1119                 t.Errorf("got URL %q, want %q", tr.req.URL.String(), url)
1120         }
1121         if tr.req.Header == nil {
1122                 t.Fatalf("expected non-nil request Header")
1123         }
1124         auth := tr.req.Header.Get("Authorization")
1125         if strings.HasPrefix(auth, "Basic ") {
1126                 encoded := auth[6:]
1127                 decoded, err := base64.StdEncoding.DecodeString(encoded)
1128                 if err != nil {
1129                         t.Fatal(err)
1130                 }
1131                 s := string(decoded)
1132                 if expected != s {
1133                         t.Errorf("Invalid Authorization header. Got %q, wanted %q", s, expected)
1134                 }
1135         } else {
1136                 t.Errorf("Invalid auth %q", auth)
1137         }
1138
1139 }
1140
1141 func TestStripPasswordFromError(t *testing.T) {
1142         client := &Client{Transport: &recordingTransport{}}
1143         testCases := []struct {
1144                 desc string
1145                 in   string
1146                 out  string
1147         }{
1148                 {
1149                         desc: "Strip password from error message",
1150                         in:   "http://user:password@dummy.faketld/",
1151                         out:  `Get "http://user:***@dummy.faketld/": dummy impl`,
1152                 },
1153                 {
1154                         desc: "Don't Strip password from domain name",
1155                         in:   "http://user:password@password.faketld/",
1156                         out:  `Get "http://user:***@password.faketld/": dummy impl`,
1157                 },
1158                 {
1159                         desc: "Don't Strip password from path",
1160                         in:   "http://user:password@dummy.faketld/password",
1161                         out:  `Get "http://user:***@dummy.faketld/password": dummy impl`,
1162                 },
1163                 {
1164                         desc: "Strip escaped password",
1165                         in:   "http://user:pa%2Fssword@dummy.faketld/",
1166                         out:  `Get "http://user:***@dummy.faketld/": dummy impl`,
1167                 },
1168         }
1169         for _, tC := range testCases {
1170                 t.Run(tC.desc, func(t *testing.T) {
1171                         _, err := client.Get(tC.in)
1172                         if err.Error() != tC.out {
1173                                 t.Errorf("Unexpected output for %q: expected %q, actual %q",
1174                                         tC.in, tC.out, err.Error())
1175                         }
1176                 })
1177         }
1178 }
1179
1180 func TestClientTimeout(t *testing.T) { run(t, testClientTimeout) }
1181 func testClientTimeout(t *testing.T, mode testMode) {
1182         var (
1183                 mu           sync.Mutex
1184                 nonce        string // a unique per-request string
1185                 sawSlowNonce bool   // true if the handler saw /slow?nonce=<nonce>
1186         )
1187         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1188                 _ = r.ParseForm()
1189                 if r.URL.Path == "/" {
1190                         Redirect(w, r, "/slow?nonce="+r.Form.Get("nonce"), StatusFound)
1191                         return
1192                 }
1193                 if r.URL.Path == "/slow" {
1194                         mu.Lock()
1195                         if r.Form.Get("nonce") == nonce {
1196                                 sawSlowNonce = true
1197                         } else {
1198                                 t.Logf("mismatched nonce: received %s, want %s", r.Form.Get("nonce"), nonce)
1199                         }
1200                         mu.Unlock()
1201
1202                         w.Write([]byte("Hello"))
1203                         w.(Flusher).Flush()
1204                         <-r.Context().Done()
1205                         return
1206                 }
1207         }))
1208
1209         // Try to trigger a timeout after reading part of the response body.
1210         // The initial timeout is emprically usually long enough on a decently fast
1211         // machine, but if we undershoot we'll retry with exponentially longer
1212         // timeouts until the test either passes or times out completely.
1213         // This keeps the test reasonably fast in the typical case but allows it to
1214         // also eventually succeed on arbitrarily slow machines.
1215         timeout := 10 * time.Millisecond
1216         nextNonce := 0
1217         for ; ; timeout *= 2 {
1218                 if timeout <= 0 {
1219                         // The only way we can feasibly hit this while the test is running is if
1220                         // the request fails without actually waiting for the timeout to occur.
1221                         t.Fatalf("timeout overflow")
1222                 }
1223                 if deadline, ok := t.Deadline(); ok && !time.Now().Add(timeout).Before(deadline) {
1224                         t.Fatalf("failed to produce expected timeout before test deadline")
1225                 }
1226                 t.Logf("attempting test with timeout %v", timeout)
1227                 cst.c.Timeout = timeout
1228
1229                 mu.Lock()
1230                 nonce = fmt.Sprint(nextNonce)
1231                 nextNonce++
1232                 sawSlowNonce = false
1233                 mu.Unlock()
1234                 res, err := cst.c.Get(cst.ts.URL + "/?nonce=" + nonce)
1235                 if err != nil {
1236                         if strings.Contains(err.Error(), "Client.Timeout") {
1237                                 // Timed out before handler could respond.
1238                                 t.Logf("timeout before response received")
1239                                 continue
1240                         }
1241                         if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1242                                 testenv.SkipFlaky(t, 43120)
1243                         }
1244                         t.Fatal(err)
1245                 }
1246
1247                 mu.Lock()
1248                 ok := sawSlowNonce
1249                 mu.Unlock()
1250                 if !ok {
1251                         t.Fatal("handler never got /slow request, but client returned response")
1252                 }
1253
1254                 _, err = io.ReadAll(res.Body)
1255                 res.Body.Close()
1256
1257                 if err == nil {
1258                         t.Fatal("expected error from ReadAll")
1259                 }
1260                 ne, ok := err.(net.Error)
1261                 if !ok {
1262                         t.Errorf("error value from ReadAll was %T; expected some net.Error", err)
1263                 } else if !ne.Timeout() {
1264                         t.Errorf("net.Error.Timeout = false; want true")
1265                 }
1266                 if got := ne.Error(); !strings.Contains(got, "(Client.Timeout") {
1267                         if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1268                                 testenv.SkipFlaky(t, 43120)
1269                         }
1270                         t.Errorf("error string = %q; missing timeout substring", got)
1271                 }
1272
1273                 break
1274         }
1275 }
1276
1277 // Client.Timeout firing before getting to the body
1278 func TestClientTimeout_Headers(t *testing.T) { run(t, testClientTimeout_Headers) }
1279 func testClientTimeout_Headers(t *testing.T, mode testMode) {
1280         donec := make(chan bool, 1)
1281         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1282                 <-donec
1283         }), optQuietLog)
1284         // Note that we use a channel send here and not a close.
1285         // The race detector doesn't know that we're waiting for a timeout
1286         // and thinks that the waitgroup inside httptest.Server is added to concurrently
1287         // with us closing it. If we timed out immediately, we could close the testserver
1288         // before we entered the handler. We're not timing out immediately and there's
1289         // no way we would be done before we entered the handler, but the race detector
1290         // doesn't know this, so synchronize explicitly.
1291         defer func() { donec <- true }()
1292
1293         cst.c.Timeout = 5 * time.Millisecond
1294         res, err := cst.c.Get(cst.ts.URL)
1295         if err == nil {
1296                 res.Body.Close()
1297                 t.Fatal("got response from Get; expected error")
1298         }
1299         if _, ok := err.(*url.Error); !ok {
1300                 t.Fatalf("Got error of type %T; want *url.Error", err)
1301         }
1302         ne, ok := err.(net.Error)
1303         if !ok {
1304                 t.Fatalf("Got error of type %T; want some net.Error", err)
1305         }
1306         if !ne.Timeout() {
1307                 t.Error("net.Error.Timeout = false; want true")
1308         }
1309         if got := ne.Error(); !strings.Contains(got, "Client.Timeout exceeded") {
1310                 if runtime.GOOS == "windows" && strings.HasPrefix(runtime.GOARCH, "arm") {
1311                         testenv.SkipFlaky(t, 43120)
1312                 }
1313                 t.Errorf("error string = %q; missing timeout substring", got)
1314         }
1315 }
1316
1317 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
1318 // returned.
1319 func TestClientTimeoutCancel(t *testing.T) { run(t, testClientTimeoutCancel) }
1320 func testClientTimeoutCancel(t *testing.T, mode testMode) {
1321         testDone := make(chan struct{})
1322         ctx, cancel := context.WithCancel(context.Background())
1323
1324         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1325                 w.(Flusher).Flush()
1326                 <-testDone
1327         }))
1328         defer close(testDone)
1329
1330         cst.c.Timeout = 1 * time.Hour
1331         req, _ := NewRequest("GET", cst.ts.URL, nil)
1332         req.Cancel = ctx.Done()
1333         res, err := cst.c.Do(req)
1334         if err != nil {
1335                 t.Fatal(err)
1336         }
1337         cancel()
1338         _, err = io.Copy(io.Discard, res.Body)
1339         if err != ExportErrRequestCanceled {
1340                 t.Fatalf("error = %v; want errRequestCanceled", err)
1341         }
1342 }
1343
1344 // Issue 49366: if Client.Timeout is set but not hit, no error should be returned.
1345 func TestClientTimeoutDoesNotExpire(t *testing.T) { run(t, testClientTimeoutDoesNotExpire) }
1346 func testClientTimeoutDoesNotExpire(t *testing.T, mode testMode) {
1347         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1348                 w.Write([]byte("body"))
1349         }))
1350
1351         cst.c.Timeout = 1 * time.Hour
1352         req, _ := NewRequest("GET", cst.ts.URL, nil)
1353         res, err := cst.c.Do(req)
1354         if err != nil {
1355                 t.Fatal(err)
1356         }
1357         if _, err = io.Copy(io.Discard, res.Body); err != nil {
1358                 t.Fatalf("io.Copy(io.Discard, res.Body) = %v, want nil", err)
1359         }
1360         if err = res.Body.Close(); err != nil {
1361                 t.Fatalf("res.Body.Close() = %v, want nil", err)
1362         }
1363 }
1364
1365 func TestClientRedirectEatsBody_h1(t *testing.T) { run(t, testClientRedirectEatsBody) }
1366 func testClientRedirectEatsBody(t *testing.T, mode testMode) {
1367         saw := make(chan string, 2)
1368         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1369                 saw <- r.RemoteAddr
1370                 if r.URL.Path == "/" {
1371                         Redirect(w, r, "/foo", StatusFound) // which includes a body
1372                 }
1373         }))
1374
1375         res, err := cst.c.Get(cst.ts.URL)
1376         if err != nil {
1377                 t.Fatal(err)
1378         }
1379         _, err = io.ReadAll(res.Body)
1380         res.Body.Close()
1381         if err != nil {
1382                 t.Fatal(err)
1383         }
1384
1385         var first string
1386         select {
1387         case first = <-saw:
1388         default:
1389                 t.Fatal("server didn't see a request")
1390         }
1391
1392         var second string
1393         select {
1394         case second = <-saw:
1395         default:
1396                 t.Fatal("server didn't see a second request")
1397         }
1398
1399         if first != second {
1400                 t.Fatal("server saw different client ports before & after the redirect")
1401         }
1402 }
1403
1404 // eofReaderFunc is an io.Reader that runs itself, and then returns io.EOF.
1405 type eofReaderFunc func()
1406
1407 func (f eofReaderFunc) Read(p []byte) (n int, err error) {
1408         f()
1409         return 0, io.EOF
1410 }
1411
1412 func TestReferer(t *testing.T) {
1413         tests := []struct {
1414                 lastReq, newReq string // from -> to URLs
1415                 want            string
1416         }{
1417                 // don't send user:
1418                 {"http://gopher@test.com", "http://link.com", "http://test.com"},
1419                 {"https://gopher@test.com", "https://link.com", "https://test.com"},
1420
1421                 // don't send a user and password:
1422                 {"http://gopher:go@test.com", "http://link.com", "http://test.com"},
1423                 {"https://gopher:go@test.com", "https://link.com", "https://test.com"},
1424
1425                 // nothing to do:
1426                 {"http://test.com", "http://link.com", "http://test.com"},
1427                 {"https://test.com", "https://link.com", "https://test.com"},
1428
1429                 // https to http doesn't send a referer:
1430                 {"https://test.com", "http://link.com", ""},
1431                 {"https://gopher:go@test.com", "http://link.com", ""},
1432         }
1433         for _, tt := range tests {
1434                 l, err := url.Parse(tt.lastReq)
1435                 if err != nil {
1436                         t.Fatal(err)
1437                 }
1438                 n, err := url.Parse(tt.newReq)
1439                 if err != nil {
1440                         t.Fatal(err)
1441                 }
1442                 r := ExportRefererForURL(l, n)
1443                 if r != tt.want {
1444                         t.Errorf("refererForURL(%q, %q) = %q; want %q", tt.lastReq, tt.newReq, r, tt.want)
1445                 }
1446         }
1447 }
1448
1449 // issue15577Tripper returns a Response with a redirect response
1450 // header and doesn't populate its Response.Request field.
1451 type issue15577Tripper struct{}
1452
1453 func (issue15577Tripper) RoundTrip(*Request) (*Response, error) {
1454         resp := &Response{
1455                 StatusCode: 303,
1456                 Header:     map[string][]string{"Location": {"http://www.example.com/"}},
1457                 Body:       io.NopCloser(strings.NewReader("")),
1458         }
1459         return resp, nil
1460 }
1461
1462 // Issue 15577: don't assume the roundtripper's response populates its Request field.
1463 func TestClientRedirectResponseWithoutRequest(t *testing.T) {
1464         c := &Client{
1465                 CheckRedirect: func(*Request, []*Request) error { return fmt.Errorf("no redirects!") },
1466                 Transport:     issue15577Tripper{},
1467         }
1468         // Check that this doesn't crash:
1469         c.Get("http://dummy.tld")
1470 }
1471
1472 // Issue 4800: copy (some) headers when Client follows a redirect.
1473 // Issue 35104: Since both URLs have the same host (localhost)
1474 // but different ports, sensitive headers like Cookie and Authorization
1475 // are preserved.
1476 func TestClientCopyHeadersOnRedirect(t *testing.T) { run(t, testClientCopyHeadersOnRedirect) }
1477 func testClientCopyHeadersOnRedirect(t *testing.T, mode testMode) {
1478         const (
1479                 ua   = "some-agent/1.2"
1480                 xfoo = "foo-val"
1481         )
1482         var ts2URL string
1483         ts1 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1484                 want := Header{
1485                         "User-Agent":      []string{ua},
1486                         "X-Foo":           []string{xfoo},
1487                         "Referer":         []string{ts2URL},
1488                         "Accept-Encoding": []string{"gzip"},
1489                         "Cookie":          []string{"foo=bar"},
1490                         "Authorization":   []string{"secretpassword"},
1491                 }
1492                 if !reflect.DeepEqual(r.Header, want) {
1493                         t.Errorf("Request.Header = %#v; want %#v", r.Header, want)
1494                 }
1495                 if t.Failed() {
1496                         w.Header().Set("Result", "got errors")
1497                 } else {
1498                         w.Header().Set("Result", "ok")
1499                 }
1500         })).ts
1501         ts2 := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1502                 Redirect(w, r, ts1.URL, StatusFound)
1503         })).ts
1504         ts2URL = ts2.URL
1505
1506         c := ts1.Client()
1507         c.CheckRedirect = func(r *Request, via []*Request) error {
1508                 want := Header{
1509                         "User-Agent":    []string{ua},
1510                         "X-Foo":         []string{xfoo},
1511                         "Referer":       []string{ts2URL},
1512                         "Cookie":        []string{"foo=bar"},
1513                         "Authorization": []string{"secretpassword"},
1514                 }
1515                 if !reflect.DeepEqual(r.Header, want) {
1516                         t.Errorf("CheckRedirect Request.Header = %#v; want %#v", r.Header, want)
1517                 }
1518                 return nil
1519         }
1520
1521         req, _ := NewRequest("GET", ts2.URL, nil)
1522         req.Header.Add("User-Agent", ua)
1523         req.Header.Add("X-Foo", xfoo)
1524         req.Header.Add("Cookie", "foo=bar")
1525         req.Header.Add("Authorization", "secretpassword")
1526         res, err := c.Do(req)
1527         if err != nil {
1528                 t.Fatal(err)
1529         }
1530         defer res.Body.Close()
1531         if res.StatusCode != 200 {
1532                 t.Fatal(res.Status)
1533         }
1534         if got := res.Header.Get("Result"); got != "ok" {
1535                 t.Errorf("result = %q; want ok", got)
1536         }
1537 }
1538
1539 // Issue 22233: copy host when Client follows a relative redirect.
1540 func TestClientCopyHostOnRedirect(t *testing.T) { run(t, testClientCopyHostOnRedirect) }
1541 func testClientCopyHostOnRedirect(t *testing.T, mode testMode) {
1542         // Virtual hostname: should not receive any request.
1543         virtual := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1544                 t.Errorf("Virtual host received request %v", r.URL)
1545                 w.WriteHeader(403)
1546                 io.WriteString(w, "should not see this response")
1547         })).ts
1548         defer virtual.Close()
1549         virtualHost := strings.TrimPrefix(virtual.URL, "http://")
1550         virtualHost = strings.TrimPrefix(virtualHost, "https://")
1551         t.Logf("Virtual host is %v", virtualHost)
1552
1553         // Actual hostname: should not receive any request.
1554         const wantBody = "response body"
1555         var tsURL string
1556         var tsHost string
1557         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1558                 switch r.URL.Path {
1559                 case "/":
1560                         // Relative redirect.
1561                         if r.Host != virtualHost {
1562                                 t.Errorf("Serving /: Request.Host = %#v; want %#v", r.Host, virtualHost)
1563                                 w.WriteHeader(404)
1564                                 return
1565                         }
1566                         w.Header().Set("Location", "/hop")
1567                         w.WriteHeader(302)
1568                 case "/hop":
1569                         // Absolute redirect.
1570                         if r.Host != virtualHost {
1571                                 t.Errorf("Serving /hop: Request.Host = %#v; want %#v", r.Host, virtualHost)
1572                                 w.WriteHeader(404)
1573                                 return
1574                         }
1575                         w.Header().Set("Location", tsURL+"/final")
1576                         w.WriteHeader(302)
1577                 case "/final":
1578                         if r.Host != tsHost {
1579                                 t.Errorf("Serving /final: Request.Host = %#v; want %#v", r.Host, tsHost)
1580                                 w.WriteHeader(404)
1581                                 return
1582                         }
1583                         w.WriteHeader(200)
1584                         io.WriteString(w, wantBody)
1585                 default:
1586                         t.Errorf("Serving unexpected path %q", r.URL.Path)
1587                         w.WriteHeader(404)
1588                 }
1589         })).ts
1590         tsURL = ts.URL
1591         tsHost = strings.TrimPrefix(ts.URL, "http://")
1592         tsHost = strings.TrimPrefix(tsHost, "https://")
1593         t.Logf("Server host is %v", tsHost)
1594
1595         c := ts.Client()
1596         req, _ := NewRequest("GET", ts.URL, nil)
1597         req.Host = virtualHost
1598         resp, err := c.Do(req)
1599         if err != nil {
1600                 t.Fatal(err)
1601         }
1602         defer resp.Body.Close()
1603         if resp.StatusCode != 200 {
1604                 t.Fatal(resp.Status)
1605         }
1606         if got, err := io.ReadAll(resp.Body); err != nil || string(got) != wantBody {
1607                 t.Errorf("body = %q; want %q", got, wantBody)
1608         }
1609 }
1610
1611 // Issue 17494: cookies should be altered when Client follows redirects.
1612 func TestClientAltersCookiesOnRedirect(t *testing.T) { run(t, testClientAltersCookiesOnRedirect) }
1613 func testClientAltersCookiesOnRedirect(t *testing.T, mode testMode) {
1614         cookieMap := func(cs []*Cookie) map[string][]string {
1615                 m := make(map[string][]string)
1616                 for _, c := range cs {
1617                         m[c.Name] = append(m[c.Name], c.Value)
1618                 }
1619                 return m
1620         }
1621
1622         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1623                 var want map[string][]string
1624                 got := cookieMap(r.Cookies())
1625
1626                 c, _ := r.Cookie("Cycle")
1627                 switch c.Value {
1628                 case "0":
1629                         want = map[string][]string{
1630                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1631                                 "Cookie2": {"OldValue2"},
1632                                 "Cookie3": {"OldValue3a", "OldValue3b"},
1633                                 "Cookie4": {"OldValue4"},
1634                                 "Cycle":   {"0"},
1635                         }
1636                         SetCookie(w, &Cookie{Name: "Cycle", Value: "1", Path: "/"})
1637                         SetCookie(w, &Cookie{Name: "Cookie2", Path: "/", MaxAge: -1}) // Delete cookie from Header
1638                         Redirect(w, r, "/", StatusFound)
1639                 case "1":
1640                         want = map[string][]string{
1641                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1642                                 "Cookie3": {"OldValue3a", "OldValue3b"},
1643                                 "Cookie4": {"OldValue4"},
1644                                 "Cycle":   {"1"},
1645                         }
1646                         SetCookie(w, &Cookie{Name: "Cycle", Value: "2", Path: "/"})
1647                         SetCookie(w, &Cookie{Name: "Cookie3", Value: "NewValue3", Path: "/"}) // Modify cookie in Header
1648                         SetCookie(w, &Cookie{Name: "Cookie4", Value: "NewValue4", Path: "/"}) // Modify cookie in Jar
1649                         Redirect(w, r, "/", StatusFound)
1650                 case "2":
1651                         want = map[string][]string{
1652                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1653                                 "Cookie3": {"NewValue3"},
1654                                 "Cookie4": {"NewValue4"},
1655                                 "Cycle":   {"2"},
1656                         }
1657                         SetCookie(w, &Cookie{Name: "Cycle", Value: "3", Path: "/"})
1658                         SetCookie(w, &Cookie{Name: "Cookie5", Value: "NewValue5", Path: "/"}) // Insert cookie into Jar
1659                         Redirect(w, r, "/", StatusFound)
1660                 case "3":
1661                         want = map[string][]string{
1662                                 "Cookie1": {"OldValue1a", "OldValue1b"},
1663                                 "Cookie3": {"NewValue3"},
1664                                 "Cookie4": {"NewValue4"},
1665                                 "Cookie5": {"NewValue5"},
1666                                 "Cycle":   {"3"},
1667                         }
1668                         // Don't redirect to ensure the loop ends.
1669                 default:
1670                         t.Errorf("unexpected redirect cycle")
1671                         return
1672                 }
1673
1674                 if !reflect.DeepEqual(got, want) {
1675                         t.Errorf("redirect %s, Cookie = %v, want %v", c.Value, got, want)
1676                 }
1677         })).ts
1678
1679         jar, _ := cookiejar.New(nil)
1680         c := ts.Client()
1681         c.Jar = jar
1682
1683         u, _ := url.Parse(ts.URL)
1684         req, _ := NewRequest("GET", ts.URL, nil)
1685         req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1a"})
1686         req.AddCookie(&Cookie{Name: "Cookie1", Value: "OldValue1b"})
1687         req.AddCookie(&Cookie{Name: "Cookie2", Value: "OldValue2"})
1688         req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3a"})
1689         req.AddCookie(&Cookie{Name: "Cookie3", Value: "OldValue3b"})
1690         jar.SetCookies(u, []*Cookie{{Name: "Cookie4", Value: "OldValue4", Path: "/"}})
1691         jar.SetCookies(u, []*Cookie{{Name: "Cycle", Value: "0", Path: "/"}})
1692         res, err := c.Do(req)
1693         if err != nil {
1694                 t.Fatal(err)
1695         }
1696         defer res.Body.Close()
1697         if res.StatusCode != 200 {
1698                 t.Fatal(res.Status)
1699         }
1700 }
1701
1702 // Part of Issue 4800
1703 func TestShouldCopyHeaderOnRedirect(t *testing.T) {
1704         tests := []struct {
1705                 header     string
1706                 initialURL string
1707                 destURL    string
1708                 want       bool
1709         }{
1710                 {"User-Agent", "http://foo.com/", "http://bar.com/", true},
1711                 {"X-Foo", "http://foo.com/", "http://bar.com/", true},
1712
1713                 // Sensitive headers:
1714                 {"cookie", "http://foo.com/", "http://bar.com/", false},
1715                 {"cookie2", "http://foo.com/", "http://bar.com/", false},
1716                 {"authorization", "http://foo.com/", "http://bar.com/", false},
1717                 {"authorization", "http://foo.com/", "https://foo.com/", true},
1718                 {"authorization", "http://foo.com:1234/", "http://foo.com:4321/", true},
1719                 {"www-authenticate", "http://foo.com/", "http://bar.com/", false},
1720
1721                 // But subdomains should work:
1722                 {"www-authenticate", "http://foo.com/", "http://foo.com/", true},
1723                 {"www-authenticate", "http://foo.com/", "http://sub.foo.com/", true},
1724                 {"www-authenticate", "http://foo.com/", "http://notfoo.com/", false},
1725                 {"www-authenticate", "http://foo.com/", "https://foo.com/", true},
1726                 {"www-authenticate", "http://foo.com:80/", "http://foo.com/", true},
1727                 {"www-authenticate", "http://foo.com:80/", "http://sub.foo.com/", true},
1728                 {"www-authenticate", "http://foo.com:443/", "https://foo.com/", true},
1729                 {"www-authenticate", "http://foo.com:443/", "https://sub.foo.com/", true},
1730                 {"www-authenticate", "http://foo.com:1234/", "http://foo.com/", true},
1731
1732                 {"authorization", "http://foo.com/", "http://foo.com/", true},
1733                 {"authorization", "http://foo.com/", "http://sub.foo.com/", true},
1734                 {"authorization", "http://foo.com/", "http://notfoo.com/", false},
1735                 {"authorization", "http://foo.com/", "https://foo.com/", true},
1736                 {"authorization", "http://foo.com:80/", "http://foo.com/", true},
1737                 {"authorization", "http://foo.com:80/", "http://sub.foo.com/", true},
1738                 {"authorization", "http://foo.com:443/", "https://foo.com/", true},
1739                 {"authorization", "http://foo.com:443/", "https://sub.foo.com/", true},
1740                 {"authorization", "http://foo.com:1234/", "http://foo.com/", true},
1741         }
1742         for i, tt := range tests {
1743                 u0, err := url.Parse(tt.initialURL)
1744                 if err != nil {
1745                         t.Errorf("%d. initial URL %q parse error: %v", i, tt.initialURL, err)
1746                         continue
1747                 }
1748                 u1, err := url.Parse(tt.destURL)
1749                 if err != nil {
1750                         t.Errorf("%d. dest URL %q parse error: %v", i, tt.destURL, err)
1751                         continue
1752                 }
1753                 got := Export_shouldCopyHeaderOnRedirect(tt.header, u0, u1)
1754                 if got != tt.want {
1755                         t.Errorf("%d. shouldCopyHeaderOnRedirect(%q, %q => %q) = %v; want %v",
1756                                 i, tt.header, tt.initialURL, tt.destURL, got, tt.want)
1757                 }
1758         }
1759 }
1760
1761 func TestClientRedirectTypes(t *testing.T) { run(t, testClientRedirectTypes) }
1762 func testClientRedirectTypes(t *testing.T, mode testMode) {
1763         tests := [...]struct {
1764                 method       string
1765                 serverStatus int
1766                 wantMethod   string // desired subsequent client method
1767         }{
1768                 0: {method: "POST", serverStatus: 301, wantMethod: "GET"},
1769                 1: {method: "POST", serverStatus: 302, wantMethod: "GET"},
1770                 2: {method: "POST", serverStatus: 303, wantMethod: "GET"},
1771                 3: {method: "POST", serverStatus: 307, wantMethod: "POST"},
1772                 4: {method: "POST", serverStatus: 308, wantMethod: "POST"},
1773
1774                 5: {method: "HEAD", serverStatus: 301, wantMethod: "HEAD"},
1775                 6: {method: "HEAD", serverStatus: 302, wantMethod: "HEAD"},
1776                 7: {method: "HEAD", serverStatus: 303, wantMethod: "HEAD"},
1777                 8: {method: "HEAD", serverStatus: 307, wantMethod: "HEAD"},
1778                 9: {method: "HEAD", serverStatus: 308, wantMethod: "HEAD"},
1779
1780                 10: {method: "GET", serverStatus: 301, wantMethod: "GET"},
1781                 11: {method: "GET", serverStatus: 302, wantMethod: "GET"},
1782                 12: {method: "GET", serverStatus: 303, wantMethod: "GET"},
1783                 13: {method: "GET", serverStatus: 307, wantMethod: "GET"},
1784                 14: {method: "GET", serverStatus: 308, wantMethod: "GET"},
1785
1786                 15: {method: "DELETE", serverStatus: 301, wantMethod: "GET"},
1787                 16: {method: "DELETE", serverStatus: 302, wantMethod: "GET"},
1788                 17: {method: "DELETE", serverStatus: 303, wantMethod: "GET"},
1789                 18: {method: "DELETE", serverStatus: 307, wantMethod: "DELETE"},
1790                 19: {method: "DELETE", serverStatus: 308, wantMethod: "DELETE"},
1791
1792                 20: {method: "PUT", serverStatus: 301, wantMethod: "GET"},
1793                 21: {method: "PUT", serverStatus: 302, wantMethod: "GET"},
1794                 22: {method: "PUT", serverStatus: 303, wantMethod: "GET"},
1795                 23: {method: "PUT", serverStatus: 307, wantMethod: "PUT"},
1796                 24: {method: "PUT", serverStatus: 308, wantMethod: "PUT"},
1797
1798                 25: {method: "MADEUPMETHOD", serverStatus: 301, wantMethod: "GET"},
1799                 26: {method: "MADEUPMETHOD", serverStatus: 302, wantMethod: "GET"},
1800                 27: {method: "MADEUPMETHOD", serverStatus: 303, wantMethod: "GET"},
1801                 28: {method: "MADEUPMETHOD", serverStatus: 307, wantMethod: "MADEUPMETHOD"},
1802                 29: {method: "MADEUPMETHOD", serverStatus: 308, wantMethod: "MADEUPMETHOD"},
1803         }
1804
1805         handlerc := make(chan HandlerFunc, 1)
1806
1807         ts := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) {
1808                 h := <-handlerc
1809                 h(rw, req)
1810         })).ts
1811
1812         c := ts.Client()
1813         for i, tt := range tests {
1814                 handlerc <- func(w ResponseWriter, r *Request) {
1815                         w.Header().Set("Location", ts.URL)
1816                         w.WriteHeader(tt.serverStatus)
1817                 }
1818
1819                 req, err := NewRequest(tt.method, ts.URL, nil)
1820                 if err != nil {
1821                         t.Errorf("#%d: NewRequest: %v", i, err)
1822                         continue
1823                 }
1824
1825                 c.CheckRedirect = func(req *Request, via []*Request) error {
1826                         if got, want := req.Method, tt.wantMethod; got != want {
1827                                 return fmt.Errorf("#%d: got next method %q; want %q", i, got, want)
1828                         }
1829                         handlerc <- func(rw ResponseWriter, req *Request) {
1830                                 // TODO: Check that the body is valid when we do 307 and 308 support
1831                         }
1832                         return nil
1833                 }
1834
1835                 res, err := c.Do(req)
1836                 if err != nil {
1837                         t.Errorf("#%d: Response: %v", i, err)
1838                         continue
1839                 }
1840
1841                 res.Body.Close()
1842         }
1843 }
1844
1845 // issue18239Body is an io.ReadCloser for TestTransportBodyReadError.
1846 // Its Read returns readErr and increments *readCalls atomically.
1847 // Its Close returns nil and increments *closeCalls atomically.
1848 type issue18239Body struct {
1849         readCalls  *int32
1850         closeCalls *int32
1851         readErr    error
1852 }
1853
1854 func (b issue18239Body) Read([]byte) (int, error) {
1855         atomic.AddInt32(b.readCalls, 1)
1856         return 0, b.readErr
1857 }
1858
1859 func (b issue18239Body) Close() error {
1860         atomic.AddInt32(b.closeCalls, 1)
1861         return nil
1862 }
1863
1864 // Issue 18239: make sure the Transport doesn't retry requests with bodies
1865 // if Request.GetBody is not defined.
1866 func TestTransportBodyReadError(t *testing.T) { run(t, testTransportBodyReadError) }
1867 func testTransportBodyReadError(t *testing.T, mode testMode) {
1868         ts := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1869                 if r.URL.Path == "/ping" {
1870                         return
1871                 }
1872                 buf := make([]byte, 1)
1873                 n, err := r.Body.Read(buf)
1874                 w.Header().Set("X-Body-Read", fmt.Sprintf("%v, %v", n, err))
1875         })).ts
1876         c := ts.Client()
1877         tr := c.Transport.(*Transport)
1878
1879         // Do one initial successful request to create an idle TCP connection
1880         // for the subsequent request to reuse. (The Transport only retries
1881         // requests on reused connections.)
1882         res, err := c.Get(ts.URL + "/ping")
1883         if err != nil {
1884                 t.Fatal(err)
1885         }
1886         res.Body.Close()
1887
1888         var readCallsAtomic int32
1889         var closeCallsAtomic int32 // atomic
1890         someErr := errors.New("some body read error")
1891         body := issue18239Body{&readCallsAtomic, &closeCallsAtomic, someErr}
1892
1893         req, err := NewRequest("POST", ts.URL, body)
1894         if err != nil {
1895                 t.Fatal(err)
1896         }
1897         req = req.WithT(t)
1898         _, err = tr.RoundTrip(req)
1899         if err != someErr {
1900                 t.Errorf("Got error: %v; want Request.Body read error: %v", err, someErr)
1901         }
1902
1903         // And verify that our Body wasn't used multiple times, which
1904         // would indicate retries. (as it buggily was during part of
1905         // Go 1.8's dev cycle)
1906         readCalls := atomic.LoadInt32(&readCallsAtomic)
1907         closeCalls := atomic.LoadInt32(&closeCallsAtomic)
1908         if readCalls != 1 {
1909                 t.Errorf("read calls = %d; want 1", readCalls)
1910         }
1911         if closeCalls != 1 {
1912                 t.Errorf("close calls = %d; want 1", closeCalls)
1913         }
1914 }
1915
1916 type roundTripperWithoutCloseIdle struct{}
1917
1918 func (roundTripperWithoutCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1919
1920 type roundTripperWithCloseIdle func() // underlying func is CloseIdleConnections func
1921
1922 func (roundTripperWithCloseIdle) RoundTrip(*Request) (*Response, error) { panic("unused") }
1923 func (f roundTripperWithCloseIdle) CloseIdleConnections()               { f() }
1924
1925 func TestClientCloseIdleConnections(t *testing.T) {
1926         c := &Client{Transport: roundTripperWithoutCloseIdle{}}
1927         c.CloseIdleConnections() // verify we don't crash at least
1928
1929         closed := false
1930         var tr RoundTripper = roundTripperWithCloseIdle(func() {
1931                 closed = true
1932         })
1933         c = &Client{Transport: tr}
1934         c.CloseIdleConnections()
1935         if !closed {
1936                 t.Error("not closed")
1937         }
1938 }
1939
1940 func TestClientPropagatesTimeoutToContext(t *testing.T) {
1941         errDial := errors.New("not actually dialing")
1942         c := &Client{
1943                 Timeout: 5 * time.Second,
1944                 Transport: &Transport{
1945                         DialContext: func(ctx context.Context, netw, addr string) (net.Conn, error) {
1946                                 deadline, ok := ctx.Deadline()
1947                                 if !ok {
1948                                         t.Error("no deadline")
1949                                 } else {
1950                                         t.Logf("deadline in %v", deadline.Sub(time.Now()).Round(time.Second/10))
1951                                 }
1952                                 return nil, errDial
1953                         },
1954                 },
1955         }
1956         c.Get("https://example.tld/")
1957 }
1958
1959 // Issue 33545: lock-in the behavior promised by Client.Do's
1960 // docs about request cancellation vs timing out.
1961 func TestClientDoCanceledVsTimeout(t *testing.T) { run(t, testClientDoCanceledVsTimeout) }
1962 func testClientDoCanceledVsTimeout(t *testing.T, mode testMode) {
1963         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
1964                 w.Write([]byte("Hello, World!"))
1965         }))
1966
1967         cases := []string{"timeout", "canceled"}
1968
1969         for _, name := range cases {
1970                 t.Run(name, func(t *testing.T) {
1971                         var ctx context.Context
1972                         var cancel func()
1973                         if name == "timeout" {
1974                                 ctx, cancel = context.WithTimeout(context.Background(), -time.Nanosecond)
1975                         } else {
1976                                 ctx, cancel = context.WithCancel(context.Background())
1977                                 cancel()
1978                         }
1979                         defer cancel()
1980
1981                         req, _ := NewRequestWithContext(ctx, "GET", cst.ts.URL, nil)
1982                         _, err := cst.c.Do(req)
1983                         if err == nil {
1984                                 t.Fatal("Unexpectedly got a nil error")
1985                         }
1986
1987                         ue := err.(*url.Error)
1988
1989                         var wantIsTimeout bool
1990                         var wantErr error = context.Canceled
1991                         if name == "timeout" {
1992                                 wantErr = context.DeadlineExceeded
1993                                 wantIsTimeout = true
1994                         }
1995                         if g, w := ue.Timeout(), wantIsTimeout; g != w {
1996                                 t.Fatalf("url.Timeout() = %t, want %t", g, w)
1997                         }
1998                         if g, w := ue.Err, wantErr; g != w {
1999                                 t.Errorf("url.Error.Err = %v; want %v", g, w)
2000                         }
2001                 })
2002         }
2003 }
2004
2005 type nilBodyRoundTripper struct{}
2006
2007 func (nilBodyRoundTripper) RoundTrip(req *Request) (*Response, error) {
2008         return &Response{
2009                 StatusCode: StatusOK,
2010                 Status:     StatusText(StatusOK),
2011                 Body:       nil,
2012                 Request:    req,
2013         }, nil
2014 }
2015
2016 func TestClientPopulatesNilResponseBody(t *testing.T) {
2017         c := &Client{Transport: nilBodyRoundTripper{}}
2018
2019         resp, err := c.Get("http://localhost/anything")
2020         if err != nil {
2021                 t.Fatalf("Client.Get rejected Response with nil Body: %v", err)
2022         }
2023
2024         if resp.Body == nil {
2025                 t.Fatalf("Client failed to provide a non-nil Body as documented")
2026         }
2027         defer func() {
2028                 if err := resp.Body.Close(); err != nil {
2029                         t.Fatalf("error from Close on substitute Response.Body: %v", err)
2030                 }
2031         }()
2032
2033         if b, err := io.ReadAll(resp.Body); err != nil {
2034                 t.Errorf("read error from substitute Response.Body: %v", err)
2035         } else if len(b) != 0 {
2036                 t.Errorf("substitute Response.Body was unexpectedly non-empty: %q", b)
2037         }
2038 }
2039
2040 // Issue 40382: Client calls Close multiple times on Request.Body.
2041 func TestClientCallsCloseOnlyOnce(t *testing.T) { run(t, testClientCallsCloseOnlyOnce) }
2042 func testClientCallsCloseOnlyOnce(t *testing.T, mode testMode) {
2043         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2044                 w.WriteHeader(StatusNoContent)
2045         }))
2046
2047         // Issue occurred non-deterministically: needed to occur after a successful
2048         // write (into TCP buffer) but before end of body.
2049         for i := 0; i < 50 && !t.Failed(); i++ {
2050                 body := &issue40382Body{t: t, n: 300000}
2051                 req, err := NewRequest(MethodPost, cst.ts.URL, body)
2052                 if err != nil {
2053                         t.Fatal(err)
2054                 }
2055                 resp, err := cst.tr.RoundTrip(req)
2056                 if err != nil {
2057                         t.Fatal(err)
2058                 }
2059                 resp.Body.Close()
2060         }
2061 }
2062
2063 // issue40382Body is an io.ReadCloser for TestClientCallsCloseOnlyOnce.
2064 // Its Read reads n bytes before returning io.EOF.
2065 // Its Close returns nil but fails the test if called more than once.
2066 type issue40382Body struct {
2067         t                *testing.T
2068         n                int
2069         closeCallsAtomic int32
2070 }
2071
2072 func (b *issue40382Body) Read(p []byte) (int, error) {
2073         switch {
2074         case b.n == 0:
2075                 return 0, io.EOF
2076         case b.n < len(p):
2077                 p = p[:b.n]
2078                 fallthrough
2079         default:
2080                 for i := range p {
2081                         p[i] = 'x'
2082                 }
2083                 b.n -= len(p)
2084                 return len(p), nil
2085         }
2086 }
2087
2088 func (b *issue40382Body) Close() error {
2089         if atomic.AddInt32(&b.closeCallsAtomic, 1) == 2 {
2090                 b.t.Error("Body closed more than once")
2091         }
2092         return nil
2093 }
2094
2095 func TestProbeZeroLengthBody(t *testing.T) { run(t, testProbeZeroLengthBody) }
2096 func testProbeZeroLengthBody(t *testing.T, mode testMode) {
2097         reqc := make(chan struct{})
2098         cst := newClientServerTest(t, mode, HandlerFunc(func(w ResponseWriter, r *Request) {
2099                 close(reqc)
2100                 if _, err := io.Copy(w, r.Body); err != nil {
2101                         t.Errorf("error copying request body: %v", err)
2102                 }
2103         }))
2104
2105         bodyr, bodyw := io.Pipe()
2106         var gotBody string
2107         var wg sync.WaitGroup
2108         wg.Add(1)
2109         go func() {
2110                 defer wg.Done()
2111                 req, _ := NewRequest("GET", cst.ts.URL, bodyr)
2112                 res, err := cst.c.Do(req)
2113                 b, err := io.ReadAll(res.Body)
2114                 if err != nil {
2115                         t.Error(err)
2116                 }
2117                 gotBody = string(b)
2118         }()
2119
2120         select {
2121         case <-reqc:
2122                 // Request should be sent after trying to probe the request body for 200ms.
2123         case <-time.After(60 * time.Second):
2124                 t.Errorf("request not sent after 60s")
2125         }
2126
2127         // Write the request body and wait for the request to complete.
2128         const content = "body"
2129         bodyw.Write([]byte(content))
2130         bodyw.Close()
2131         wg.Wait()
2132         if gotBody != content {
2133                 t.Fatalf("server got body %q, want %q", gotBody, content)
2134         }
2135 }