docker_cli_by_digest_test.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "regexp"
  8. "strings"
  9. "testing"
  10. "github.com/docker/distribution/manifest/schema1"
  11. "github.com/docker/distribution/manifest/schema2"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/integration-cli/cli"
  14. "github.com/docker/docker/integration-cli/cli/build"
  15. "github.com/opencontainers/go-digest"
  16. "gotest.tools/v3/assert"
  17. is "gotest.tools/v3/assert/cmp"
  18. "gotest.tools/v3/skip"
  19. )
  20. const (
  21. remoteRepoName = "dockercli/busybox-by-dgst"
  22. repoName = privateRegistryURL + "/" + remoteRepoName
  23. )
  24. var (
  25. pushDigestRegex = regexp.MustCompile(`[\S]+: digest: ([\S]+) size: [0-9]+`)
  26. digestRegex = regexp.MustCompile(`Digest: ([\S]+)`)
  27. )
  28. func setupImage(c *testing.T) (digest.Digest, error) {
  29. return setupImageWithTag(c, "latest")
  30. }
  31. func setupImageWithTag(c *testing.T, tag string) (digest.Digest, error) {
  32. const containerName = "busyboxbydigest"
  33. // new file is committed because this layer is used for detecting malicious
  34. // changes. if this was committed as empty layer it would be skipped on pull
  35. // and malicious changes would never be detected.
  36. cli.DockerCmd(c, "run", "-e", "digest=1", "--name", containerName, "busybox", "touch", "anewfile")
  37. // tag the image to upload it to the private registry
  38. repoAndTag := repoName + ":" + tag
  39. cli.DockerCmd(c, "commit", containerName, repoAndTag)
  40. // delete the container as we don't need it any more
  41. cli.DockerCmd(c, "rm", "-fv", containerName)
  42. // push the image
  43. out := cli.DockerCmd(c, "push", repoAndTag).Combined()
  44. // delete our local repo that we previously tagged
  45. cli.DockerCmd(c, "rmi", repoAndTag)
  46. matches := pushDigestRegex.FindStringSubmatch(out)
  47. assert.Equal(c, len(matches), 2, "unable to parse digest from push output: %s", out)
  48. pushDigest := matches[1]
  49. return digest.Digest(pushDigest), nil
  50. }
  51. func testPullByTagDisplaysDigest(c *testing.T) {
  52. testRequires(c, DaemonIsLinux)
  53. pushDigest, err := setupImage(c)
  54. assert.NilError(c, err, "error setting up image")
  55. // pull from the registry using the tag
  56. out := cli.DockerCmd(c, "pull", repoName).Combined()
  57. // the pull output includes "Digest: <digest>", so find that
  58. matches := digestRegex.FindStringSubmatch(out)
  59. assert.Equal(c, len(matches), 2, "unable to parse digest from push output: %s", out)
  60. pullDigest := matches[1]
  61. // make sure the pushed and pull digests match
  62. assert.Equal(c, pushDigest.String(), pullDigest)
  63. }
  64. func (s *DockerRegistrySuite) TestPullByTagDisplaysDigest(c *testing.T) {
  65. testPullByTagDisplaysDigest(c)
  66. }
  67. func (s *DockerSchema1RegistrySuite) TestPullByTagDisplaysDigest(c *testing.T) {
  68. testPullByTagDisplaysDigest(c)
  69. }
  70. func testPullByDigest(c *testing.T) {
  71. testRequires(c, DaemonIsLinux)
  72. pushDigest, err := setupImage(c)
  73. assert.NilError(c, err, "error setting up image")
  74. // pull from the registry using the <name>@<digest> reference
  75. imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest)
  76. out := cli.DockerCmd(c, "pull", imageReference).Combined()
  77. // the pull output includes "Digest: <digest>", so find that
  78. matches := digestRegex.FindStringSubmatch(out)
  79. assert.Equal(c, len(matches), 2, "unable to parse digest from push output: %s", out)
  80. pullDigest := matches[1]
  81. // make sure the pushed and pull digests match
  82. assert.Equal(c, pushDigest.String(), pullDigest)
  83. }
  84. func (s *DockerRegistrySuite) TestPullByDigest(c *testing.T) {
  85. testPullByDigest(c)
  86. }
  87. func (s *DockerSchema1RegistrySuite) TestPullByDigest(c *testing.T) {
  88. testPullByDigest(c)
  89. }
  90. func testPullByDigestNoFallback(c *testing.T) {
  91. testRequires(c, DaemonIsLinux)
  92. // pull from the registry using the <name>@<digest> reference
  93. imageReference := fmt.Sprintf("%s@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", repoName)
  94. out, _, err := dockerCmdWithError("pull", imageReference)
  95. assert.Assert(c, err != nil, "expected non-zero exit status and correct error message when pulling non-existing image")
  96. expectedMsg := fmt.Sprintf("manifest for %s not found", imageReference)
  97. if testEnv.UsingSnapshotter() {
  98. expectedMsg = fmt.Sprintf("%s: not found", imageReference)
  99. }
  100. assert.Check(c, is.Contains(out, expectedMsg), "expected non-zero exit status and correct error message when pulling non-existing image")
  101. }
  102. func (s *DockerRegistrySuite) TestPullByDigestNoFallback(c *testing.T) {
  103. testPullByDigestNoFallback(c)
  104. }
  105. func (s *DockerSchema1RegistrySuite) TestPullByDigestNoFallback(c *testing.T) {
  106. testPullByDigestNoFallback(c)
  107. }
  108. func (s *DockerRegistrySuite) TestCreateByDigest(c *testing.T) {
  109. pushDigest, err := setupImage(c)
  110. assert.NilError(c, err, "error setting up image")
  111. imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest)
  112. const containerName = "createByDigest"
  113. cli.DockerCmd(c, "create", "--name", containerName, imageReference)
  114. res := inspectField(c, containerName, "Config.Image")
  115. assert.Equal(c, res, imageReference)
  116. }
  117. func (s *DockerRegistrySuite) TestRunByDigest(c *testing.T) {
  118. pushDigest, err := setupImage(c)
  119. assert.NilError(c, err)
  120. imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest)
  121. const containerName = "runByDigest"
  122. out := cli.DockerCmd(c, "run", "--name", containerName, imageReference, "sh", "-c", "echo found=$digest").Combined()
  123. foundRegex := regexp.MustCompile("found=([^\n]+)")
  124. matches := foundRegex.FindStringSubmatch(out)
  125. assert.Equal(c, len(matches), 2, fmt.Sprintf("unable to parse digest from pull output: %s", out))
  126. assert.Equal(c, matches[1], "1", fmt.Sprintf("Expected %q, got %q", "1", matches[1]))
  127. res := inspectField(c, containerName, "Config.Image")
  128. assert.Equal(c, res, imageReference)
  129. }
  130. func (s *DockerRegistrySuite) TestRemoveImageByDigest(c *testing.T) {
  131. imgDigest, err := setupImage(c)
  132. assert.NilError(c, err, "error setting up image")
  133. imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest)
  134. // pull from the registry using the <name>@<digest> reference
  135. cli.DockerCmd(c, "pull", imageReference)
  136. // make sure inspect runs ok
  137. inspectField(c, imageReference, "Id")
  138. // do the delete
  139. err = deleteImages(imageReference)
  140. assert.NilError(c, err, "unexpected error deleting image")
  141. // try to inspect again - it should error this time
  142. _, err = inspectFieldWithError(imageReference, "Id")
  143. // unexpected nil err trying to inspect what should be a non-existent image
  144. assert.ErrorContains(c, err, "No such object")
  145. }
  146. func (s *DockerRegistrySuite) TestBuildByDigest(c *testing.T) {
  147. skip.If(c, testEnv.UsingSnapshotter(), "Config.Image is not created with containerd, buildkit doesn't set it either")
  148. imgDigest, err := setupImage(c)
  149. assert.NilError(c, err, "error setting up image")
  150. imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest)
  151. // pull from the registry using the <name>@<digest> reference
  152. cli.DockerCmd(c, "pull", imageReference)
  153. // get the image id
  154. imageID := inspectField(c, imageReference, "Id")
  155. // do the build
  156. const name = "buildbydigest"
  157. buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(
  158. `FROM %s
  159. CMD ["/bin/echo", "Hello World"]`, imageReference)))
  160. assert.NilError(c, err)
  161. // get the build's image id
  162. res := inspectField(c, name, "Config.Image")
  163. // make sure they match
  164. assert.Equal(c, res, imageID)
  165. }
  166. func (s *DockerRegistrySuite) TestTagByDigest(c *testing.T) {
  167. imgDigest, err := setupImage(c)
  168. assert.NilError(c, err, "error setting up image")
  169. imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest)
  170. // pull from the registry using the <name>@<digest> reference
  171. cli.DockerCmd(c, "pull", imageReference)
  172. // tag it
  173. const tag = "tagbydigest"
  174. cli.DockerCmd(c, "tag", imageReference, tag)
  175. expectedID := inspectField(c, imageReference, "Id")
  176. tagID := inspectField(c, tag, "Id")
  177. assert.Equal(c, tagID, expectedID)
  178. }
  179. func (s *DockerRegistrySuite) TestListImagesWithoutDigests(c *testing.T) {
  180. imgDigest, err := setupImage(c)
  181. assert.NilError(c, err, "error setting up image")
  182. imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest)
  183. // pull from the registry using the <name>@<digest> reference
  184. cli.DockerCmd(c, "pull", imageReference)
  185. out := cli.DockerCmd(c, "images").Stdout()
  186. assert.Assert(c, !strings.Contains(out, "DIGEST"), "list output should not have contained DIGEST header")
  187. }
  188. func (s *DockerRegistrySuite) TestListImagesWithDigests(c *testing.T) {
  189. // setup image1
  190. digest1, err := setupImageWithTag(c, "tag1")
  191. assert.NilError(c, err, "error setting up image")
  192. imageReference1 := fmt.Sprintf("%s@%s", repoName, digest1)
  193. c.Logf("imageReference1 = %s", imageReference1)
  194. // pull image1 by digest
  195. cli.DockerCmd(c, "pull", imageReference1)
  196. // list images
  197. out := cli.DockerCmd(c, "images", "--digests").Combined()
  198. // make sure repo shown, tag=<none>, digest = $digest1
  199. re1 := regexp.MustCompile(`\s*` + repoName + `\s*<none>\s*` + digest1.String() + `\s`)
  200. assert.Assert(c, re1.MatchString(out), "expected %q: %s", re1.String(), out)
  201. // setup image2
  202. digest2, err := setupImageWithTag(c, "tag2")
  203. assert.NilError(c, err, "error setting up image")
  204. imageReference2 := fmt.Sprintf("%s@%s", repoName, digest2)
  205. c.Logf("imageReference2 = %s", imageReference2)
  206. // pull image1 by digest
  207. cli.DockerCmd(c, "pull", imageReference1)
  208. // pull image2 by digest
  209. cli.DockerCmd(c, "pull", imageReference2)
  210. // list images
  211. out = cli.DockerCmd(c, "images", "--digests").Stdout()
  212. // make sure repo shown, tag=<none>, digest = $digest1
  213. assert.Assert(c, re1.MatchString(out), "expected %q: %s", re1.String(), out)
  214. // make sure repo shown, tag=<none>, digest = $digest2
  215. re2 := regexp.MustCompile(`\s*` + repoName + `\s*<none>\s*` + digest2.String() + `\s`)
  216. assert.Assert(c, re2.MatchString(out), "expected %q: %s", re2.String(), out)
  217. // pull tag1
  218. cli.DockerCmd(c, "pull", repoName+":tag1")
  219. // list images
  220. out = cli.DockerCmd(c, "images", "--digests").Stdout()
  221. // make sure image 1 has repo, tag, <none> AND repo, <none>, digest
  222. reWithDigest1 := regexp.MustCompile(`\s*` + repoName + `\s*tag1\s*` + digest1.String() + `\s`)
  223. assert.Assert(c, reWithDigest1.MatchString(out), "expected %q: %s", reWithDigest1.String(), out)
  224. // make sure image 2 has repo, <none>, digest
  225. assert.Assert(c, re2.MatchString(out), "expected %q: %s", re2.String(), out)
  226. // pull tag 2
  227. cli.DockerCmd(c, "pull", repoName+":tag2")
  228. // list images
  229. out = cli.DockerCmd(c, "images", "--digests").Stdout()
  230. // make sure image 1 has repo, tag, digest
  231. assert.Assert(c, reWithDigest1.MatchString(out), "expected %q: %s", reWithDigest1.String(), out)
  232. // make sure image 2 has repo, tag, digest
  233. reWithDigest2 := regexp.MustCompile(`\s*` + repoName + `\s*tag2\s*` + digest2.String() + `\s`)
  234. assert.Assert(c, reWithDigest2.MatchString(out), "expected %q: %s", reWithDigest2.String(), out)
  235. // list images
  236. out = cli.DockerCmd(c, "images", "--digests").Stdout()
  237. // make sure image 1 has repo, tag, digest
  238. assert.Assert(c, reWithDigest1.MatchString(out), "expected %q: %s", reWithDigest1.String(), out)
  239. // make sure image 2 has repo, tag, digest
  240. assert.Assert(c, reWithDigest2.MatchString(out), "expected %q: %s", reWithDigest2.String(), out)
  241. // We always have a digest when using containerd to store images
  242. if !testEnv.UsingSnapshotter() {
  243. // make sure busybox has tag, but not digest
  244. busyboxRe := regexp.MustCompile(`\s*busybox\s*latest\s*<none>\s`)
  245. assert.Assert(c, busyboxRe.MatchString(out), "expected %q: %s", busyboxRe.String(), out)
  246. }
  247. }
  248. func (s *DockerRegistrySuite) TestListDanglingImagesWithDigests(c *testing.T) {
  249. // See https://github.com/moby/moby/pull/46856
  250. skip.If(c, testEnv.UsingSnapshotter(), "dangling=true filter behaves a bit differently with c8d")
  251. // setup image1
  252. digest1, err := setupImageWithTag(c, "dangle1")
  253. assert.NilError(c, err, "error setting up image")
  254. imageReference1 := fmt.Sprintf("%s@%s", repoName, digest1)
  255. c.Logf("imageReference1 = %s", imageReference1)
  256. // pull image1 by digest
  257. cli.DockerCmd(c, "pull", imageReference1)
  258. // list images
  259. out := cli.DockerCmd(c, "images", "--digests").Stdout()
  260. // make sure repo shown, tag=<none>, digest = $digest1
  261. re1 := regexp.MustCompile(`\s*` + repoName + `\s*<none>\s*` + digest1.String() + `\s`)
  262. assert.Assert(c, re1.MatchString(out), "expected %q: %s", re1.String(), out)
  263. // setup image2
  264. digest2, err := setupImageWithTag(c, "dangle2")
  265. // error setting up image
  266. assert.NilError(c, err)
  267. imageReference2 := fmt.Sprintf("%s@%s", repoName, digest2)
  268. c.Logf("imageReference2 = %s", imageReference2)
  269. // pull image1 by digest
  270. cli.DockerCmd(c, "pull", imageReference1)
  271. // pull image2 by digest
  272. cli.DockerCmd(c, "pull", imageReference2)
  273. // list images
  274. out = cli.DockerCmd(c, "images", "--digests", "--filter=dangling=true").Stdout()
  275. // make sure repo shown, tag=<none>, digest = $digest1
  276. assert.Assert(c, re1.MatchString(out), "expected %q: %s", re1.String(), out)
  277. // make sure repo shown, tag=<none>, digest = $digest2
  278. re2 := regexp.MustCompile(`\s*` + repoName + `\s*<none>\s*` + digest2.String() + `\s`)
  279. assert.Assert(c, re2.MatchString(out), "expected %q: %s", re2.String(), out)
  280. // pull dangle1 tag
  281. cli.DockerCmd(c, "pull", repoName+":dangle1")
  282. // list images
  283. out = cli.DockerCmd(c, "images", "--digests", "--filter=dangling=true").Stdout()
  284. // make sure image 1 has repo, tag, <none> AND repo, <none>, digest
  285. reWithDigest1 := regexp.MustCompile(`\s*` + repoName + `\s*dangle1\s*` + digest1.String() + `\s`)
  286. assert.Assert(c, !reWithDigest1.MatchString(out), "unexpected %q: %s", reWithDigest1.String(), out)
  287. // make sure image 2 has repo, <none>, digest
  288. assert.Assert(c, re2.MatchString(out), "expected %q: %s", re2.String(), out)
  289. // pull dangle2 tag
  290. cli.DockerCmd(c, "pull", repoName+":dangle2")
  291. // list images, show tagged images
  292. out = cli.DockerCmd(c, "images", "--digests").Stdout()
  293. // make sure image 1 has repo, tag, digest
  294. assert.Assert(c, reWithDigest1.MatchString(out), "expected %q: %s", reWithDigest1.String(), out)
  295. // make sure image 2 has repo, tag, digest
  296. reWithDigest2 := regexp.MustCompile(`\s*` + repoName + `\s*dangle2\s*` + digest2.String() + `\s`)
  297. assert.Assert(c, reWithDigest2.MatchString(out), "expected %q: %s", reWithDigest2.String(), out)
  298. // list images, no longer dangling, should not match
  299. out = cli.DockerCmd(c, "images", "--digests", "--filter=dangling=true").Stdout()
  300. // make sure image 1 has repo, tag, digest
  301. assert.Assert(c, !reWithDigest1.MatchString(out), "unexpected %q: %s", reWithDigest1.String(), out)
  302. // make sure image 2 has repo, tag, digest
  303. assert.Assert(c, !reWithDigest2.MatchString(out), "unexpected %q: %s", reWithDigest2.String(), out)
  304. }
  305. func (s *DockerRegistrySuite) TestInspectImageWithDigests(c *testing.T) {
  306. imgDigest, err := setupImage(c)
  307. assert.Assert(c, err == nil, "error setting up image")
  308. imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest)
  309. // pull from the registry using the <name>@<digest> reference
  310. cli.DockerCmd(c, "pull", imageReference)
  311. out := cli.DockerCmd(c, "inspect", imageReference).Stdout()
  312. var imageJSON []types.ImageInspect
  313. err = json.Unmarshal([]byte(out), &imageJSON)
  314. assert.NilError(c, err)
  315. assert.Equal(c, len(imageJSON), 1)
  316. assert.Equal(c, len(imageJSON[0].RepoDigests), 1)
  317. assert.Check(c, is.Contains(imageJSON[0].RepoDigests, imageReference))
  318. }
  319. func (s *DockerRegistrySuite) TestPsListContainersFilterAncestorImageByDigest(c *testing.T) {
  320. existingContainers := ExistingContainerIDs(c)
  321. imgDigest, err := setupImage(c)
  322. assert.NilError(c, err, "error setting up image")
  323. imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest)
  324. // pull from the registry using the <name>@<digest> reference
  325. cli.DockerCmd(c, "pull", imageReference)
  326. // build an image from it
  327. const imageName1 = "images_ps_filter_test"
  328. buildImageSuccessfully(c, imageName1, build.WithDockerfile(fmt.Sprintf(
  329. `FROM %s
  330. LABEL match me 1`, imageReference)))
  331. // run a container based on that
  332. cli.DockerCmd(c, "run", "--name=test1", imageReference, "echo", "hello")
  333. expectedID := getIDByName(c, "test1")
  334. // run a container based on the a descendant of that too
  335. cli.DockerCmd(c, "run", "--name=test2", imageName1, "echo", "hello")
  336. expectedID1 := getIDByName(c, "test2")
  337. expectedIDs := []string{expectedID, expectedID1}
  338. // Invalid imageReference
  339. out := cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", fmt.Sprintf("--filter=ancestor=busybox@%s", imgDigest)).Stdout()
  340. assert.Equal(c, strings.TrimSpace(out), "", "Filter container for ancestor filter should be empty")
  341. // Valid imageReference
  342. out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+imageReference).Stdout()
  343. checkPsAncestorFilterOutput(c, RemoveOutputForExistingElements(out, existingContainers), imageReference, expectedIDs)
  344. }
  345. func (s *DockerRegistrySuite) TestDeleteImageByIDOnlyPulledByDigest(c *testing.T) {
  346. pushDigest, err := setupImage(c)
  347. assert.NilError(c, err, "error setting up image")
  348. // pull from the registry using the <name>@<digest> reference
  349. imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest)
  350. cli.DockerCmd(c, "pull", imageReference)
  351. // just in case...
  352. cli.DockerCmd(c, "tag", imageReference, repoName+":sometag")
  353. imageID := inspectField(c, imageReference, "Id")
  354. cli.DockerCmd(c, "rmi", imageID)
  355. _, err = inspectFieldWithError(imageID, "Id")
  356. assert.ErrorContains(c, err, "", "image should have been deleted")
  357. }
  358. func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndTag(c *testing.T) {
  359. pushDigest, err := setupImage(c)
  360. assert.NilError(c, err, "error setting up image")
  361. // pull from the registry using the <name>@<digest> reference
  362. imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest)
  363. cli.DockerCmd(c, "pull", imageReference)
  364. imageID := inspectField(c, imageReference, "Id")
  365. const repoTag = repoName + ":sometag"
  366. const repoTag2 = repoName + ":othertag"
  367. cli.DockerCmd(c, "tag", imageReference, repoTag)
  368. cli.DockerCmd(c, "tag", imageReference, repoTag2)
  369. cli.DockerCmd(c, "rmi", repoTag2)
  370. // rmi should have deleted only repoTag2, because there's another tag
  371. inspectField(c, repoTag, "Id")
  372. cli.DockerCmd(c, "rmi", repoTag)
  373. // rmi should have deleted the tag, the digest reference, and the image itself
  374. _, err = inspectFieldWithError(imageID, "Id")
  375. assert.ErrorContains(c, err, "", "image should have been deleted")
  376. }
  377. func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndMultiRepoTag(c *testing.T) {
  378. pushDigest, err := setupImage(c)
  379. assert.NilError(c, err, "error setting up image")
  380. repo2 := fmt.Sprintf("%s/%s", repoName, "repo2")
  381. // pull from the registry using the <name>@<digest> reference
  382. imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest)
  383. cli.DockerCmd(c, "pull", imageReference)
  384. imageID := inspectField(c, imageReference, "Id")
  385. repoTag := repoName + ":sometag"
  386. repoTag2 := repo2 + ":othertag"
  387. cli.DockerCmd(c, "tag", imageReference, repoTag)
  388. cli.DockerCmd(c, "tag", imageReference, repoTag2)
  389. cli.DockerCmd(c, "rmi", repoTag)
  390. // rmi should have deleted repoTag and image reference, but left repoTag2
  391. inspectField(c, repoTag2, "Id")
  392. _, err = inspectFieldWithError(imageReference, "Id")
  393. assert.ErrorContains(c, err, "", "image digest reference should have been removed")
  394. _, err = inspectFieldWithError(repoTag, "Id")
  395. assert.ErrorContains(c, err, "", "image tag reference should have been removed")
  396. cli.DockerCmd(c, "rmi", repoTag2)
  397. // rmi should have deleted the tag, the digest reference, and the image itself
  398. _, err = inspectFieldWithError(imageID, "Id")
  399. assert.ErrorContains(c, err, "", "image should have been deleted")
  400. }
  401. // TestPullFailsWithAlteredManifest tests that a `docker pull` fails when
  402. // we have modified a manifest blob and its digest cannot be verified.
  403. // This is the schema2 version of the test.
  404. func (s *DockerRegistrySuite) TestPullFailsWithAlteredManifest(c *testing.T) {
  405. testRequires(c, DaemonIsLinux)
  406. manifestDigest, err := setupImage(c)
  407. assert.NilError(c, err, "error setting up image")
  408. // Load the target manifest blob.
  409. manifestBlob := s.reg.ReadBlobContents(c, manifestDigest)
  410. var imgManifest schema2.Manifest
  411. err = json.Unmarshal(manifestBlob, &imgManifest)
  412. assert.NilError(c, err, "unable to decode image manifest from blob")
  413. // Change a layer in the manifest.
  414. imgManifest.Layers[0].Digest = digest.Digest("sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
  415. // Move the existing data file aside, so that we can replace it with a
  416. // malicious blob of data. NOTE: we defer the returned undo func.
  417. undo := s.reg.TempMoveBlobData(c, manifestDigest)
  418. defer undo()
  419. alteredManifestBlob, err := json.MarshalIndent(imgManifest, "", " ")
  420. assert.NilError(c, err, "unable to encode altered image manifest to JSON")
  421. s.reg.WriteBlobContents(c, manifestDigest, alteredManifestBlob)
  422. // Now try pulling that image by digest. We should get an error about
  423. // digest verification for the manifest digest.
  424. // Pull from the registry using the <name>@<digest> reference.
  425. imageReference := fmt.Sprintf("%s@%s", repoName, manifestDigest)
  426. out, exitStatus, _ := dockerCmdWithError("pull", imageReference)
  427. assert.Assert(c, exitStatus != 0)
  428. if testEnv.UsingSnapshotter() {
  429. assert.Assert(c, is.Contains(out, "unexpected commit digest"))
  430. assert.Assert(c, is.Contains(out, "expected "+manifestDigest))
  431. } else {
  432. assert.Assert(c, is.Contains(out, fmt.Sprintf("manifest verification failed for digest %s", manifestDigest)))
  433. }
  434. }
  435. // TestPullFailsWithAlteredManifest tests that a `docker pull` fails when
  436. // we have modified a manifest blob and its digest cannot be verified.
  437. // This is the schema1 version of the test.
  438. func (s *DockerSchema1RegistrySuite) TestPullFailsWithAlteredManifest(c *testing.T) {
  439. testRequires(c, DaemonIsLinux)
  440. manifestDigest, err := setupImage(c)
  441. assert.Assert(c, err == nil, "error setting up image")
  442. // Load the target manifest blob.
  443. manifestBlob := s.reg.ReadBlobContents(c, manifestDigest)
  444. var imgManifest schema1.Manifest
  445. err = json.Unmarshal(manifestBlob, &imgManifest)
  446. assert.Assert(c, err == nil, "unable to decode image manifest from blob")
  447. // Change a layer in the manifest.
  448. imgManifest.FSLayers[0] = schema1.FSLayer{
  449. BlobSum: digest.Digest("sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"),
  450. }
  451. // Move the existing data file aside, so that we can replace it with a
  452. // malicious blob of data. NOTE: we defer the returned undo func.
  453. undo := s.reg.TempMoveBlobData(c, manifestDigest)
  454. defer undo()
  455. alteredManifestBlob, err := json.MarshalIndent(imgManifest, "", " ")
  456. assert.Assert(c, err == nil, "unable to encode altered image manifest to JSON")
  457. s.reg.WriteBlobContents(c, manifestDigest, alteredManifestBlob)
  458. // Now try pulling that image by digest. We should get an error about
  459. // digest verification for the manifest digest.
  460. // Pull from the registry using the <name>@<digest> reference.
  461. imageReference := fmt.Sprintf("%s@%s", repoName, manifestDigest)
  462. out, exitStatus, _ := dockerCmdWithError("pull", imageReference)
  463. assert.Assert(c, exitStatus != 0)
  464. expectedErrorMsg := fmt.Sprintf("image verification failed for digest %s", manifestDigest)
  465. assert.Assert(c, strings.Contains(out, expectedErrorMsg))
  466. }
  467. // TestPullFailsWithAlteredLayer tests that a `docker pull` fails when
  468. // we have modified a layer blob and its digest cannot be verified.
  469. // This is the schema2 version of the test.
  470. func (s *DockerRegistrySuite) TestPullFailsWithAlteredLayer(c *testing.T) {
  471. testRequires(c, DaemonIsLinux)
  472. skip.If(c, testEnv.UsingSnapshotter(), "Faked layer is already in the content store, so it won't be fetched from the repository at all.")
  473. manifestDigest, err := setupImage(c)
  474. assert.Assert(c, err == nil)
  475. // Load the target manifest blob.
  476. manifestBlob := s.reg.ReadBlobContents(c, manifestDigest)
  477. var imgManifest schema2.Manifest
  478. err = json.Unmarshal(manifestBlob, &imgManifest)
  479. assert.Assert(c, err == nil)
  480. // Next, get the digest of one of the layers from the manifest.
  481. targetLayerDigest := imgManifest.Layers[0].Digest
  482. // Move the existing data file aside, so that we can replace it with a
  483. // malicious blob of data. NOTE: we defer the returned undo func.
  484. undo := s.reg.TempMoveBlobData(c, targetLayerDigest)
  485. defer undo()
  486. // Now make a fake data blob in this directory.
  487. s.reg.WriteBlobContents(c, targetLayerDigest, []byte("This is not the data you are looking for."))
  488. // Now try pulling that image by digest. We should get an error about
  489. // digest verification for the target layer digest.
  490. // Remove distribution cache to force a re-pull of the blobs
  491. if err := os.RemoveAll(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "image", s.d.StorageDriver(), "distribution")); err != nil {
  492. c.Fatalf("error clearing distribution cache: %v", err)
  493. }
  494. // Pull from the registry using the <name>@<digest> reference.
  495. imageReference := fmt.Sprintf("%s@%s", repoName, manifestDigest)
  496. out, exitStatus, _ := dockerCmdWithError("pull", imageReference)
  497. assert.Assert(c, exitStatus != 0, "expected a non-zero exit status")
  498. expectedErrorMsg := fmt.Sprintf("filesystem layer verification failed for digest %s", targetLayerDigest)
  499. assert.Assert(c, strings.Contains(out, expectedErrorMsg), "expected error message in output: %s", out)
  500. }
  501. // TestPullFailsWithAlteredLayer tests that a `docker pull` fails when
  502. // we have modified a layer blob and its digest cannot be verified.
  503. // This is the schema1 version of the test.
  504. func (s *DockerSchema1RegistrySuite) TestPullFailsWithAlteredLayer(c *testing.T) {
  505. testRequires(c, DaemonIsLinux)
  506. manifestDigest, err := setupImage(c)
  507. assert.Assert(c, err == nil)
  508. // Load the target manifest blob.
  509. manifestBlob := s.reg.ReadBlobContents(c, manifestDigest)
  510. var imgManifest schema1.Manifest
  511. err = json.Unmarshal(manifestBlob, &imgManifest)
  512. assert.Assert(c, err == nil)
  513. // Next, get the digest of one of the layers from the manifest.
  514. targetLayerDigest := imgManifest.FSLayers[0].BlobSum
  515. // Move the existing data file aside, so that we can replace it with a
  516. // malicious blob of data. NOTE: we defer the returned undo func.
  517. undo := s.reg.TempMoveBlobData(c, targetLayerDigest)
  518. defer undo()
  519. // Now make a fake data blob in this directory.
  520. s.reg.WriteBlobContents(c, targetLayerDigest, []byte("This is not the data you are looking for."))
  521. // Now try pulling that image by digest. We should get an error about
  522. // digest verification for the target layer digest.
  523. // Remove distribution cache to force a re-pull of the blobs
  524. if err := os.RemoveAll(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "image", s.d.StorageDriver(), "distribution")); err != nil {
  525. c.Fatalf("error clearing distribution cache: %v", err)
  526. }
  527. // Pull from the registry using the <name>@<digest> reference.
  528. imageReference := fmt.Sprintf("%s@%s", repoName, manifestDigest)
  529. out, exitStatus, _ := dockerCmdWithError("pull", imageReference)
  530. assert.Assert(c, exitStatus != 0, "expected a non-zero exit status")
  531. expectedErrorMsg := fmt.Sprintf("filesystem layer verification failed for digest %s", targetLayerDigest)
  532. assert.Assert(c, strings.Contains(out, expectedErrorMsg), "expected error message in output: %s", out)
  533. }