Debian Codegraph @

registry/repository_test.go

raw ◀ ▶
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: req,
160 Header: map[string][]string{
•161 "Location": {"/v2/test/blobs/uploads/test"},
162 },
163 }, nil
164 default:
165 return &http.Response{}, fmt.Errorf(msg)
166 }
167 case "/v2/test/referrers/":
168 return &http.Response{
169 StatusCode: http.StatusOK,
170 Header: http.Header{
171 "Content-Type": []string{ocispec.MediaTypeImageIndex},
172 },
173 Body: io.NopCloser(bytes.NewReader([]byte(validPage))),
174 Request: &http.Request{
175 Method: "GET",
176 URL: &url.URL{Path: "/v2/test/referrers/"},
177 },
178 }, nil
179 case "/v2/test/referrers/" + validDigestWithAlgo:
180 return &http.Response{
181 StatusCode: http.StatusOK,
182 Header: http.Header{
183 "Content-Type": []string{ocispec.MediaTypeImageIndex},
184 },
185 Body: io.NopCloser(bytes.NewReader([]byte(validPage))),
186 Request: &http.Request{
187 Method: "GET",
188 URL: &url.URL{Path: "/v2/test/referrers/" + validDigestWithAlgo},
189 },
190 }, nil
191 case "/v2/test/referrers/" + zeroDigest:
192 return &http.Response{
193 StatusCode: http.StatusOK,
194 Header: http.Header{
195 "Content-Type": []string{ocispec.MediaTypeImageIndex},
196 },
197 Body: io.NopCloser(bytes.NewReader([]byte(validPageImage))),
198 Request: &http.Request{
199 Method: "GET",
200 URL: &url.URL{Path: "/v2/test/referrers/" + zeroDigest},
201 },
202 }, nil
•203 case "/v2/test/blobs/uploads/test", validRepo:
204 return &http.Response{
205 StatusCode: http.StatusCreated,
206 Body: io.NopCloser(bytes.NewReader([]byte(msg))),
207 }, nil
208 default:
209 _, digest, found := strings.Cut(req.URL.Path, "/v2/test/manifests/")
210 if found && !slices.Contains(validDigestWithAlgoSlice, digest) {
211 resp := &http.Response{
212 StatusCode: http.StatusCreated,
213 Body: io.NopCloser(bytes.NewReader([]byte(msg))),
214 Header: http.Header{
215 "Content-Type": []string{joseTag},
216 "Oci-Subject": []string{validDigestWithAlgo},
217 },
218 }
219 return resp, nil
220 }
221 return &http.Response{}, fmt.Errorf(errMsg)
222 }
223 }
224
225 func TestResolve(t *testing.T) {
226 tests := []struct {
227 name string
228 args args
229 expect ocispec.Descriptor
230 expectErr bool
231 }{
232 {
233 name: "failed to resolve",
234 args: args{
235 ctx: context.Background(),
236 reference: invalidReference,
237 remoteClient: mockRemoteClient{},
238 plainHttp: false,
239 },
240 expect: ocispec.Descriptor{},
241 expectErr: true,
242 },
243 }
244
245 for _, tt := range tests {
246 t.Run(tt.name, func(t *testing.T) {
247 args := tt.args
248 ref, _ := registry.ParseReference(args.reference)
249 client := newRepositoryClient(args.remoteClient, ref, args.plainHttp)
250 res, err := client.Resolve(args.ctx, args.reference)
251 if (err != nil) != tt.expectErr {
252 t.Errorf("error = %v, expectErr = %v", err, tt.expectErr)
253 }
254 if !reflect.DeepEqual(res, tt.expect) {
255 t.Errorf("expect %+v, got %+v", tt.expect, res)
256 }
257 })
258 }
259 }
260
261 func TestFetchSignatureBlob(t *testing.T) {
262 tests := []struct {
263 name string
264 args args
265 expect []byte
266 expectErr bool
267 }{
268 {
269 name: "failed to resolve",
270 expect: nil,
271 expectErr: true,
272 args: args{
273 ctx: context.Background(),
274 reference: validReference,
275 remoteClient: mockRemoteClient{},
276 plainHttp: false,
277 signatureManifestDesc: ocispec.Descriptor{
278 MediaType: artifactspec.MediaTypeArtifactManifest,
279 Digest: digest.Digest(invalidDigest),
280 },
281 },
282 },
283 {
284 name: "exceed max blob size",
285 expect: nil,
286 expectErr: true,
287 args: args{
288 ctx: context.Background(),
289 reference: validReference,
290 remoteClient: mockRemoteClient{},
291 plainHttp: false,
292 signatureManifestDesc: ocispec.Descriptor{
293 MediaType: artifactspec.MediaTypeArtifactManifest,
294 Digest: digest.Digest(validDigestWithAlgo2),
295 },
296 },
297 },
298 }
299
300 for _, tt := range tests {
301 t.Run(tt.name, func(t *testing.T) {
302 args := tt.args
303 ref, _ := registry.ParseReference(args.reference)
304 client := newRepositoryClient(args.remoteClient, ref, args.plainHttp)
305 res, _, err := client.FetchSignatureBlob(args.ctx, args.signatureManifestDesc)
306 if (err != nil) != tt.expectErr {
307 t.Errorf("error = %v, expectErr = %v", err, tt.expectErr)
308 }
309 if !reflect.DeepEqual(res, tt.expect) {
310 t.Errorf("expect %+v, got %+v", tt.expect, res)
311 }
312 })
313 }
314 }
315
316 func TestListSignatures(t *testing.T) {
317 tests := []struct {
318 name string
319 args args
320 expect []interface{}
321 expectErr bool
322 }{
323 {
324 name: "successfully fetch content",
325 expectErr: false,
326 expect: nil,
327 args: args{
328 ctx: context.Background(),
329 reference: validReference,
330 remoteClient: mockRemoteClient{},
331 plainHttp: false,
332 artifactManifestDesc: ocispec.Descriptor{
333 MediaType: "application/vnd.oci.image.manifest.v1+json",
334 Digest: validDigestWithAlgo,
335 Size: 481,
336 },
337 },
338 },
339 }
340 for _, tt := range tests {
341 t.Run(tt.name, func(t *testing.T) {
342 args := tt.args
343 ref, err := registry.ParseReference(args.reference)
344 if err != nil {
345 t.Fatal(err)
346 }
347 client := newRepositoryClient(args.remoteClient, ref, args.plainHttp)
348
349 err = client.ListSignatures(args.ctx, args.artifactManifestDesc, func(signatureManifests []ocispec.Descriptor) error {
350 if len(signatureManifests) != 1 {
351 return fmt.Errorf("length of signatureManifests expected 1, got %d", len(signatureManifests))
352 }
353 for _, sigManifest := range signatureManifests {
354 sigManifestDigest := sigManifest.Digest.String()
355 if sigManifestDigest != validPageDigest {
356 return fmt.Errorf("signature manifest digest expected: %s, got %s", validPageDigest, sigManifestDigest)
357 }
358 }
359 return nil
360 })
361 if (err != nil) != tt.expectErr {
362 t.Errorf("error = %v, expectErr = %v", err, tt.expectErr)
363 }
364 })
365 }
366 }
367
368 func TestPushSignature(t *testing.T) {
369 signature, err := os.ReadFile(signaturePath)
370 if err != nil {
371 t.Fatalf("failed to read signature: %v", err)
372 }
373 tests := []struct {
374 name string
375 args args
376 expectDes ocispec.Descriptor
377 expectManifest ocispec.Descriptor
378 expectErr bool
379 }{
380 {
381 name: "failed to upload signature",
382 expectErr: true,
383 args: args{
384 reference: referenceWithInvalidHost,
385 signatureMediaType: joseTag,
386 signature: signature,
387 ctx: context.Background(),
388 remoteClient: mockRemoteClient{},
389 },
390 },
391 {
392 name: "successfully uploaded signature manifest",
393 expectErr: false,
394 args: args{
395 reference: validReference,
396 signatureMediaType: joseTag,
397 signature: signature,
398 ctx: context.Background(),
399 remoteClient: mockRemoteClient{},
400 subjectManifest: ocispec.Descriptor{
401 MediaType: "application/vnd.oci.image.manifest.v1+json",
402 Digest: validDigestWithAlgo,
403 Size: 481,
404 },
405 annotations: map[string]string{
406 envelope.AnnotationX509ChainThumbprint: "[\"9f5f5aecee24b5cfdc7a91f6d5ac5c3a5348feb17c934d403f59ac251549ea0d\"]",
407 },
408 },
409 },
410 }
411 for _, tt := range tests {
412 t.Run(tt.name, func(t *testing.T) {
413 args := tt.args
414 ref, _ := registry.ParseReference(args.reference)
415 client := newRepositoryClient(args.remoteClient, ref, args.plainHttp)
416
417 _, _, err := client.PushSignature(args.ctx, args.signatureMediaType, args.signature, args.subjectManifest, args.annotations)
418 if (err != nil) != tt.expectErr {
419 t.Errorf("error = %v, expectErr = %v", err, tt.expectErr)
420 }
421 })
422 }
423 }
424
425 func TestPushSignatureImageManifest(t *testing.T) {
426 ref, err := registry.ParseReference(validReference)
427 if err != nil {
428 t.Fatalf("failed to parse reference")
429 }
430 client := newRepositoryClientWithImageManifest(mockRemoteClient{}, ref, false)
431 signature, err := os.ReadFile(signaturePath)
432 if err != nil {
433 t.Fatalf("failed to read signature: %v", err)
434 }
435 _, manifestDesc, err := client.PushSignature(context.Background(), joseTag, signature, ocispec.Descriptor{}, annotations)
436 if err != nil {
437 t.Fatalf("failed to push signature")
438 }
439 if manifestDesc.MediaType != ocispec.MediaTypeImageManifest {
440 t.Errorf("expect manifestDesc.MediaType: %v, got %v", ocispec.MediaTypeImageManifest, manifestDesc.MediaType)
441 }
442 }
443
444 // newRepositoryClient creates a new repository client
445 func newRepositoryClient(client remote.Client, ref registry.Reference, plainHTTP bool) *repositoryClient {
446 repo := remote.Repository{
447 Client: client,
448 Reference: ref,
449 PlainHTTP: plainHTTP,
450 }
451 return &repositoryClient{
452 GraphTarget: &repo,
453 }
454 }
455
456 // newRepositoryClientWithImageManifest creates a new repository client for
457 // pushing OCI image manifest
458 func newRepositoryClientWithImageManifest(client remote.Client, ref registry.Reference, plainHTTP bool) *repositoryClient {
459 return &repositoryClient{
460 GraphTarget: &remote.Repository{
461 Client: client,
462 Reference: ref,
463 PlainHTTP: plainHTTP,
464 },
465 }
466 }
467
468 var (
469 reference = "sha256:19dbd2e48e921426ee8ace4dc892edfb2ecdc1d1a72d5416c83670c30acecef0"
470 expectedTargetDesc = ocispec.Descriptor{
471 MediaType: "application/vnd.oci.image.manifest.v1+json",
472 Digest: "sha256:19dbd2e48e921426ee8ace4dc892edfb2ecdc1d1a72d5416c83670c30acecef0",
473 Size: 481,
474 }
475 annotations = map[string]string{
476 envelope.AnnotationX509ChainThumbprint: "[\"9f5f5aecee24b5cfdc7a91f6d5ac5c3a5348feb17c934d403f59ac251549ea0d\"]",
477 ocispec.AnnotationCreated: "2023-03-14T08:10:02Z",
478 }
479 expectedSignatureManifestDesc = ocispec.Descriptor{
480 MediaType: "application/vnd.oci.image.manifest.v1+json",
481 Digest: "sha256:baeaea44f55c94499b7e082bd3c98ad5ec40fdf23ef89cdf4e5db6b83e4f18f5",
482 Size: 728,
483 }
484 expectedSignatureBlobDesc = ocispec.Descriptor{
485 MediaType: joseTag,
486 Digest: "sha256:586c5e0f341d7d07e835a06b7c9f21c21fff4f4a85933079e5859f99ba0ad02d",
487 Size: 2078,
488 }
489 )
490
491 func TestOciLayoutRepositoryPushAndFetch(t *testing.T) {
492 // create a temp OCI layout
493 ociLayoutTestdataPath, err := filepath.Abs(filepath.Join("..", "internal", "testdata", "oci-layout"))
494 if err != nil {
495 t.Fatalf("failed to get oci layout path: %v", err)
496 }
497
498 newOCILayoutPath := t.TempDir()
499 if err := ocilayout.Copy(ociLayoutTestdataPath, newOCILayoutPath, "v2"); err != nil {
500 t.Fatalf("failed to create temp oci layout: %v", err)
501 }
502 repo, err := NewOCIRepository(newOCILayoutPath, RepositoryOptions{})
503 if err != nil {
504 t.Fatalf("failed to create oci.Store as registry.Repository: %v", err)
505 }
506
507 // test resolve
508 targetDesc, err := repo.Resolve(context.Background(), reference)
509 if err != nil {
510 t.Fatalf("failed to resolve reference: %v", err)
511 }
512 if !content.Equal(targetDesc, expectedTargetDesc) {
513 t.Fatalf("failed to resolve reference. expected descriptor: %v, but got: %v", expectedTargetDesc, targetDesc)
514 }
515
516 t.Run("oci layout push", func(t *testing.T) {
517 signature, err := os.ReadFile(signaturePath)
518 if err != nil {
519 t.Fatalf("failed to read signature: %v", err)
520 }
521 _, signatureManifestDesc, err := repo.PushSignature(context.Background(), joseTag, signature, targetDesc, annotations)
522 if err != nil {
523 t.Fatalf("failed to push signature: %v", err)
524 }
525 if !content.Equal(expectedSignatureManifestDesc, signatureManifestDesc) {
526 t.Fatalf("expected desc: %v, got: %v", expectedSignatureManifestDesc, signatureManifestDesc)
527 }
528 expectedAnnotations := map[string]string{
529 envelope.AnnotationX509ChainThumbprint: "[\"9f5f5aecee24b5cfdc7a91f6d5ac5c3a5348feb17c934d403f59ac251549ea0d\"]",
530 ocispec.AnnotationCreated: "2023-03-14T08:10:02Z",
531 }
532 if !reflect.DeepEqual(expectedAnnotations, signatureManifestDesc.Annotations) {
533 t.Fatalf("expected annotations: %v, but got: %v", expectedAnnotations, signatureManifestDesc.Annotations)
534 }
535 })
536
537 t.Run("oci layout fetch", func(t *testing.T) {
538 err = repo.ListSignatures(context.Background(), targetDesc, func(signatureManifests []ocispec.Descriptor) error {
539 if len(signatureManifests) == 0 {
540 return fmt.Errorf("expected to find signature in the OCI layout folder, but got none")
541 }
542 var found bool
543 for _, sigManifestDesc := range signatureManifests {
544 if !content.Equal(sigManifestDesc, expectedSignatureManifestDesc) {
545 continue
546 }
547 _, sigDesc, err := repo.FetchSignatureBlob(context.Background(), sigManifestDesc)
548 if err != nil {
549 return fmt.Errorf("failed to fetch blob: %w", err)
550 }
551 if !content.Equal(expectedSignatureBlobDesc, sigDesc) {
552 return fmt.Errorf("expected to get signature blob desc: %v, got: %v", expectedSignatureBlobDesc, sigDesc)
553 }
554 found = true
555 }
556 if !found {
557 return fmt.Errorf("expected to find the signature with manifest desc: %v, but failed", expectedSignatureManifestDesc)
558 }
559 return nil
560 })
561 if err != nil {
562 t.Fatal(err)
563 }
564 })
565 }
566
567 func TestNewRepository(t *testing.T) {
568 target, err := oci.New(t.TempDir())
569 if err != nil {
570 t.Fatalf("failed to create oci.Store as registry.Repository: %v", err)
571 }
572 repo := NewRepository(target)
573 if repo == nil {
574 t.Fatalf("failed to create repository")
575 }
576 repoClient, ok := repo.(*repositoryClient)
577 if !ok {
578 t.Fatalf("failed to create repositoryClient")
579 }
580 if target != repoClient.GraphTarget {
581 t.Fatalf("expected target: %v, got: %v", target, repoClient.GraphTarget)
582 }
583 }
584
585 func TestNewOCIRepositoryFailed(t *testing.T) {
586 t.Run("os stat failed", func(t *testing.T) {
587 _, err := NewOCIRepository("invalid-path", RepositoryOptions{})
588 if err == nil {
589 t.Fatalf("expected to fail with invalid path")
590 }
591 })
592
593 t.Run("path is regular file", func(t *testing.T) {
594 // create a regular file in the temp dir
595 filePath := filepath.Join(t.TempDir(), "file")
596 file, err := os.Create(filePath)
597 if err != nil {
598 t.Fatalf("failed to create file: %v", err)
599 }
600 file.Close()
601
602 _, err = NewOCIRepository(filePath, RepositoryOptions{})
603 if err == nil {
604 t.Fatalf("expected to fail with regular file")
605 }
606 })
607
608 t.Run("no permission to create new path", func(t *testing.T) {
609 if runtime.GOOS == "windows" {
610 t.Skip("skipping test on Windows")
611 }
612 // create a directory in the temp dir
613 dirPath := filepath.Join(t.TempDir(), "dir")
614 err := os.Mkdir(dirPath, 0000)
615 if err != nil {
616 t.Fatalf("failed to create dir: %v", err)
617 }
618
619 _, err = NewOCIRepository(dirPath, RepositoryOptions{})
620 if err == nil {
621 t.Fatalf("expected to fail with no permission to create new path")
622 }
623 })
624 }
625
626 // testStorage implements content.ReadOnlyGraphStorage
627 type testStorage struct {
628 store *memory.Store
629 FetchError error
630 FetchContent []byte
631 PredecessorsError error
632 PredecessorsDesc []ocispec.Descriptor
633 }
634
635 func (s *testStorage) Push(ctx context.Context, expected ocispec.Descriptor, reader io.Reader) error {
636 return s.store.Push(ctx, expected, reader)
637 }
638
639 func (s *testStorage) Fetch(ctx context.Context, target ocispec.Descriptor) (io.ReadCloser, error) {
640 if s.FetchError != nil {
641 return nil, s.FetchError
642 }
643 return io.NopCloser(bytes.NewReader(s.FetchContent)), nil
644 }
645
646 func (s *testStorage) Exists(ctx context.Context, target ocispec.Descriptor) (bool, error) {
647 return s.store.Exists(ctx, target)
648 }
649
650 func (s *testStorage) Predecessors(ctx context.Context, node ocispec.Descriptor) ([]ocispec.Descriptor, error) {
651 if s.PredecessorsError != nil {
652 return nil, s.PredecessorsError
653 }
654 return s.PredecessorsDesc, nil
655 }
656
657 func TestSignatureReferrers(t *testing.T) {
658 t.Run("get predecessors failed", func(t *testing.T) {
659 store := &testStorage{
660 store: &memory.Store{},
661 PredecessorsError: fmt.Errorf("failed to get predecessors"),
662 }
663 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{})
664 if err == nil {
665 t.Fatalf("expected to fail with getting predecessors")
666 }
667 })
668
669 t.Run("artifact manifest exceds max blob size", func(t *testing.T) {
670 store := &testStorage{
671 store: &memory.Store{},
672 PredecessorsDesc: []ocispec.Descriptor{
673 {
674 Digest: validDigestWithAlgo2,
675 MediaType: "application/vnd.oci.artifact.manifest.v1+json",
676 Size: 4*1024*1024 + 1,
677 },
678 },
679 }
680 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
681 Digest: validDigestWithAlgo2,
682 })
683 if err == nil {
684 t.Fatalf("expected to fail with artifact manifest exceds max blob size")
685 }
686 })
687
688 t.Run("image manifest exceds max blob size", func(t *testing.T) {
689 store := &testStorage{
690 store: &memory.Store{},
691 PredecessorsDesc: []ocispec.Descriptor{
692 {
693 Digest: validDigestWithAlgo2,
694 MediaType: "application/vnd.oci.image.manifest.v1+json",
695 Size: 4*1024*1024 + 1,
696 },
697 },
698 }
699 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
700 Digest: validDigestWithAlgo2,
701 })
702 if err == nil {
703 t.Fatalf("expected to fail with image manifest exceds max blob size")
704 }
705 })
706
707 t.Run("artifact manifest fetchAll failed", func(t *testing.T) {
708 store := &testStorage{
709 store: &memory.Store{},
710 PredecessorsDesc: []ocispec.Descriptor{
711 {
712 Digest: validDigestWithAlgo,
713 MediaType: "application/vnd.oci.artifact.manifest.v1+json",
714 Size: 481,
715 },
716 },
717 FetchError: fmt.Errorf("failed to fetch all"),
718 }
719 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
720 Digest: validDigestWithAlgo,
721 })
722 if err == nil {
723 t.Fatalf("expected to fail with fetchAll failed")
724 }
725 })
726
727 t.Run("image manifest fetchAll failed", func(t *testing.T) {
728 store := &testStorage{
729 store: &memory.Store{},
730 PredecessorsDesc: []ocispec.Descriptor{
731 {
732 Digest: validDigestWithAlgo,
733 MediaType: "application/vnd.oci.image.manifest.v1+json",
734 Size: 481,
735 },
736 },
737 FetchError: fmt.Errorf("failed to fetch all"),
738 }
739 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
740 Digest: validDigestWithAlgo,
741 })
742 if err == nil {
743 t.Fatalf("expected to fail with fetchAll failed")
744 }
745 })
746
747 t.Run("artifact manifest marshal failed", func(t *testing.T) {
748 store := &testStorage{
749 store: &memory.Store{},
750 PredecessorsDesc: []ocispec.Descriptor{
751 {
752 Digest: "sha256:24aafc739daae02bcd33471a1b28bcfaaef0bb5e530ef44cd4e5d2445e606690",
753 MediaType: "application/vnd.oci.artifact.manifest.v1+json",
754 Size: 15,
755 },
756 },
757 FetchContent: []byte("invalid content"),
758 }
759 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
760 Digest: "sha256:24aafc739daae02bcd33471a1b28bcfaaef0bb5e530ef44cd4e5d2445e606690",
761 })
762 if err == nil {
763 t.Fatalf("expected to fail with marshal failed")
764 }
765 })
766
767 t.Run("image manifest marshal failed", func(t *testing.T) {
768 store := &testStorage{
769 store: &memory.Store{},
770 PredecessorsDesc: []ocispec.Descriptor{
771 {
772 Digest: "sha256:24aafc739daae02bcd33471a1b28bcfaaef0bb5e530ef44cd4e5d2445e606690",
773 MediaType: "application/vnd.oci.image.manifest.v1+json",
774 Size: 15,
775 },
776 },
777 FetchContent: []byte("invalid content"),
778 }
779 _, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
780 Digest: "sha256:24aafc739daae02bcd33471a1b28bcfaaef0bb5e530ef44cd4e5d2445e606690",
781 })
782 if err == nil {
783 t.Fatalf("expected to fail with marshal failed")
784 }
785 })
786
787 t.Run("no valid artifact manifest", func(t *testing.T) {
788 store := &testStorage{
789 store: &memory.Store{},
790 PredecessorsDesc: []ocispec.Descriptor{
791 {
792 Digest: "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
793 MediaType: "application/vnd.oci.artifact.manifest.v1+json",
794 Size: 2,
795 },
796 },
797 FetchContent: []byte("{}"),
798 }
799 descriptors, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
800 Digest: "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
801 })
802
803 if err != nil {
804 t.Fatalf("failed to get referrers: %v", err)
805 }
806 if len(descriptors) != 0 {
807 t.Fatalf("expected to get no referrers, but got: %v", descriptors)
808 }
809 })
810
811 t.Run("no valid image manifest", func(t *testing.T) {
812 store := &testStorage{
813 store: &memory.Store{},
814 PredecessorsDesc: []ocispec.Descriptor{
815 {
816 Digest: "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
817 MediaType: "application/vnd.oci.image.manifest.v1+json",
818 Size: 2,
819 },
820 },
821 FetchContent: []byte("{}"),
822 }
823 descriptors, err := signatureReferrers(context.Background(), store, ocispec.Descriptor{
824 Digest: "sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",
825 })
826
827 if err != nil {
828 t.Fatalf("failed to get referrers: %v", err)
829 }
830 if len(descriptors) != 0 {
831 t.Fatalf("expected to get no referrers, but got: %v", descriptors)
832 }
833 })
834 }