docker_cli_push_test.go 12 KB

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