docker_cli_push_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package main
  2. import (
  3. "archive/tar"
  4. "context"
  5. "fmt"
  6. "net/http"
  7. "net/http/httptest"
  8. "os"
  9. "strings"
  10. "sync"
  11. "testing"
  12. "github.com/distribution/reference"
  13. "github.com/docker/docker/api/types/versions"
  14. "github.com/docker/docker/integration-cli/cli/build"
  15. "gotest.tools/v3/assert"
  16. "gotest.tools/v3/icmd"
  17. )
  18. type DockerCLIPushSuite struct {
  19. ds *DockerSuite
  20. }
  21. func (s *DockerCLIPushSuite) TearDownTest(ctx context.Context, c *testing.T) {
  22. s.ds.TearDownTest(ctx, c)
  23. }
  24. func (s *DockerCLIPushSuite) OnTimeout(c *testing.T) {
  25. s.ds.OnTimeout(c)
  26. }
  27. func (s *DockerRegistrySuite) TestPushBusyboxImage(c *testing.T) {
  28. repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  29. // tag the image to upload it to the private registry
  30. dockerCmd(c, "tag", "busybox", repoName)
  31. // push the image to the registry
  32. dockerCmd(c, "push", repoName)
  33. }
  34. // pushing an image without a prefix should throw an error
  35. func (s *DockerCLIPushSuite) TestPushUnprefixedRepo(c *testing.T) {
  36. out, _, err := dockerCmdWithError("push", "busybox")
  37. assert.ErrorContains(c, err, "", "pushing an unprefixed repo didn't result in a non-zero exit status: %s", out)
  38. }
  39. func (s *DockerRegistrySuite) TestPushUntagged(c *testing.T) {
  40. repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  41. expected := "An image does not exist locally with the tag"
  42. out, _, err := dockerCmdWithError("push", repoName)
  43. assert.ErrorContains(c, err, "", "pushing the image to the private registry should have failed: output %q", out)
  44. assert.Assert(c, strings.Contains(out, expected), "pushing the image failed")
  45. }
  46. func (s *DockerRegistrySuite) TestPushBadTag(c *testing.T) {
  47. repoName := fmt.Sprintf("%v/dockercli/busybox:latest", privateRegistryURL)
  48. expected := "does not exist"
  49. out, _, err := dockerCmdWithError("push", repoName)
  50. assert.ErrorContains(c, err, "", "pushing the image to the private registry should have failed: output %q", out)
  51. assert.Assert(c, strings.Contains(out, expected), "pushing the image failed")
  52. }
  53. func (s *DockerRegistrySuite) TestPushMultipleTags(c *testing.T) {
  54. repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  55. repoTag1 := fmt.Sprintf("%v/dockercli/busybox:t1", privateRegistryURL)
  56. repoTag2 := fmt.Sprintf("%v/dockercli/busybox:t2", privateRegistryURL)
  57. // tag the image and upload it to the private registry
  58. dockerCmd(c, "tag", "busybox", repoTag1)
  59. dockerCmd(c, "tag", "busybox", repoTag2)
  60. args := []string{"push"}
  61. if versions.GreaterThanOrEqualTo(DockerCLIVersion(c), "20.10.0") {
  62. // 20.10 CLI removed implicit push all tags and requires the "--all" flag
  63. args = append(args, "--all-tags")
  64. }
  65. args = append(args, repoName)
  66. dockerCmd(c, args...)
  67. imageAlreadyExists := ": Image already exists"
  68. // Ensure layer list is equivalent for repoTag1 and repoTag2
  69. out1, _ := dockerCmd(c, "push", repoTag1)
  70. var out1Lines []string
  71. for _, outputLine := range strings.Split(out1, "\n") {
  72. if strings.Contains(outputLine, imageAlreadyExists) {
  73. out1Lines = append(out1Lines, outputLine)
  74. }
  75. }
  76. out2, _ := dockerCmd(c, "push", repoTag2)
  77. var out2Lines []string
  78. for _, outputLine := range strings.Split(out2, "\n") {
  79. if strings.Contains(outputLine, imageAlreadyExists) {
  80. out2Lines = append(out2Lines, outputLine)
  81. }
  82. }
  83. assert.DeepEqual(c, out1Lines, out2Lines)
  84. }
  85. func (s *DockerRegistrySuite) TestPushEmptyLayer(c *testing.T) {
  86. repoName := fmt.Sprintf("%v/dockercli/emptylayer", privateRegistryURL)
  87. emptyTarball, err := os.CreateTemp("", "empty_tarball")
  88. assert.NilError(c, err, "Unable to create test file")
  89. tw := tar.NewWriter(emptyTarball)
  90. err = tw.Close()
  91. assert.NilError(c, err, "Error creating empty tarball")
  92. freader, err := os.Open(emptyTarball.Name())
  93. assert.NilError(c, err, "Could not open test tarball")
  94. defer freader.Close()
  95. icmd.RunCmd(icmd.Cmd{
  96. Command: []string{dockerBinary, "import", "-", repoName},
  97. Stdin: freader,
  98. }).Assert(c, icmd.Success)
  99. // Now verify we can push it
  100. out, _, err := dockerCmdWithError("push", repoName)
  101. assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out)
  102. }
  103. // TestConcurrentPush pushes multiple tags to the same repo
  104. // concurrently.
  105. func (s *DockerRegistrySuite) TestConcurrentPush(c *testing.T) {
  106. repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  107. var repos []string
  108. for _, tag := range []string{"push1", "push2", "push3"} {
  109. repo := fmt.Sprintf("%v:%v", repoName, tag)
  110. buildImageSuccessfully(c, repo, build.WithDockerfile(fmt.Sprintf(`
  111. FROM busybox
  112. ENTRYPOINT ["/bin/echo"]
  113. ENV FOO foo
  114. ENV BAR bar
  115. CMD echo %s
  116. `, repo)))
  117. repos = append(repos, repo)
  118. }
  119. // Push tags, in parallel
  120. results := make(chan error, len(repos))
  121. for _, repo := range repos {
  122. go func(repo string) {
  123. result := icmd.RunCommand(dockerBinary, "push", repo)
  124. results <- result.Error
  125. }(repo)
  126. }
  127. for range repos {
  128. err := <-results
  129. assert.NilError(c, err, "concurrent push failed with error: %v", err)
  130. }
  131. // Clear local images store.
  132. args := append([]string{"rmi"}, repos...)
  133. dockerCmd(c, args...)
  134. // Re-pull and run individual tags, to make sure pushes succeeded
  135. for _, repo := range repos {
  136. dockerCmd(c, "pull", repo)
  137. dockerCmd(c, "inspect", repo)
  138. out, _ := dockerCmd(c, "run", "--rm", repo)
  139. assert.Equal(c, strings.TrimSpace(out), "/bin/sh -c echo "+repo)
  140. }
  141. }
  142. func (s *DockerRegistrySuite) TestCrossRepositoryLayerPush(c *testing.T) {
  143. sourceRepoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
  144. // tag the image to upload it to the private registry
  145. dockerCmd(c, "tag", "busybox", sourceRepoName)
  146. // push the image to the registry
  147. out1, _, err := dockerCmdWithError("push", sourceRepoName)
  148. assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out1)
  149. // ensure that none of the layers were mounted from another repository during push
  150. assert.Assert(c, !strings.Contains(out1, "Mounted from"))
  151. digest1 := reference.DigestRegexp.FindString(out1)
  152. assert.Assert(c, len(digest1) > 0, "no digest found for pushed manifest")
  153. destRepoName := fmt.Sprintf("%v/dockercli/crossrepopush", privateRegistryURL)
  154. // retag the image to upload the same layers to another repo in the same registry
  155. dockerCmd(c, "tag", "busybox", destRepoName)
  156. // push the image to the registry
  157. out2, _, err := dockerCmdWithError("push", destRepoName)
  158. assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out2)
  159. // ensure that layers were mounted from the first repo during push
  160. assert.Assert(c, strings.Contains(out2, "Mounted from dockercli/busybox"))
  161. digest2 := reference.DigestRegexp.FindString(out2)
  162. assert.Assert(c, len(digest2) > 0, "no digest found for pushed manifest")
  163. assert.Equal(c, digest1, digest2)
  164. // ensure that pushing again produces the same digest
  165. out3, _, err := dockerCmdWithError("push", destRepoName)
  166. assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out3)
  167. digest3 := reference.DigestRegexp.FindString(out3)
  168. assert.Assert(c, len(digest3) > 0, "no digest found for pushed manifest")
  169. assert.Equal(c, digest3, digest2)
  170. // ensure that we can pull and run the cross-repo-pushed repository
  171. dockerCmd(c, "rmi", destRepoName)
  172. dockerCmd(c, "pull", destRepoName)
  173. out4, _ := dockerCmd(c, "run", destRepoName, "echo", "-n", "hello world")
  174. assert.Equal(c, out4, "hello world")
  175. }
  176. func (s *DockerRegistryAuthHtpasswdSuite) TestPushNoCredentialsNoRetry(c *testing.T) {
  177. repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
  178. dockerCmd(c, "tag", "busybox", repoName)
  179. out, _, err := dockerCmdWithError("push", repoName)
  180. assert.ErrorContains(c, err, "", out)
  181. assert.Assert(c, !strings.Contains(out, "Retrying"))
  182. assert.Assert(c, strings.Contains(out, "no basic auth credentials"))
  183. }
  184. // This may be flaky but it's needed not to regress on unauthorized push, see #21054
  185. func (s *DockerCLIPushSuite) TestPushToCentralRegistryUnauthorized(c *testing.T) {
  186. testRequires(c, Network)
  187. repoName := "test/busybox"
  188. dockerCmd(c, "tag", "busybox", repoName)
  189. out, _, err := dockerCmdWithError("push", repoName)
  190. assert.ErrorContains(c, err, "", out)
  191. assert.Assert(c, !strings.Contains(out, "Retrying"))
  192. }
  193. func getTestTokenService(status int, body string, retries int) *httptest.Server {
  194. var mu sync.Mutex
  195. return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  196. mu.Lock()
  197. if retries > 0 {
  198. w.Header().Set("Content-Type", "application/json")
  199. w.WriteHeader(http.StatusServiceUnavailable)
  200. w.Write([]byte(`{"errors":[{"code":"UNAVAILABLE","message":"cannot create token at this time"}]}`))
  201. retries--
  202. } else {
  203. w.Header().Set("Content-Type", "application/json")
  204. w.WriteHeader(status)
  205. w.Write([]byte(body))
  206. }
  207. mu.Unlock()
  208. }))
  209. }
  210. func (s *DockerRegistryAuthTokenSuite) TestPushTokenServiceUnauthResponse(c *testing.T) {
  211. ts := getTestTokenService(http.StatusUnauthorized, `{"errors": [{"Code":"UNAUTHORIZED", "message": "a message", "detail": null}]}`, 0)
  212. defer ts.Close()
  213. s.setupRegistryWithTokenService(c, ts.URL)
  214. repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
  215. dockerCmd(c, "tag", "busybox", repoName)
  216. out, _, err := dockerCmdWithError("push", repoName)
  217. assert.ErrorContains(c, err, "", out)
  218. assert.Assert(c, !strings.Contains(out, "Retrying"))
  219. assert.Assert(c, strings.Contains(out, "unauthorized: a message"))
  220. }
  221. func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseUnauthorized(c *testing.T) {
  222. ts := getTestTokenService(http.StatusUnauthorized, `{"error": "unauthorized"}`, 0)
  223. defer ts.Close()
  224. s.setupRegistryWithTokenService(c, ts.URL)
  225. repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
  226. dockerCmd(c, "tag", "busybox", repoName)
  227. out, _, err := dockerCmdWithError("push", repoName)
  228. assert.ErrorContains(c, err, "", out)
  229. assert.Assert(c, !strings.Contains(out, "Retrying"))
  230. split := strings.Split(out, "\n")
  231. assert.Equal(c, split[len(split)-2], "unauthorized: authentication required")
  232. }
  233. func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseError(c *testing.T) {
  234. ts := getTestTokenService(http.StatusTooManyRequests, `{"errors": [{"code":"TOOMANYREQUESTS","message":"out of tokens"}]}`, 3)
  235. defer ts.Close()
  236. s.setupRegistryWithTokenService(c, ts.URL)
  237. repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
  238. dockerCmd(c, "tag", "busybox", repoName)
  239. out, _, err := dockerCmdWithError("push", repoName)
  240. assert.ErrorContains(c, err, "", out)
  241. // TODO: isolate test so that it can be guaranteed that the 503 will trigger xfer retries
  242. // assert.Assert(c, strings.Contains(out, "Retrying"))
  243. // assert.Assert(c, !strings.Contains(out, "Retrying in 15"))
  244. split := strings.Split(out, "\n")
  245. assert.Equal(c, split[len(split)-2], "toomanyrequests: out of tokens")
  246. }
  247. func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseUnparsable(c *testing.T) {
  248. ts := getTestTokenService(http.StatusForbidden, `no way`, 0)
  249. defer ts.Close()
  250. s.setupRegistryWithTokenService(c, ts.URL)
  251. repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
  252. dockerCmd(c, "tag", "busybox", repoName)
  253. out, _, err := dockerCmdWithError("push", repoName)
  254. assert.ErrorContains(c, err, "", out)
  255. assert.Assert(c, !strings.Contains(out, "Retrying"))
  256. split := strings.Split(out, "\n")
  257. assert.Assert(c, strings.Contains(split[len(split)-2], "error parsing HTTP 403 response body: "))
  258. }
  259. func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseNoToken(c *testing.T) {
  260. ts := getTestTokenService(http.StatusOK, `{"something": "wrong"}`, 0)
  261. defer ts.Close()
  262. s.setupRegistryWithTokenService(c, ts.URL)
  263. repoName := fmt.Sprintf("%s/busybox", privateRegistryURL)
  264. dockerCmd(c, "tag", "busybox", repoName)
  265. out, _, err := dockerCmdWithError("push", repoName)
  266. assert.ErrorContains(c, err, "", out)
  267. assert.Assert(c, !strings.Contains(out, "Retrying"))
  268. split := strings.Split(out, "\n")
  269. assert.Equal(c, split[len(split)-2], "authorization server did not include a token in the response")
  270. }