registry_unit_test.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. package distribution
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/url"
  8. "os"
  9. "runtime"
  10. "strings"
  11. "testing"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/distribution/reference"
  14. "github.com/docker/docker/api/types"
  15. registrytypes "github.com/docker/docker/api/types/registry"
  16. "github.com/docker/docker/pkg/archive"
  17. "github.com/docker/docker/pkg/stringid"
  18. "github.com/docker/docker/registry"
  19. "golang.org/x/net/context"
  20. )
  21. const secretRegistryToken = "mysecrettoken"
  22. type tokenPassThruHandler struct {
  23. reached bool
  24. gotToken bool
  25. shouldSend401 func(url string) bool
  26. }
  27. func (h *tokenPassThruHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  28. h.reached = true
  29. if strings.Contains(r.Header.Get("Authorization"), secretRegistryToken) {
  30. logrus.Debug("Detected registry token in auth header")
  31. h.gotToken = true
  32. }
  33. if h.shouldSend401 == nil || h.shouldSend401(r.RequestURI) {
  34. w.Header().Set("WWW-Authenticate", `Bearer realm="foorealm"`)
  35. w.WriteHeader(401)
  36. }
  37. }
  38. func testTokenPassThru(t *testing.T, ts *httptest.Server) {
  39. tmp, err := testDirectory("")
  40. if err != nil {
  41. t.Fatal(err)
  42. }
  43. defer os.RemoveAll(tmp)
  44. uri, err := url.Parse(ts.URL)
  45. if err != nil {
  46. t.Fatalf("could not parse url from test server: %v", err)
  47. }
  48. endpoint := registry.APIEndpoint{
  49. Mirror: false,
  50. URL: uri,
  51. Version: 2,
  52. Official: false,
  53. TrimHostname: false,
  54. TLSConfig: nil,
  55. }
  56. n, _ := reference.ParseNormalizedNamed("testremotename")
  57. repoInfo := &registry.RepositoryInfo{
  58. Name: n,
  59. Index: &registrytypes.IndexInfo{
  60. Name: "testrepo",
  61. Mirrors: nil,
  62. Secure: false,
  63. Official: false,
  64. },
  65. Official: false,
  66. }
  67. imagePullConfig := &ImagePullConfig{
  68. Config: Config{
  69. MetaHeaders: http.Header{},
  70. AuthConfig: &types.AuthConfig{
  71. RegistryToken: secretRegistryToken,
  72. },
  73. },
  74. Schema2Types: ImageTypes,
  75. }
  76. puller, err := newPuller(endpoint, repoInfo, imagePullConfig)
  77. if err != nil {
  78. t.Fatal(err)
  79. }
  80. p := puller.(*v2Puller)
  81. ctx := context.Background()
  82. p.repo, _, err = NewV2Repository(ctx, p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig, "pull")
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. logrus.Debug("About to pull")
  87. // We expect it to fail, since we haven't mock'd the full registry exchange in our handler above
  88. tag, _ := reference.WithTag(n, "tag_goes_here")
  89. _ = p.pullV2Repository(ctx, tag)
  90. }
  91. func TestTokenPassThru(t *testing.T) {
  92. handler := &tokenPassThruHandler{shouldSend401: func(url string) bool { return url == "/v2/" }}
  93. ts := httptest.NewServer(handler)
  94. defer ts.Close()
  95. testTokenPassThru(t, ts)
  96. if !handler.reached {
  97. t.Fatal("Handler not reached")
  98. }
  99. if !handler.gotToken {
  100. t.Fatal("Failed to receive registry token")
  101. }
  102. }
  103. func TestTokenPassThruDifferentHost(t *testing.T) {
  104. handler := new(tokenPassThruHandler)
  105. ts := httptest.NewServer(handler)
  106. defer ts.Close()
  107. tsredirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  108. if r.RequestURI == "/v2/" {
  109. w.Header().Set("WWW-Authenticate", `Bearer realm="foorealm"`)
  110. w.WriteHeader(401)
  111. return
  112. }
  113. http.Redirect(w, r, ts.URL+r.URL.Path, http.StatusMovedPermanently)
  114. }))
  115. defer tsredirect.Close()
  116. testTokenPassThru(t, tsredirect)
  117. if !handler.reached {
  118. t.Fatal("Handler not reached")
  119. }
  120. if handler.gotToken {
  121. t.Fatal("Redirect should not forward Authorization header to another host")
  122. }
  123. }
  124. // testDirectory creates a new temporary directory and returns its path.
  125. // The contents of directory at path `templateDir` is copied into the
  126. // new directory.
  127. func testDirectory(templateDir string) (dir string, err error) {
  128. testID := stringid.GenerateNonCryptoID()[:4]
  129. prefix := fmt.Sprintf("docker-test%s-%s-", testID, getCallerName(2))
  130. if prefix == "" {
  131. prefix = "docker-test-"
  132. }
  133. dir, err = ioutil.TempDir("", prefix)
  134. if err = os.Remove(dir); err != nil {
  135. return
  136. }
  137. if templateDir != "" {
  138. if err = archive.CopyWithTar(templateDir, dir); err != nil {
  139. return
  140. }
  141. }
  142. return
  143. }
  144. // getCallerName introspects the call stack and returns the name of the
  145. // function `depth` levels down in the stack.
  146. func getCallerName(depth int) string {
  147. // Use the caller function name as a prefix.
  148. // This helps trace temp directories back to their test.
  149. pc, _, _, _ := runtime.Caller(depth + 1)
  150. callerLongName := runtime.FuncForPC(pc).Name()
  151. parts := strings.Split(callerLongName, ".")
  152. callerShortName := parts[len(parts)-1]
  153. return callerShortName
  154. }