MCPcopy Create free account
hub / github.com/cli/cli / TestHTTPClientRedirectAuthenticationHeaderHandling

Function TestHTTPClientRedirectAuthenticationHeaderHandling

api/http_client_test.go:368–420  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls 7

AddrMethod · 0.80
EqualMethod · 0.80
CloseMethod · 0.65
StringMethod · 0.65
DoMethod · 0.65
GetMethod · 0.65

Tested by

no test coverage detected