| 367 | } |
| 368 | |
| 369 | func TestHTTPClientRedirectAuthenticationHeaderHandling(t *testing.T) { |
| 370 | // Two servers stand in for two different hosts. A dial map lets the test |
| 371 | // address them by hostname, so the auth layer compares real hostnames rather |
| 372 | // than the ephemeral ports of localhost servers, which it no longer treats as |
| 373 | // part of the host. |
| 374 | var serverRequest *http.Request |
| 375 | server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 376 | serverRequest = r |
| 377 | w.WriteHeader(http.StatusNoContent) |
| 378 | })) |
| 379 | defer server.Close() |
| 380 | |
| 381 | var redirectRequest *http.Request |
| 382 | redirectServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 383 | redirectRequest = r |
| 384 | http.Redirect(w, r, "http://canonical.example/", http.StatusFound) |
| 385 | })) |
| 386 | defer redirectServer.Close() |
| 387 | |
| 388 | hostToAddr := map[string]string{ |
| 389 | "other.example": redirectServer.Listener.Addr().String(), |
| 390 | "canonical.example": server.Listener.Addr().String(), |
| 391 | } |
| 392 | dialer := &net.Dialer{} |
| 393 | transport := &http.Transport{ |
| 394 | DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| 395 | if host, _, err := net.SplitHostPort(addr); err == nil { |
| 396 | if mapped, ok := hostToAddr[host]; ok { |
| 397 | addr = mapped |
| 398 | } |
| 399 | } |
| 400 | return dialer.DialContext(ctx, network, addr) |
| 401 | }, |
| 402 | } |
| 403 | config := tinyConfig{ |
| 404 | "other.example:oauth_token": "OTHER-TOKEN", |
| 405 | "canonical.example:oauth_token": "CANONICAL-TOKEN", |
| 406 | } |
| 407 | client := &http.Client{Transport: AddAuthTokenHeaderWithRefresh(transport, config)} |
| 408 | |
| 409 | req, err := http.NewRequest("GET", "http://other.example/", nil) |
| 410 | require.NoError(t, err) |
| 411 | |
| 412 | res, err := client.Do(req) |
| 413 | require.NoError(t, err) |
| 414 | |
| 415 | // The initial request is authenticated as its own host. |
| 416 | assert.Equal(t, "token OTHER-TOKEN", redirectRequest.Header.Get(authorization)) |
| 417 | // Following the redirect crosses to a different host, so no token is attached, |
| 418 | // even though one is configured for that host. |
| 419 | assert.Equal(t, "", serverRequest.Header.Get(authorization)) |
| 420 | assert.Equal(t, 204, res.StatusCode) |
| 421 | } |
| 422 | |
| 423 | // serverHostname returns the hostname of a test server URL, so config can be |
| 424 | // keyed by host, as production config is, rather than host:port. |