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