docker_cli_push_test.go 13 KB

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