Debian Codegraph @

registry/repository_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package registry
15
16 import (
17 "bytes"
18 "context"
19 "fmt"
20 "io"
21 "net/http"
22 "net/url"
23 "os"
24 "path/filepath"
25 "reflect"
26 "runtime"
27 "strings"
28 "testing"
29
30 "github.com/notaryproject/notation-go/internal/envelope"
31 "github.com/notaryproject/notation-go/internal/mock/ocilayout"
32 "github.com/notaryproject/notation-go/internal/slices"
33 "github.com/notaryproject/notation-go/registry/internal/artifactspec"
34 "github.com/opencontainers/go-digest"
35 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
36 "oras.land/oras-go/v2/content"
37 "oras.land/oras-go/v2/content/memory"
38 "oras.land/oras-go/v2/content/oci"
39 "oras.land/oras-go/v2/registry"
40 "oras.land/oras-go/v2/registry/remote"
41 )
42
43 const (
44 zeroDigest = "sha256:0000000000000000000000000000000000000000000000000000000000000000"
45 emptyConfigDigest = "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a"
46 validDigest = "6c3c624b58dbbcd3c0dd82b4c53f04194d1247c6eebdaab7c610cf7d66709b3b"
47 validDigest2 = "1834876dcfb05cb167a5c24953eba58c4ac89b1adf57f28f2f9d09af107ee8f2"
48 invalidDigest = "invaliddigest"
49 algo = "sha256"
50 validDigestWithAlgo = algo + ":" + validDigest
51 validDigestWithAlgo2 = algo + ":" + validDigest2
52 validHost = "localhost"
53 validRegistry = validHost + ":5000"
54 invalidHost = "badhost"
55 invalidRegistry = invalidHost + ":5000"
56 validRepo = "test"
57 msg = "message"
58 errMsg = "error message"
59 validReference = validRegistry + "/" + validRepo + "@" + validDigestWithAlgo
60 referenceWithInvalidHost = invalidRegistry + "/" + validRepo + "@" + validDigestWithAlgo
61 invalidReference = "invalid reference"
62 joseTag = "application/jose+json"
63 coseTag = "application/cose"
64 validTimestamp = "2022-07-29T02:23:10Z"
65 validPage = `
66 {
67 "Manifests": [
68 {
69 "MediaType": "application/vnd.oci.image.manifest.v1+json",
70 "Digest": "sha256:cf2a0974295fc17b8351ef52abae2f40212e20e0359ea980ec5597bb0315347b",
71 "Size": 620,
72 "ArtifactType": "application/vnd.cncf.notary.signature"
73 }
74 ]
75 }`
76 validPageDigest = "sha256:cf2a0974295fc17b8351ef52abae2f40212e20e0359ea980ec5597bb0315347b"
77 validPageImage = `
78 {
79 "Manifests": [
80 {
81 "MediaType": "application/vnd.oci.image.manifest.v1+json",
82 "Digest": "sha256:c8f1c1a1bdf099fbc1b70ec4b98da3d8704e27d863f1407db06aad1e022a32cf",
83 "Size": 733,
84 "ArtifactType": "application/vnd.cncf.notary.signature"
85 }
86 ]
87 }`
88 validPageImageDigest = "sha256:c8f1c1a1bdf099fbc1b70ec4b98da3d8704e27d863f1407db06aad1e022a32cf"
89 validBlob = `{
90 "digest": "sha256:1834876dcfb05cb167a5c24953eba58c4ac89b1adf57f28f2f9d09af107ee8f2",
91 "size": 90
92 }`
93 )
94
95 var (
96 validDigestWithAlgoSlice = []string{validDigestWithAlgo, validDigestWithAlgo2}
97 signaturePath = filepath.FromSlash("../internal/testdata/jws_signature.sig")
98 )
99
100 type args struct {
101 ctx context.Context
102 reference string
103 remoteClient remote.Client
104 plainHttp bool
105 annotations map[string]string
106 subjectManifest ocispec.Descriptor
107 signature []byte
108 signatureMediaType string
109 signatureManifestDesc ocispec.Descriptor
110 artifactManifestDesc ocispec.Descriptor
111 }
112
113 type mockRemoteClient struct {
114 }
115
116 func (c mockRemoteClient) Do(req *http.Request) (*http.Response, error) {
117 switch req.URL.Path {
118 case "/v2/test/manifests/" + validDigest:
119 return &http.Response{
120 StatusCode: http.StatusOK,
121 Body: io.NopCloser(bytes.NewReader([]byte(msg))),
122 Header: map[string][]string{
123 "Content-Type": {joseTag},
124 "Docker-Content-Digest": {validDigestWithAlgo},
125 },
126 }, nil
127 case "/v2/test/blobs/" + validDigestWithAlgo2:
128 return &http.Response{
129 StatusCode: http.StatusOK,
130 Body: io.NopCloser(bytes.NewReader([]byte(validBlob))),
131 ContentLength: maxBlobSizeLimit + 1,
132 Header: map[string][]string{
133 "Content-Type": {joseTag},
134 "Docker-Content-Digest": {validDigestWithAlgo2},
135 },
136 }, nil
137 case "/v2/test/blobs/" + emptyConfigDigest:
138 return &http.Response{
139 StatusCode: http.StatusNotFound,
140 Body: io.NopCloser(bytes.NewReader([]byte{})),
141 }, nil
142 case "/v2/test/manifests/" + invalidDigest:
143 return &http.Response{}, fmt.Errorf(errMsg)
144 case "v2/test/manifest/" + validDigest2:
145 return &http.Response{
146 StatusCode: http.StatusOK,
147 Body: io.NopCloser(bytes.NewReader([]byte(validDigest2))),
148 Header: map[string][]string{
149 "Content-Type": {joseTag},
150 "Docker-Content-Digest": {validDigestWithAlgo2},
151 },
152 }, nil
153 case "/v2/test/blobs/uploads/":
154 switch req.Host {
155 case validRegistry:
156 return &http.Response{
157 StatusCode: http.StatusAccepted,
158 Body: io.NopCloser(bytes.NewReader([]byte(msg))),
159 Request: &http.Request{
160 Header: map[string][]string{},
161 },
162 Header: map[string][]string{
163 "Location": {"test"},
164 },
165 }, nil
166 default:
167 return &http.Response{}, fmt.Errorf(msg)
168 }
169 case "/v2/test/referrers/":
170 return &http.Response{
171 StatusCode: http.StatusOK,
172 Header: http.Header{
173 "Content-Type": []string{ocispec.MediaTypeImageIndex},
174 },
175 Body: io.NopCloser(bytes.NewReader([]byte(validPage))),
176 Request: &http.Request{
177 Method: "GET",
178 URL: &url.URL{Path: "/v2/test/referrers/"},
179 },
180 }, nil
181 case "/v2/test/referrers/" + validDigestWithAlgo:
182 return &http.Response{
183 StatusCode: http.StatusOK,
184 Header: http.Header{
185 "Content-Type": []string{ocispec.MediaTypeImageIndex},
186 },
187 Body: io.NopCloser(bytes.NewReader([]byte(validPage))),
188 Request: &http.Request{
189 Method: "GET",
190 URL: &url.URL{Path: "/v2/test/referrers/" + validDigestWithAlgo},
191 },
192 }, nil
193 case "/v2/test/referrers/" + zeroDigest:
194 return &http.Response{
195 StatusCode: http.StatusOK,
196 Header: http.Header{
197 "Content-Type": []string{ocispec.MediaTypeImageIndex},
198 },
199 Body: io.NopCloser(bytes.NewReader([]byte(validPageImage))),
200 Request: &http.Request{
201 Method: "GET",
202 URL: &url.URL{Path: "/v2/test/referrers/" + zeroDigest},
203 },
204 }, nil
205 case validRepo:
206 return &http.Response{
207 StatusCode: http.StatusCreated,
208 Body: io.NopCloser(bytes.NewReader([]byte(msg))),
209 }, nil
210 default:
211 _, digest, found := strings.Cut(req.URL.Path, "/v2/test/manifests/")
212 if found && !slices.Contains(validDigestWithAlgoSlice, digest) {
213 resp := &http.Response{
214 StatusCode: http.StatusCreated,
215 Body: io.NopCloser(bytes.NewReader([]byte(msg))),
216 Header: http.Header{
217 "Content-Type": []string{joseTag},
218 "Oci-Subject": []string{validDigestWithAlgo},
219 },
220 }
221 return resp, nil
222 }
223 return &http.Response{}, fmt.Errorf(errMsg)
224 }
225 }
226
227 func TestResolve(t *testing.T) {
228 tests := []struct {
229 name string
230 args args
231 expect ocispec.Descriptor
232 expectErr bool
233 }{
234 {
235 name: "failed to resolve",
236 args: args{
237 ctx: context.Background(),
238 reference: invalidReference,
239 remoteClient: mockRemoteClient{},
240 plainHttp: false,
241 },
242 expect: ocispec.Descriptor{},
243 expectErr: true,
244 },
245 }
246
247 for _, tt := range tests {
248 t.Run(tt.name, func(t *testing.T) {
249 args := tt.args
250 ref, _ := registry.ParseReference(args.reference)
251 client := newRepositoryClient(args.remoteClient, ref, args.plainHttp)
252 res, err := client.Resolve(args.ctx, args.reference)
253 if (err != nil) != tt.expectErr {
254 t.Errorf("error = %v, expectErr = %v", err, tt.expectErr)
255 }
256 if !reflect.DeepEqual(res, tt.expect) {
257 t.Errorf("expect %+v, got %+v", tt.expect, res)
258 }
259 })
260 }
261 }
262
263 func TestFetchSignatureBlob(t *testing.T) {
264 tests := []struct {
265 name string
266 args args
267 expect []byte
268 expectErr bool
269 }{
270 {
271 name: "failed to resolve",
272 expect: nil,
273 expectErr: true,
274 args: args{
275 ctx: context.Background(),
276 reference: validReference,
277 remoteClient: mockRemoteClient{},
278 plainHttp: false,
279 signatureManifestDesc: ocispec.Descriptor{
280 MediaType: artifactspec.MediaTypeArtifactManifest,
281 Digest: digest.Digest(invalidDigest),
282 },
283 },
284 },
285 {
286 name: "exceed max blob size",
287 expect: nil,
288 expectErr: true,
289 args: args{
290 ctx: context.Background(),
291 reference: validReference,
292 remoteClient: mockRemoteClient{},
293 plainHttp: false,
294 signatureManifestDesc: ocispec.Descriptor{
295 MediaType: artifactspec.MediaTypeArtifactManifest,
296 Digest: digest.Digest(validDigestWithAlgo2),
297 },
298 },
299 },
300 }
301
302 for _, tt := range tests {
303 t.Run(tt.name, func(t *testing.T) {
304 args := tt.args
305 ref, _ := registry.ParseReference(args.reference)
306 client := newRepositoryClient(args.remoteClient, ref, args.plainHttp)
307 res, _, err := client.FetchSignatureBlob(args.ctx, args.signatureManifestDesc)
308 if (err != nil) != tt.expectErr {
309 t.Errorf("error = %v, expectErr = %v", err, tt.expectErr)
310 }
311 if !reflect.DeepEqual(res, tt.expect) {
312 t.Errorf("expect %+v, got %+v", tt.expect, res)
313 }
314 })
315 }
316 }
317
318 func TestListSignatures(t *testing.T) {
319 tests := []struct {
320 name string
321 args args
322 expect []interface{}
323 expectErr bool
324 }{
325 {
326 name: "successfully fetch content",
327 expectErr: false,
328 expect: nil,
329 args: args{
330 ctx: context.Background(),
331 reference: validReference,
332 remoteClient: mockRemoteClient{},
333 plainHttp: false,
334 artifactManifestDesc: ocispec.Descriptor{
335 MediaType: "application/vnd.oci.image.manifest.v1+json",
336 Digest: validDigestWithAlgo,
337 Size: 481,
338 },
339 },
340 },
341 }
342 for _, tt := range tests {
343 t.Run(tt.name, func(t *testing.T) {
344 args := tt.args
345 ref, err := registry.ParseReference(args.reference)
346 if err != nil {
347 t.Fatal(err)
348 }
349 client := newRepositoryClient(args.remoteClient, ref, args.plainHttp)
350
351 err = client.ListSignatures(args.ctx, args.artifactManifestDesc, func(signatureManifests []ocispec.Descriptor) error {
352 if len(signatureManifests) != 1 {
353 return fmt.Errorf("length of signatureManifests expected 1, got %d", len(signatureManifests))
354 }
355 for _, sigManifest := range signatureManifests {
356 sigManifestDigest := sigManifest.Digest.String()
357 if sigManifestDigest != validPageDigest {
358 return fmt.Errorf("signature manifest digest expected: %s, got %s", validPageDigest, sigManifestDigest)
359 }
360 }
361 return nil
362 })
363 if (err != nil) != tt.expectErr {
364 t.Errorf("error = %v, expectErr = %v", err, tt.expectErr)
365 }
366 })
367 }
368 }
369
370 func TestPushSignature(t *testing.T) {
371 signature, err := os.ReadFile(signaturePath)
372 if err != nil {
373 t.Fatalf("failed to read signature: %v", err)
374 }
375 tests := []struct {
376 name string
377 args args
378 expectDes ocispec.Descriptor
379 expectManifest ocispec.Descriptor
380 expectErr bool
381 }{
382 {
383 name: "failed to upload signature",
384 expectErr: true,
385 args: args{
386 reference: referenceWithInvalidHost,
387 signatureMediaType: joseTag,
388 signature: signature,
389 ctx: context.Background(),
390 remoteClient: mockRemoteClient{},
391 },
392 },
393 {
394 name: "successfully uploaded signature manifest",
395 expectErr: false,
396 args: args{
397 reference: validReference,
398 signatureMediaType: joseTag,
399 signature: signature,
400 ctx: context.Background(),
401 remoteClient: mockRemoteClient{},
402 subjectManifest: ocispec.Descriptor{
403 MediaType: "application/vnd.oci.image.manifest.v1+json",
404 Digest: validDigestWithAlgo,
405 Size: 481,
406 },
407 annotations: map[string]string{
408 envelope.AnnotationX509ChainThumbprint: "[\"9f5f5aecee24b5cfdc7a91f6d5ac5c3a5348feb17c934d403f59ac251549ea0d\"]",
409 },
410 },
411 },
412 }
413 for _, tt := range tests {
414 t.Run(tt.name, func(t *testing.T) {
415 args := tt.args
416 ref, _ := registry.ParseReference(args.reference)
417 client := newRepositoryClient(args.remoteClient, ref, args.plainHttp)
418
419 _, _, err := client.PushSignature(args.ctx, args.signatureMediaType, args.signature, args.subjectManifest, args.annotations)
420 if (err != nil) != tt.expectErr {
421 t.Errorf("error = %v, expectErr = %v", err, tt.expectErr)
422 }
423 })
424 }
425 }
426
427 func TestPushSignatureImageManifest(t *testing.T) {
428 ref, err := registry.ParseReference(validReference)
429 if err != nil {
430 t.Fatalf("failed to parse reference")
431 }
432 client := newRepositoryClientWithImageManifest(mockRemoteClient{}, ref, false)
433 signature, err := os.ReadFile(signaturePath)
434 if err != nil {
435 t.Fatalf("failed to read signature: %v", err)
436 }
437 _, manifestDesc, err := client.PushSignature(context.Background(), joseTag, signature, ocispec.Descriptor{}, annotations)
438 if err != nil {
439 t.Fatalf("failed to push signature")
440 }
441 if manifestDesc.MediaType != ocispec.MediaTypeImageManifest {
442 t.Errorf("expect manifestDesc.MediaType: %v, got %v", ocispec.MediaTypeImageManifest, manifestDesc.MediaType)
443 }
444 }
445
446 // newRepositoryClient creates a new repository client
447 func newRepositoryClient(client remote.Client, ref registry.Reference, plainHTTP bool) *repositoryClient {
448 repo := remote.Repository{
449 Client: client,
450 Reference: ref,
451 PlainHTTP: plainHTTP,
452 }
453 return &repositoryClient{
454 GraphTarget: &repo,
455 }
456 }
457
458 // newRepositoryClientWithImageManifest creates a new repository client for
459 // pushing OCI image manifest
460 func newRepositoryClientWithImageManifest(client remote.Client, ref registry.Reference, plainHTTP bool) *repositoryClient {
461 return &repositoryClient{
462 GraphTarget: &remote.Repository{
463 Client: client,
464 Reference: ref,
465 PlainHTTP: plainHTTP,
466 },
467 }
468 }
469
470 var (
471 reference = "sha256:19dbd2e48e921426ee8ace4dc892edfb2ecdc1d1a72d5416c83670c30acecef0"
472 expectedTargetDesc = ocispec.Descriptor{
473 MediaType: "application/vnd.oci.image.manifest.v1+json",
474 Digest: "sha256:19dbd2e48e921426ee8ace4dc892edfb2ecdc1d1a72d5416c83670c30acecef0",
475 Size: 481,
476 }
477 annotations = map[string]string{
478 envelope.AnnotationX509ChainThumbprint: "[\"9f5f5aecee24b5cfdc7a91f6d5ac5c3a5348feb17c934d403f59ac251549ea0d\"]",
479 ocispec.AnnotationCreated: "2023-03-14T08:10:02Z",
480 }
481 expectedSignatureManifestDesc = ocispec.Descriptor{
482 MediaType: "application/vnd.oci.image.manifest.v1+json",
483 Digest: "sha256:baeaea44f55c94499b7e082bd3c98ad5ec40fdf23ef89cdf4e5db6b83e4f18f5",
484 Size: 728,
485 }
486 expectedSignatureBlobDesc = ocispec.Descriptor{
487 MediaType: joseTag,
488 Digest: "sha256:586c5e0f341d7d07e835a06b7c9f21c21fff4f4a85933079e5859f99ba0ad02d",
489 Size: 2078,
490 }
491 )
492
493 func TestOciLayoutRepositoryPushAndFetch(t *testing.T) {
494 // create a temp OCI layout
495 ociLayoutTestdataPath, err := filepath.Abs(filepath.Join("..", "internal", "testdata", "oci-layout"))
496 if err != nil {
497 t.Fatalf("failed to get oci layout path: %v", err)
498 }
499
500 newOCILayoutPath := t.TempDir()
501 if err := ocilayout.Copy(ociLayoutTestdataPath, newOCILayoutPath, "v2"); err != nil {
502 t.Fatalf("failed to create temp oci layout: %v", err)
503 }
504 repo, err := NewOCIRepository(newOCILayoutPath, RepositoryOptions{})
505 if err != nil {
506 t.Fatalf("failed to create oci.Store as registry.Repository: %v", err)
507 }
508
509 // test resolve
510 targetDesc, err := repo.Resolve(context.Background(), reference)
511 if err != nil {
512 t.Fatalf("failed to resolve reference: %v", err)
513 }
514 if !content.Equal(targetDesc, expectedTargetDesc) {
515 t.Fatalf("failed to resolve reference. expected descriptor: %v, but got: %v", expectedTargetDesc, targetDesc)
516 }
517
518 t.Run("oci layout push", func(t *testing.T) {
519 signature, err := os.ReadFile(signaturePath)
520 if err != nil {
521 t.Fatalf("failed to read signature: %v", err)
522 }
523 _, signatureManifestDesc, err := repo.PushSignature(context.Background(), joseTag, signature, targetDesc, annotations)
524 if err != nil {
525 t.Fatalf("failed to push signature: %v", err)
526 }
527 if !content.Equal(expectedSignatureManifestDesc, signatureManifestDesc) {
528 t.Fatalf("expected desc: %v, got: %v", expectedSignatureManifestDesc, signatureManifestDesc)
529 }
530 expectedAnnotations := map[string]string{
531 envelope.AnnotationX509ChainThumbprint: "[\"9f5f5aecee24b5cfdc7a91f6d5ac5c3a5348feb17c934d403f59ac251549ea0d\"]",
532 ocispec.AnnotationCreated: "2023-03-14T08:10:02Z",
533 }
534 if !reflect.DeepEqual(expectedAnnotations, signatureManifestDesc.Annotations) {
535 t.Fatalf("expected annotations: %v, but got: %v", expectedAnnotations, signatureManifestDesc.Annotations)
536 }
537 })
538
539 t.Run("oci layout fetch", func(t *testing.T) {
540 err = repo.ListSignatures(context.Background(), targetDesc, func(signatureManifests []ocispec.Descriptor) error {
541 if len(signatureManifests) == 0 {
542 return fmt.Errorf("expected to find signature in the OCI layout folder, but got none")
543 }
544 var found bool
545 for _, sigManifestDesc := range signatureManifests {
546 if !content.Equal(sigManifestDesc, expectedSignatureManifestDesc) {
547 continue
548 }
549 _, sigDesc, err := repo.FetchSignatureBlob(context.Background(), sigManifestDesc)
550 if err != nil {
551 return fmt.Errorf("failed to fetch blob: %w", err)
552 }
553 if !content.Equal(expectedSignatureBlobDesc, sigDesc) {
554 return fmt.Errorf("expected to get signature blob desc: %v, got: %v", expectedSignatureBlobDesc, sigDesc)
555 }
556 found = true
557 }
558 if !found {
559 return fmt.Errorf("expected to find the signature with manifest desc: %v, but failed", expectedSignatureManifestDesc)
560 }
561 return nil
562 })
563 if err != nil {
564 t.Fatal(err)
565 }
566 })
567 }
568
569 func TestNewRepository(t *testing.T) {
570 target, err := oci.New(t.TempDir())
571 if err != nil {
572 t.Fatalf("failed to create oci.Store as registry.Repository: %v", err)
573 }
574 repo := NewRepository(target)
575 if repo == nil {
576 t.Fatalf("failed to create repository")
577 }
578 repoClient, ok := repo.(*repositoryClient)
579 if !ok {
580 t.Fatalf("failed to create repositoryClient")
581 }
582 if target != repoClient.GraphTarget {
583 t.Fatalf("expected target: %v, got: %v", target, repoClient.GraphTarget)
584 }
585 }
586
587 func TestNewOCIRepositoryFailed(t *testing.T) {
588 t.Run("os stat failed", func(t *testing.T) {
589 _, err := NewOCIRepository("invalid-path", RepositoryOptions{})
590 if err == nil {
591 t.Fatalf("expected to fail with invalid path")
592 }
593 })
594
595 t.Run("path is regular file", func(t *testing.T) {
596 // create a regular file in the temp dir
597 filePath := filepath.Join(t.TempDir(), "file")
598 file, err := os.Create(filePath)
599 if err != nil {
600 t.Fatalf("failed to create file: %v", err)
601 }
602 file.Close()
603
604 _, err = NewOCIRepository(filePath, RepositoryOptions{})
605 if err == nil {
606 t.Fatalf("expected to fail with regular file")
607 }
608 })
609
610 t.Run("no permission to create new path", func(t *testing.T) {
611 if runtime.GOOS == "windows" {
612 t.Skip("skipping test on Windows")
613 }
614 // create a directory in the temp dir
615 dirPath := filepath.Join(t.TempDir(), "dir")
616 err := os.Mkdir(dirPath, 0000)
617 if err != nil {
618 t.Fatalf("failed to create dir: %v", err)
619 }
620
621 _, err = NewOCIRepository(dirPath, RepositoryOptions{})
622 if err == nil {
623 t.Fatalf("expected to fail with no permission to create new path")
624 }
625 })
626 }
627
628 // testStorage implements content.ReadOnlyGraphStorage
629 type testStorage struct {
630 store *memory.Store
631 FetchError error
632 FetchContent []byte
633 PredecessorsError error
634 PredecessorsDesc []ocispec.Descriptor
635 }
636
637 func (s *testStorage) Push(ctx context.Context, expected ocispec.Descriptor, reader io.Reader) error {
638 return s.store.Push(ctx, expected, reader)
639 }
640
641 func (s *testStorage) Fetch(ctx context.Context, target ocispec.Descriptor) (io.ReadCloser, error) {
642 if s.FetchError != nil {
643 return nil, s.FetchError
644 }
645 return io.NopCloser(bytes.NewReader(s.FetchContent)), nil
646 }
647
648 func (s *testStorage) Exists(ctx context.Context, target ocispec.Descriptor) (bool, error) {
649 return s.store.Exists(ctx, target)
650 }
651
652 func (s *testStorage) Predecessors(ctx context.Context, node ocispec.Descriptor) ([]ocispec.Descriptor, error) {
653 if s.PredecessorsError != nil {
654 return nil, s.PredecessorsError
655 }
656 return s.PredecessorsDesc, nil
657 }
658
659 func TestSignatureReferrers(t *testing.T) {
660 t.Run("get predecessors failed", func(t *testing.T) {
661 store := &testStorage{
662 store: &memory.Store{},
663 PredecessorsError: fmt.Errorf("failed to get predecessors"),
664 }
665 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{})
666 if err == nil {
667 t.Fatalf("expected to fail with getting predecessors")
668 }
669 })
670
671 t.Run("artifact manifest exceds max blob size", func(t *testing.T) {
672 store := &testStorage{
673 store: &memory.Store{},
674 PredecessorsDesc: []ocispec.Descriptor{
675 {
676 Digest: validDigestWithAlgo2,
677 MediaType: "application/vnd.oci.artifact.manifest.v1+json",
678 Size: 4*1024*1024 + 1,
679 },
680 },
681 }
682 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
683 Digest: validDigestWithAlgo2,
684 })
685 if err == nil {
686 t.Fatalf("expected to fail with artifact manifest exceds max blob size")
687 }
688 })
689
690 t.Run("image manifest exceds max blob size", func(t *testing.T) {
691 store := &testStorage{
692 store: &memory.Store{},
693 PredecessorsDesc: []ocispec.Descriptor{
694 {
695 Digest: validDigestWithAlgo2,
696 MediaType: "application/vnd.oci.image.manifest.v1+json",
697 Size: 4*1024*1024 + 1,
698 },
699 },
700 }
701 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
702 Digest: validDigestWithAlgo2,
703 })
704 if err == nil {
705 t.Fatalf("expected to fail with image manifest exceds max blob size")
706 }
707 })
708
709 t.Run("artifact manifest fetchAll failed", func(t *testing.T) {
710 store := &testStorage{
711 store: &memory.Store{},
712 PredecessorsDesc: []ocispec.Descriptor{
713 {
714 Digest: validDigestWithAlgo,
715 MediaType: "application/vnd.oci.artifact.manifest.v1+json",
716 Size: 481,
717 },
718 },
719 FetchError: fmt.Errorf("failed to fetch all"),
720 }
721 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
722 Digest: validDigestWithAlgo,
723 })
724 if err == nil {
725 t.Fatalf("expected to fail with fetchAll failed")
726 }
727 })
728
729 t.Run("image manifest fetchAll failed", func(t *testing.T) {
730 store := &testStorage{
731 store: &memory.Store{},
732 PredecessorsDesc: []ocispec.Descriptor{
733 {
734 Digest: validDigestWithAlgo,
735 MediaType: "application/vnd.oci.image.manifest.v1+json",
736 Size: 481,
737 },
738 },
739 FetchError: fmt.Errorf("failed to fetch all"),
740 }
741 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
742 Digest: validDigestWithAlgo,
743 })
744 if err == nil {
745 t.Fatalf("expected to fail with fetchAll failed")
746 }
747 })
748
749 t.Run("artifact manifest marshal failed", func(t *testing.T) {
750 store := &testStorage{
751 store: &memory.Store{},
752 PredecessorsDesc: []ocispec.Descriptor{
753 {
754 Digest: "sha256:24aafc739daae02bcd33471a1b28bcfaaef0bb5e530ef44cd4e5d2445e606690",
755 MediaType: "application/vnd.oci.artifact.manifest.v1+json",
756 Size: 15,
757 },
758 },
759 FetchContent: []byte("invalid content"),
760 }
761 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
762 Digest: "sha256:24aafc739daae02bcd33471a1b28bcfaaef0bb5e530ef44cd4e5d2445e606690",
763 })
764 if err == nil {
765 t.Fatalf("expected to fail with marshal failed")
766 }
767 })
768
769 t.Run("image manifest marshal failed", func(t *testing.T) {
770 store := &testStorage{
771 store: &memory.Store{},
772 PredecessorsDesc: []ocispec.Descriptor{
773 {
774 Digest: "sha256:24aafc739daae02bcd33471a1b28bcfaaef0bb5e530ef44cd4e5d2445e606690",
775 MediaType: "application/vnd.oci.image.manifest.v1+json",
776 Size: 15,
777 },
778 },
779 FetchContent: []byte("invalid content"),
780 }
781 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
782 Digest: "sha256:24aafc739daae02bcd33471a1b28bcfaaef0bb5e530ef44cd4e5d2445e606690",
783 })
784 if err == nil {
785 t.Fatalf("expected to fail with marshal failed")
786 }
787 })
788
789 t.Run("no valid artifact manifest", func(t *testing.T) {
790 store := &testStorage{
791 store: &memory.Store{},
792 PredecessorsDesc: []ocispec.Descriptor{
793 {
794 Digest: "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
795 MediaType: "application/vnd.oci.artifact.manifest.v1+json",
796 Size: 2,
797 },
798 },
799 FetchContent: []byte("{}"),
800 }
801 descriptors, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
802 Digest: "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
803 })
804
805 if err != nil {
806 t.Fatalf("failed to get referrers: %v", err)
807 }
808 if len(descriptors) != 0 {
809 t.Fatalf("expected to get no referrers, but got: %v", descriptors)
810 }
811 })
812
813 t.Run("no valid image manifest", func(t *testing.T) {
814 store := &testStorage{
815 store: &memory.Store{},
816 PredecessorsDesc: []ocispec.Descriptor{
817 {
818 Digest: "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
819 MediaType: "application/vnd.oci.image.manifest.v1+json",
820 Size: 2,
821 },
822 },
823 FetchContent: []byte("{}"),
824 }
825 descriptors, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
826 Digest: "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
827 })
828
829 if err != nil {
830 t.Fatalf("failed to get referrers: %v", err)
831 }
832 if len(descriptors) != 0 {
833 t.Fatalf("expected to get no referrers, but got: %v", descriptors)
834 }
835 })
836 }