github.com/ooni/oohttp@v0.7.2/client_test.go (about)

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