github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/integration-cli/docker_cli_by_digest_test.go (about)

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