File: manifest_list_test.go

package info (click to toggle)
golang-github-containers-common 0.64.1%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 5,932 kB
  • sloc: makefile: 132; sh: 111
file content (507 lines) | stat: -rw-r--r-- 18,536 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//go:build !remote

package libimage

import (
	"bytes"
	"context"
	"crypto/rand"
	"errors"
	"fmt"
	"io"
	mathrand "math/rand"
	"mime"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"testing"

	"github.com/containers/common/pkg/config"
	cp "github.com/containers/image/v5/copy"
	"github.com/containers/image/v5/image"
	"github.com/containers/image/v5/manifest"
	"github.com/containers/image/v5/pkg/compression"
	"github.com/containers/image/v5/transports/alltransports"
	"github.com/containers/storage"
	"github.com/containers/storage/pkg/ioutils"
	"github.com/opencontainers/go-digest"
	imgspecv1 "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestCreateManifestList(t *testing.T) {
	runtime := testNewRuntime(t)
	ctx := context.Background()

	list, err := runtime.CreateManifestList("mylist")
	require.NoError(t, err)
	require.NotNil(t, list)
	initialID := list.ID()

	list, err = runtime.LookupManifestList("mylist")
	require.NoError(t, err)
	require.NotNil(t, list)
	require.Equal(t, initialID, list.ID())

	_, rmErrors := runtime.RemoveImages(ctx, []string{"mylist"}, nil)
	require.Nil(t, rmErrors)

	_, err = runtime.LookupManifestList("nosuchthing")
	require.Error(t, err)
	require.True(t, errors.Is(err, storage.ErrImageUnknown))

	_, err = runtime.Pull(ctx, "busybox", config.PullPolicyMissing, nil)
	require.NoError(t, err)
	_, err = runtime.LookupManifestList("busybox")
	require.Error(t, err)
	require.True(t, errors.Is(err, ErrNotAManifestList))
}

func TestConvertManifestList(t *testing.T) {
	runtime := testNewRuntime(t)
	ctx := context.Background()

	images, err := runtime.Pull(ctx, "busybox", config.PullPolicyMissing, nil)
	require.NoError(t, err)
	_, err = runtime.LookupManifestList("busybox")
	require.Error(t, err)
	require.ErrorIs(t, err, ErrNotAManifestList)

	require.NotEmpty(t, images)
	_, err = images[0].ToManifestList()
	require.ErrorIs(t, err, ErrNotAManifestList)
	isList, err := images[0].IsManifestList(ctx)
	require.NoError(t, err)
	require.False(t, isList, "non-list thinks it's a list")

	list, err := images[0].ConvertToManifestList(ctx)
	require.NoError(t, err)
	require.NotNil(t, list)

	isList, err = images[0].IsManifestList(ctx)
	require.NoError(t, err)
	require.True(t, isList, "list thinks it's not a list")
}

// Inspect must contain both formats i.e OCIv1 and docker
func TestInspectManifestListWithAnnotations(t *testing.T) {
	listName := "testinspect"
	runtime := testNewRuntime(t)
	ctx := context.Background()

	list, err := runtime.CreateManifestList(listName)
	require.NoError(t, err)
	require.NotNil(t, list)

	manifestListOpts := &ManifestListAddOptions{All: true}
	_, err = list.Add(ctx, "docker://busybox", manifestListOpts)
	require.NoError(t, err)

	list, err = runtime.LookupManifestList(listName)
	require.NoError(t, err)
	require.NotNil(t, list)

	inspectReport, err := list.Inspect()
	// get digest of the first instance
	digest := inspectReport.Manifests[0].Digest
	require.NoError(t, err)

	annotateOptions := ManifestListAnnotateOptions{}
	annotations := map[string]string{"hello": "world"}
	annotateOptions.Annotations = annotations
	indexAnnotations := map[string]string{"goodbye": "globe"}
	annotateOptions.IndexAnnotations = indexAnnotations

	subjectPath, err := filepath.Abs(filepath.Join("..", "pkg", "manifests", "testdata", "artifacts", "blobs-only"))
	require.NoError(t, err)
	annotateOptions.Subject = "oci:" + subjectPath

	err = list.AnnotateInstance(digest, &annotateOptions)
	require.NoError(t, err)
	// Inspect list again
	inspectReport, err = list.Inspect()
	require.NoError(t, err)
	// verify annotation
	require.Contains(t, inspectReport.Manifests[0].Annotations, "hello")
	require.Equal(t, inspectReport.Manifests[0].Annotations["hello"], annotations["hello"])
	require.Equal(t, inspectReport.Annotations, indexAnnotations)
	require.Equal(t, inspectReport.Subject.MediaType, imgspecv1.MediaTypeImageManifest)

	// verify that we can clear the variant field by not setting it when we set the arch
	annotateOptions = ManifestListAnnotateOptions{
		Architecture: "arm64",
		Variant:      "v8",
	}
	err = list.AnnotateInstance(digest, &annotateOptions)
	require.NoError(t, err)
	inspectReport, err = list.Inspect()
	require.NoError(t, err)
	require.Equal(t, "arm64", inspectReport.Manifests[0].Platform.Architecture)
	require.Equal(t, "v8", inspectReport.Manifests[0].Platform.Variant)

	annotateOptions = ManifestListAnnotateOptions{
		Architecture: "arm64",
	}
	err = list.AnnotateInstance(digest, &annotateOptions)
	require.NoError(t, err)
	inspectReport, err = list.Inspect()
	require.NoError(t, err)
	require.Equal(t, "arm64", inspectReport.Manifests[0].Platform.Architecture)
	require.Equal(t, "", inspectReport.Manifests[0].Platform.Variant)
}

// Following test ensure that `Tag` tags the manifest list instead of resolved image.
// Both the tags should point to same image id
func TestCreateAndTagManifestList(t *testing.T) {
	tagName := "testlisttagged"
	listName := "testlist"
	runtime := testNewRuntime(t)
	ctx := context.Background()

	list, err := runtime.CreateManifestList(listName)
	require.NoError(t, err)
	require.NotNil(t, list)

	_, err = runtime.Load(ctx, "testdata/oci-unnamed.tar.gz", nil)
	require.NoError(t, err)

	// add a remote reference
	manifestListOpts := &ManifestListAddOptions{All: true}
	_, err = list.Add(ctx, "docker://busybox", manifestListOpts)
	require.NoError(t, err)

	// add a remote reference where we have to figure out that it's remote
	_, err = list.Add(ctx, "busybox", manifestListOpts)
	require.NoError(t, err)

	// add using a local image's ID
	_, err = list.Add(ctx, "5c8aca8137ac47e84c69ae93ce650ce967917cc001ba7aad5494073fac75b8b6", manifestListOpts)
	require.NoError(t, err)

	list, err = runtime.LookupManifestList(listName)
	require.NoError(t, err)
	require.NotNil(t, list)

	lookupOptions := &LookupImageOptions{ManifestList: true}
	image, _, err := runtime.LookupImage(listName, lookupOptions)
	require.NoError(t, err)
	require.NotNil(t, image)
	err = image.Tag(tagName)
	require.NoError(t, err, "tag should have succeeded: %s", tagName)

	taggedImage, _, err := runtime.LookupImage(tagName, lookupOptions)
	require.NoError(t, err)
	require.NotNil(t, taggedImage)

	// Both origin list and newly tagged list should point to same image id
	require.Equal(t, image.ID(), taggedImage.ID())
}

// Following test ensure that we test  Removing a manifestList
// Test tags two manifestlist and deletes one of them and
// confirms if other one is not deleted.
func TestCreateAndRemoveManifestList(t *testing.T) {
	tagName := "manifestlisttagged"
	listName := "manifestlist"
	runtime := testNewRuntime(t)
	ctx := context.Background()

	list, err := runtime.CreateManifestList(listName)
	require.NoError(t, err)
	require.NotNil(t, list)

	manifestListOpts := &ManifestListAddOptions{All: true}
	_, err = list.Add(ctx, "docker://busybox", manifestListOpts)
	require.NoError(t, err)

	lookupOptions := &LookupImageOptions{ManifestList: true}
	image, _, err := runtime.LookupImage(listName, lookupOptions)
	require.NoError(t, err)
	require.NotNil(t, image)
	err = image.Tag(tagName)
	require.NoError(t, err, "tag should have succeeded: %s", tagName)

	// Try deleting the manifestList with tag
	rmReports, rmErrors := runtime.RemoveImages(ctx, []string{tagName}, &RemoveImagesOptions{Force: true, LookupManifest: true})
	require.Nil(t, rmErrors)
	require.Equal(t, []string{"localhost/manifestlisttagged:latest"}, rmReports[0].Untagged)

	// Remove original listname as well
	rmReports, rmErrors = runtime.RemoveImages(ctx, []string{listName}, &RemoveImagesOptions{Force: true, LookupManifest: true})
	require.Nil(t, rmErrors)
	// output should contain log of untagging the original manifestlist
	require.True(t, rmReports[0].Removed)
	require.Equal(t, []string{"localhost/manifestlist:latest"}, rmReports[0].Untagged)
}

// TestAddSomeArtifacts ensures that we don't fail to add artifact manifests to
// a manifest list, even (or especially) when their config blobs aren't valid
// OCI or Docker config blobs.
func TestAddSomeArtifacts(t *testing.T) {
	listName := "manifestlist"
	runtime := testNewRuntime(t)
	ctx := context.Background()

	list, err := runtime.CreateManifestList(listName)
	require.NoError(t, err)
	require.NotNil(t, list)

	manifestListOpts := &ManifestListAddOptions{All: true}
	absPath, err := filepath.Abs(filepath.Join("..", "pkg", "manifests", "testdata", "artifacts", "blobs-only"))
	require.NoError(t, err)
	_, err = list.Add(ctx, "oci:"+absPath, manifestListOpts)
	require.NoError(t, err)

	absPath, err = filepath.Abs(filepath.Join("..", "pkg", "manifests", "testdata", "artifacts", "config-only"))
	require.NoError(t, err)
	_, err = list.Add(ctx, "oci:"+absPath, manifestListOpts)
	require.NoError(t, err)

	absPath, err = filepath.Abs(filepath.Join("..", "pkg", "manifests", "testdata", "artifacts", "no-blobs"))
	require.NoError(t, err)
	_, err = list.Add(ctx, "oci:"+absPath, manifestListOpts)
	require.NoError(t, err)
}

// TestAddArtifacts ensures that we don't fail to add artifact manifests to
// a manifest list, even (or especially) when their config blobs aren't valid
// OCI or Docker config blobs.
func TestAddArtifacts(t *testing.T) {
	listName := "manifestlist"
	ctx := context.Background()
	dir := t.TempDir()
	annotations := map[string]string{
		"a": "b",
	}
	indexAnnotations := map[string]string{
		"c": "d",
	}
	files := []struct {
		path             string
		size             int
		data             []byte
		noCompress       bool
		guessedMediaType string // what we expect, might be wrong
	}{
		{path: "first.txt", size: mathrand.Intn(256), guessedMediaType: "text/plain"},
		{path: "second.qcow2", size: 512 + mathrand.Intn(256), guessedMediaType: "application/x-qemu-disk"},
		{path: "third", size: 1024 + mathrand.Intn(256), guessedMediaType: "application/x-gzip"},
		{path: "fourth", size: 2048 + mathrand.Intn(256), noCompress: true, guessedMediaType: "application/octet-stream"},
	}
	artifacts := make([]string, 0, len(files))
	for n := range files {
		file := filepath.Join(dir, files[n].path)
		abs, err := filepath.Abs(file)
		require.NoError(t, err)
		files[n].path = abs
		if files[n].data == nil {
			buf := bytes.Buffer{}
			wc := ioutils.NopWriteCloser(&buf)
			if !files[n].noCompress {
				wc, err = compression.CompressStream(&buf, compression.Gzip, nil)
				require.NoError(t, err)
			}
			_, err = io.CopyN(wc, rand.Reader, int64(files[n].size))
			require.NoError(t, err)
			wc.Close()
			files[n].size = buf.Len()
			files[n].data = buf.Bytes()
		}
		err = os.WriteFile(abs, files[n].data, 0o600)
		require.NoError(t, err)
		artifacts = append(artifacts, abs)
	}
	artifactSubjectPath, err := filepath.Abs(filepath.Join("..", "pkg", "manifests", "testdata", "artifacts", "blobs-only"))
	require.NoError(t, err)
	artifactSubject := "oci:" + artifactSubjectPath
	indexSubjectPath, err := filepath.Abs(filepath.Join("..", "pkg", "manifests", "testdata", "artifacts", "config-only"))
	require.NoError(t, err)
	indexSubject := "oci:" + indexSubjectPath
	runtime := testNewRuntime(t)
	descriptorForSubject := func(t *testing.T, refName string) imgspecv1.Descriptor {
		if refName == "" {
			return imgspecv1.Descriptor{}
		}
		ref, err := alltransports.ParseImageName(refName)
		require.NoError(t, err)
		src, err := ref.NewImageSource(ctx, nil)
		require.NoError(t, err)
		defer src.Close()
		manifestBytes, manifestType, err := image.UnparsedInstance(src, nil).Manifest(ctx)
		require.NoError(t, err)
		manifestDigest, err := manifest.Digest(manifestBytes)
		require.NoError(t, err)
		artifactType := ""
		if !manifest.MIMETypeIsMultiImage(manifestType) {
			var manifestContents imgspecv1.Manifest
			require.NoError(t, json.Unmarshal(manifestBytes, &manifestContents))
			artifactType = manifestContents.ArtifactType
		}
		return imgspecv1.Descriptor{
			MediaType:    manifestType,
			ArtifactType: artifactType,
			Digest:       manifestDigest,
			Size:         int64(len(manifestBytes)),
		}
	}
	listIndex := 0
	testWith := func(t *testing.T, testName string, artifactTypeSpec string, configType string, configData string, layerType string, excludeTitles bool, artifactSubject string, artifactSubjectDescriptor imgspecv1.Descriptor, indexSubject string, indexSubjectDescriptor imgspecv1.Descriptor) {
		listIndex++
		listName := listName + strconv.Itoa(listIndex)
		t.Run(testName, func(t *testing.T) {
			var artifactType *string
			if artifactTypeSpec != "<nil>" {
				artifactType = &artifactTypeSpec
			}
			options := ManifestListAddArtifactOptions{
				Type:          artifactType,
				ConfigType:    configType,
				Config:        configData,
				LayerType:     layerType,
				ExcludeTitles: excludeTitles,
				Annotations:   annotations,
				Subject:       artifactSubject,
			}
			list, err := runtime.CreateManifestList(listName)
			require.NoError(t, err)
			require.NotNil(t, list)

			d, err := list.AddArtifact(ctx, &options, artifacts...)
			require.NoError(t, err)

			aoptions := ManifestListAnnotateOptions{
				IndexAnnotations: indexAnnotations,
				Subject:          indexSubject,
			}
			err = list.AnnotateInstance(d, &aoptions)
			require.NoError(t, err)

			//nolint:usetesting // Test fails when using t.TempDir() because the resulting file name is to long.
			destination, err := os.MkdirTemp(dir, "pushed")
			require.NoError(t, err)

			_, err = list.Push(ctx, "oci:"+destination+":tag", &ManifestListPushOptions{ImageListSelection: cp.CopyAllImages})
			require.NoError(t, err)

			ref, err := alltransports.ParseImageName("oci:" + destination + ":tag")
			require.NoError(t, err)

			src, err := ref.NewImageSource(ctx, list.image.runtime.systemContextCopy())
			require.NoError(t, err)
			indexManifest, indexType, err := image.UnparsedInstance(src, nil).Manifest(ctx)
			require.NoError(t, err)
			require.True(t, manifest.MIMETypeIsMultiImage(indexType))
			var index imgspecv1.Index
			require.NoError(t, json.Unmarshal(indexManifest, &index))
			// check some things in the image index
			assert.Equal(t, index.Annotations, indexAnnotations)
			if index.Subject != nil {
				assert.Equal(t, indexSubjectDescriptor, *index.Subject, "subject in index was not preserved")
			}
			for _, descriptor := range index.Manifests {
				artifactManifest, artifactManifestType, err := image.UnparsedInstance(src, &descriptor.Digest).Manifest(ctx)
				require.NoError(t, err)
				require.False(t, manifest.MIMETypeIsMultiImage(artifactManifestType))
				var artifact imgspecv1.Manifest
				require.NoError(t, json.Unmarshal(artifactManifest, &artifact))
				// check some things in the artifact manifest
				switch artifactTypeSpec {
				case "<nil>":
					assert.Equal(t, "application/vnd.unknown.artifact.v1", artifact.ArtifactType)
				default:
					assert.Equal(t, *artifactType, artifact.ArtifactType)
				}
				// FIXME: require.Equal(t, artifact.ArtifactType, descriptor.ArtifactType, "artifact type in index descriptor not preserved during push")
				switch configType {
				case "":
					if len(configData) > 0 {
						assert.Equal(t, imgspecv1.MediaTypeImageConfig, artifact.Config.MediaType)
					} else {
						assert.Equal(t, imgspecv1.DescriptorEmptyJSON.MediaType, artifact.Config.MediaType)
					}
				default:
					assert.Equal(t, configType, artifact.Config.MediaType)
				}
				for i, layer := range artifact.Layers {
					switch layerType {
					case "":
						var rawMediaType string
						baseName := filepath.Base(files[i].path)
						if dotIndex := strings.LastIndex(filepath.Base(files[i].path), "."); dotIndex != -1 {
							rawMediaType = mime.TypeByExtension(baseName[dotIndex:])
						} else {
							rawMediaType = http.DetectContentType(files[i].data)
						}
						parsedMediaType, _, err := mime.ParseMediaType(rawMediaType)
						require.NoError(t, err)
						assert.Equal(t, files[i].guessedMediaType, parsedMediaType)
					default:
						assert.Equal(t, layerType, layer.MediaType)
					}
					if excludeTitles {
						assert.NotContains(t, layer.Annotations, imgspecv1.AnnotationTitle)
						// FIXME: } else {
						// FIXME: require.Contains(t, layer.Annotations, imgspecv1.AnnotationTitle, "layer annotations lost during push")
						// FIXME: assert.Equal(t, filepath.Base(files[i].path), layer.Annotations[imgspecv1.AnnotationTitle], "layer annotations lost during push")
					}
					if layer.MediaType != imgspecv1.MediaTypeImageLayerGzip { // might have been (re)compressed
						assert.Equal(t, digest.FromBytes(files[i].data), layer.Digest, "layer content digest changed during push")
						assert.Equal(t, int64(len(files[i].data)), layer.Size, "layer content size changed during push")
					}
					if artifact.Subject != nil {
						assert.Equal(t, artifactSubjectDescriptor, *artifact.Subject)
					}
				}
			}
		})
	}
	for _, artifactTypeSpec := range []string{
		"<nil>",
		"",
		"application/vnd.unknown.artifact.v1",
		"application/x-something-else",
	} {
		testName := "artifactType=" + artifactTypeSpec
		for _, configType := range []string{
			"",
			imgspecv1.MediaTypeImageConfig,
			imgspecv1.DescriptorEmptyJSON.MediaType,
		} {
			testName := testName + ",configType=" + configType
			for _, configData := range []string{
				"",
				`{"a":"b"}`,
			} {
				testName := testName + ",configLength=" + strconv.Itoa(len(configData))
				for _, layerType := range []string{
					"",
					"application/octet-stream",
					imgspecv1.MediaTypeImageLayerGzip,
				} {
					testName := testName + ",layerType=" + layerType
					for _, excludeTitles := range []bool{false, true} {
						testName := testName + ",excludeTitles=" + fmt.Sprintf("%v", excludeTitles)
						for _, artifactSubject := range []string{"", artifactSubject} {
							testName := testName + ",artifactSubject="
							if artifactSubject != "" {
								testName += filepath.Base(artifactSubjectPath)
							}
							artifactSubjectDescriptor := descriptorForSubject(t, artifactSubject)
							for _, indexSubject := range []string{"", indexSubject} {
								testName := testName + ",indexSubject="
								if indexSubject != "" {
									testName += filepath.Base(indexSubjectPath)
								}
								indexSubjectDescriptor := descriptorForSubject(t, indexSubject)
								testWith(t, testName, artifactTypeSpec, configType, configData, layerType, excludeTitles, artifactSubject, artifactSubjectDescriptor, indexSubject, indexSubjectDescriptor)
							}
						}
					}
				}
			}
		}
	}
}