Debian Codegraph @

notation_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 notation
15
16 import (
17 "context"
18 "encoding/json"
19 "errors"
20 "fmt"
21 "math"
22 "os"
23 "path/filepath"
24 "testing"
25 "time"
26
27 "oras.land/oras-go/v2/registry/remote"
28
29 "github.com/notaryproject/notation-core-go/signature"
30 "github.com/notaryproject/notation-core-go/signature/cose"
31 "github.com/notaryproject/notation-core-go/signature/jws"
32 "github.com/notaryproject/notation-go/internal/envelope"
33 "github.com/notaryproject/notation-go/internal/mock"
34 "github.com/notaryproject/notation-go/internal/mock/ocilayout"
35 "github.com/notaryproject/notation-go/plugin"
36 "github.com/notaryproject/notation-go/registry"
37 "github.com/notaryproject/notation-go/verifier/trustpolicy"
38 ocispec "github.com/opencontainers/image-spec/specs-go/v1"
39 )
40
41 var expectedMetadata = map[string]string{"foo": "bar", "bar": "foo"}
42
43 func TestSignSuccess(t *testing.T) {
44 repo := mock.NewRepository()
45 testCases := []struct {
46 name string
47 dur time.Duration
48 }{
49 {"expiryInHours", 24 * time.Hour},
50 {"oneSecondExpiry", 1 * time.Second},
51 {"zeroExpiry", 0},
52 }
53 for _, tc := range testCases {
54 t.Run(tc.name, func(b *testing.T) {
55 opts := SignOptions{}
56 opts.SignatureMediaType = jws.MediaTypeEnvelope
57 opts.ExpiryDuration = tc.dur
58 opts.ArtifactReference = mock.SampleArtifactUri
59
60 _, err := Sign(context.Background(), &dummySigner{}, repo, opts)
61 if err != nil {
62 b.Fatalf("Sign failed with error: %v", err)
63 }
64 })
65 }
66 }
67
68 func TestSignSuccessWithUserMetadata(t *testing.T) {
69 repo := mock.NewRepository()
70 opts := SignOptions{}
71 opts.ArtifactReference = mock.SampleArtifactUri
72 opts.UserMetadata = expectedMetadata
73 opts.SignatureMediaType = jws.MediaTypeEnvelope
74
75 _, err := Sign(context.Background(), &verifyMetadataSigner{}, repo, opts)
76 if err != nil {
77 t.Fatalf("error: %v", err)
78 }
79 }
80
81 func TestSignWithDanglingReferrersIndex(t *testing.T) {
82 repo := mock.NewRepository()
83 repo.PushSignatureError = &remote.ReferrersError{
84 Op: "DeleteReferrersIndex",
85 Err: errors.New("error"),
86 }
87 opts := SignOptions{}
88 opts.ArtifactReference = mock.SampleArtifactUri
89 opts.SignatureMediaType = jws.MediaTypeEnvelope
90
91 _, err := Sign(context.Background(), &dummySigner{}, repo, opts)
92 if err == nil {
93 t.Fatalf("no error occurred, expected error")
94 }
95 }
96
97 func TestSignWithNilRepo(t *testing.T) {
98 opts := SignOptions{}
99 opts.ArtifactReference = mock.SampleArtifactUri
100 opts.SignatureMediaType = jws.MediaTypeEnvelope
101
102 _, err := Sign(context.Background(), &dummySigner{}, nil, opts)
103 if err == nil {
104 t.Fatalf("no error occurred, expected error: repo cannot be nil")
105 }
106 }
107
108 func TestSignResolveFailed(t *testing.T) {
109 repo := mock.NewRepository()
110 repo.ResolveError = errors.New("resolve error")
111 opts := SignOptions{}
112 opts.ArtifactReference = mock.SampleArtifactUri
113 opts.SignatureMediaType = jws.MediaTypeEnvelope
114
115 _, err := Sign(context.Background(), &dummySigner{}, repo, opts)
116 if err == nil {
117 t.Fatalf("no error occurred, expected resolve error")
118 }
119 }
120
121 func TestSignArtifactRefIsTag(t *testing.T) {
122 repo := mock.NewRepository()
123 opts := SignOptions{}
124 opts.ArtifactReference = "registry.acme-rockets.io/software/net-monitor:v1"
125 opts.SignatureMediaType = jws.MediaTypeEnvelope
126
127 _, err := Sign(context.Background(), &dummySigner{}, repo, opts)
128 if err != nil {
129 t.Fatalf("expect no error, got %s", err)
130 }
131 }
132
133 func TestSignWithPushSignatureError(t *testing.T) {
134 repo := mock.NewRepository()
135 repo.PushSignatureError = errors.New("error")
136 opts := SignOptions{}
137 opts.ArtifactReference = mock.SampleArtifactUri
138 opts.SignatureMediaType = jws.MediaTypeEnvelope
139
140 _, err := Sign(context.Background(), &dummySigner{}, repo, opts)
141 if err == nil {
142 t.Fatalf("no error occurred, expected error: failed to delete dangling referrers index")
143 }
144 }
145
146 func TestSignWithInvalidExpiry(t *testing.T) {
147 repo := mock.NewRepository()
148 testCases := []struct {
149 name string
150 dur time.Duration
151 }{
152 {"negativeExpiry", -24 * time.Hour},
153 {"splitSecondExpiry", 1 * time.Millisecond},
154 }
155 for _, tc := range testCases {
156 t.Run(tc.name, func(b *testing.T) {
157 opts := SignOptions{}
158 opts.ExpiryDuration = tc.dur
159
160 _, err := Sign(context.Background(), &dummySigner{}, repo, opts)
161 if err == nil {
162 b.Fatalf("Expected error but not found")
163 }
164 })
165 }
166 }
167
168 func TestSignWithInvalidUserMetadata(t *testing.T) {
169 repo := mock.NewRepository()
170 testCases := []struct {
171 name string
172 metadata map[string]string
173 }{
174 {"reservedAnnotationKey", map[string]string{reservedAnnotationPrefixes[0] + ".foo": "bar"}},
175 {"keyConflict", map[string]string{"key": "value2"}},
176 }
177 for _, tc := range testCases {
178 t.Run(tc.name, func(b *testing.T) {
179 opts := SignOptions{
180 UserMetadata: tc.metadata,
181 SignerSignOptions: SignerSignOptions{
182 SignatureMediaType: jws.MediaTypeEnvelope,
183 },
184 }
185
186 _, err := Sign(context.Background(), &dummySigner{}, repo, opts)
187 if err == nil {
188 b.Fatalf("Expected error but not found")
189 }
190 })
191 }
192 }
193
194 func TestSignOptsMissingSignatureMediaType(t *testing.T) {
195 repo := mock.NewRepository()
196 opts := SignOptions{
197 SignerSignOptions: SignerSignOptions{
198 SignatureMediaType: "",
199 },
200 ArtifactReference: mock.SampleArtifactUri,
201 }
202
203 _, err := Sign(context.Background(), &dummySigner{}, repo, opts)
204 if err == nil {
205 t.Fatalf("expected error but not found")
206 }
207 }
208
209 func TestSignOptsUnknownMediaType(t *testing.T) {
210 repo := mock.NewRepository()
211 opts := SignOptions{
212 SignerSignOptions: SignerSignOptions{
213 SignatureMediaType: "unknown",
214 },
215 ArtifactReference: mock.SampleArtifactUri,
216 }
217
218 _, err := Sign(context.Background(), &dummySigner{}, repo, opts)
219 if err == nil {
220 t.Fatalf("expected error but not found")
221 }
222
223 }
224
225 func TestRegistryResolveError(t *testing.T) {
226 repo := mock.NewRepository()
227 policyDocument := dummyPolicyDocument()
228 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, false}
229
230 errorMessage := "network error"
231 expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
232
233 // mock the repository
234 repo.ResolveError = errors.New("network error")
235 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
236 _, _, err := Verify(context.Background(), &verifier, repo, opts)
237
238 if err == nil || err.Error() != errorMessage {
239 t.Fatalf("RegistryResolve expected: %v got: %v", expectedErr, err)
240 }
241 }
242
243 func TestVerifyEmptyReference(t *testing.T) {
244 repo := mock.NewRepository()
245 policyDocument := dummyPolicyDocument()
246 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, false}
247
248 errorMessage := "reference is missing digest or tag"
249 expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
250
251 // mock the repository
252 opts := VerifyOptions{ArtifactReference: "localhost/test", MaxSignatureAttempts: 50}
253 _, _, err := Verify(context.Background(), &verifier, repo, opts)
254 if err == nil || err.Error() != errorMessage {
255 t.Fatalf("VerifyTagReference expected: %v got: %v", expectedErr, err)
256 }
257 }
258
259 func TestVerifyTagReferenceFailed(t *testing.T) {
260 repo := mock.NewRepository()
261 policyDocument := dummyPolicyDocument()
262 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, false}
263
264 errorMessage := "invalid reference: invalid repository \"UPPERCASE/test\""
265 expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
266
267 // mock the repository
268 opts := VerifyOptions{ArtifactReference: "localhost/UPPERCASE/test", MaxSignatureAttempts: 50}
269 _, _, err := Verify(context.Background(), &verifier, repo, opts)
270 if err == nil || err.Error() != errorMessage {
271 t.Fatalf("VerifyTagReference expected: %v got: %v", expectedErr, err)
272 }
273 }
274
275 func TestVerifyDigestNotMatchResolve(t *testing.T) {
276 repo := mock.NewRepository()
277 repo.MissMatchDigest = true
278 policyDocument := dummyPolicyDocument()
279 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, false}
280
281 errorMessage := fmt.Sprintf("user input digest %s does not match the resolved digest %s", mock.SampleDigest, mock.ZeroDigest)
282 expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
283
284 // mock the repository
285 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
286 _, _, err := Verify(context.Background(), &verifier, repo, opts)
287 if err == nil || err.Error() != errorMessage {
288 t.Fatalf("VerifyDigestNotMatch expected: %v got: %v", expectedErr, err)
289 }
290 }
291
292 func TestSignDigestNotMatchResolve(t *testing.T) {
293 repo := mock.NewRepository()
294 repo.MissMatchDigest = true
295 signOpts := SignOptions{
296 SignerSignOptions: SignerSignOptions{
297 SignatureMediaType: jws.MediaTypeEnvelope,
298 },
299 ArtifactReference: mock.SampleArtifactUri,
300 }
301
302 errorMessage := fmt.Sprintf("user input digest %s does not match the resolved digest %s", mock.SampleDigest, mock.ZeroDigest)
303 expectedErr := errors.New(errorMessage)
304
305 _, err := Sign(context.Background(), &dummySigner{}, repo, signOpts)
306 if err == nil || err.Error() != errorMessage {
307 t.Fatalf("SignDigestNotMatch expected: %v got: %v", expectedErr, err)
308 }
309 }
310
311 func TestSkippedSignatureVerification(t *testing.T) {
312 repo := mock.NewRepository()
313 policyDocument := dummyPolicyDocument()
314 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelSkip, false}
315
316 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
317 _, outcomes, err := Verify(context.Background(), &verifier, repo, opts)
318
319 if err != nil || outcomes[0].VerificationLevel.Name != trustpolicy.LevelSkip.Name {
320 t.Fatalf("\"skip\" verification level must pass overall signature verification")
321 }
322 }
323
324 func TestRegistryNoSignatureManifests(t *testing.T) {
325 repo := mock.NewRepository()
326 policyDocument := dummyPolicyDocument()
327 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, false}
328 errorMessage := fmt.Sprintf("no signature is associated with %q, make sure the artifact was signed successfully", mock.SampleArtifactUri)
329 expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
330
331 // mock the repository
332 repo.ListSignaturesResponse = []ocispec.Descriptor{}
333 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
334 _, _, err := Verify(context.Background(), &verifier, repo, opts)
335
336 if err == nil || !errors.Is(err, expectedErr) {
337 t.Fatalf("RegistryNoSignatureManifests expected: %v got: %v", expectedErr, err)
338 }
339 }
340
341 func TestRegistryFetchSignatureBlobError(t *testing.T) {
342 repo := mock.NewRepository()
343 policyDocument := dummyPolicyDocument()
344 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, false}
345 errorMessage := fmt.Sprintf("unable to retrieve digital signature with digest %q associated with %q from the Repository, error : network error", mock.SampleDigest, mock.SampleArtifactUri)
346 expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
347
348 // mock the repository
349 repo.FetchSignatureBlobError = errors.New("network error")
350 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
351 _, _, err := Verify(context.Background(), &verifier, repo, opts)
352
353 if err == nil || !errors.Is(err, expectedErr) {
354 t.Fatalf("RegistryFetchSignatureBlob expected: %v got: %v", expectedErr, err)
355 }
356 }
357
358 func TestVerifyValid(t *testing.T) {
359 repo := mock.NewRepository()
360 policyDocument := dummyPolicyDocument()
361 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, false}
362
363 // mock the repository
364 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
365 _, _, err := Verify(context.Background(), &verifier, repo, opts)
366
367 if err != nil {
368 t.Fatalf("expected nil error, but got: %v", err)
369 }
370 }
371
372 func TestVerifySkip(t *testing.T) {
373 repo := mock.NewRepository()
374 policyDocument := dummyPolicyDocument()
375 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, true}
376
377 // mock the repository
378 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
379 _, _, err := Verify(context.Background(), &verifier, repo, opts)
380
381 if err != nil {
382 t.Fatalf("expected nil error, but got: %v", err)
383 }
384 }
385
386 func TestMaxSignatureAttemptsMissing(t *testing.T) {
387 repo := mock.NewRepository()
388 policyDocument := dummyPolicyDocument()
389 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, false}
390 expectedErr := ErrorSignatureRetrievalFailed{Msg: fmt.Sprintf("verifyOptions.MaxSignatureAttempts expects a positive number, got %d", 0)}
391
392 // mock the repository
393 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri}
394 _, _, err := Verify(context.Background(), &verifier, repo, opts)
395
396 if err == nil || !errors.Is(err, expectedErr) {
397 t.Fatalf("VerificationFailed expected: %v got: %v", expectedErr, err)
398 }
399 }
400
401 func TestExceededMaxSignatureAttempts(t *testing.T) {
402 repo := mock.NewRepository()
403 repo.ExceededNumOfSignatures = true
404 policyDocument := dummyPolicyDocument()
405 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, true, *trustpolicy.LevelStrict, false}
406
407 expectedErr := ErrorVerificationFailed{Msg: fmt.Sprintf("signature evaluation stopped. The configured limit of %d signatures to verify per artifact exceeded", 1)}
408
409 // mock the repository
410 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 1}
411 _, _, err := Verify(context.Background(), &verifier, repo, opts)
412
413 if err == nil || !errors.Is(err, expectedErr) {
414 t.Fatalf("VerificationFailed expected: %v got: %v", expectedErr, err)
415 }
416 }
417
418 func TestVerifyFailed(t *testing.T) {
419 t.Run("verification error", func(t *testing.T) {
420 policyDocument := dummyPolicyDocument()
421 repo := mock.NewRepository()
422 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, true, *trustpolicy.LevelStrict, false}
423 expectedErr := ErrorVerificationFailed{}
424
425 // mock the repository
426 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
427 _, _, err := Verify(context.Background(), &verifier, repo, opts)
428
429 if err == nil || !errors.Is(err, expectedErr) {
430 t.Fatalf("VerificationFailed expected: %v got: %v", expectedErr, err)
431 }
432 })
433
434 t.Run("verifier is nil", func(t *testing.T) {
435 repo := mock.NewRepository()
436 expectedErr := errors.New("verifier cannot be nil")
437
438 // mock the repository
439 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
440 _, _, err := Verify(context.Background(), nil, repo, opts)
441
442 if err == nil || err.Error() != expectedErr.Error() {
443 t.Fatalf("VerificationFailed expected: %v got: %v", expectedErr, err)
444 }
445 })
446
447 t.Run("repo is nil", func(t *testing.T) {
448 policyDocument := dummyPolicyDocument()
449 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, false}
450 expectedErr := errors.New("repo cannot be nil")
451
452 // mock the repository
453 opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
454 _, _, err := Verify(context.Background(), &verifier, nil, opts)
455
456 if err == nil || err.Error() != expectedErr.Error() {
457 t.Fatalf("VerificationFailed expected: %v got: %v", expectedErr, err)
458 }
459 })
460 }
461
462 func dummyPolicyDocument() (policyDoc trustpolicy.Document) {
463 policyDoc = trustpolicy.Document{
464 Version: "1.0",
465 TrustPolicies: []trustpolicy.TrustPolicy{dummyPolicyStatement()},
466 }
467 return
468 }
469
470 func dummyPolicyStatement() (policyStatement trustpolicy.TrustPolicy) {
471 policyStatement = trustpolicy.TrustPolicy{
472 Name: "test-statement-name",
473 RegistryScopes: []string{"registry.acme-rockets.io/software/net-monitor"},
474 SignatureVerification: trustpolicy.SignatureVerification{VerificationLevel: "strict"},
475 TrustStores: []string{"ca:valid-trust-store", "signingAuthority:valid-trust-store"},
476 TrustedIdentities: []string{"x509.subject:CN=Notation Test Root,O=Notary,L=Seattle,ST=WA,C=US"},
477 }
478 return
479 }
480
481 type dummySigner struct{}
482
483 func (s *dummySigner) Sign(_ context.Context, _ ocispec.Descriptor, _ SignerSignOptions) ([]byte, *signature.SignerInfo, error) {
484 return []byte("ABC"), &signature.SignerInfo{
485 SignedAttributes: signature.SignedAttributes{
486 SigningTime: time.Now(),
487 },
488 }, nil
489 }
490
491 type verifyMetadataSigner struct{}
492
493 func (s *verifyMetadataSigner) Sign(_ context.Context, desc ocispec.Descriptor, _ SignerSignOptions) ([]byte, *signature.SignerInfo, error) {
494 for k, v := range expectedMetadata {
495 if desc.Annotations[k] != v {
496 return nil, nil, errors.New("expected metadata not present in descriptor")
497 }
498 }
499 return []byte("ABC"), &signature.SignerInfo{
500 SignedAttributes: signature.SignedAttributes{
501 SigningTime: time.Now(),
502 },
503 }, nil
504 }
505
506 type dummyVerifier struct {
507 TrustPolicyDoc *trustpolicy.Document
508 PluginManager plugin.Manager
509 FailVerify bool
510 VerificationLevel trustpolicy.VerificationLevel
511 SkipVerification bool
512 }
513
514 func (v *dummyVerifier) Verify(_ context.Context, _ ocispec.Descriptor, _ []byte, _ VerifierVerifyOptions) (*VerificationOutcome, error) {
515 outcome := &VerificationOutcome{
516 VerificationResults: []*ValidationResult{},
517 VerificationLevel: &v.VerificationLevel,
518 }
519 if v.FailVerify {
520 return outcome, errors.New("failed verify")
521 }
522 return outcome, nil
523 }
524
525 func (v *dummyVerifier) SkipVerify(_ context.Context, _ VerifierVerifyOptions) (bool, *trustpolicy.VerificationLevel, error) {
526 if v.SkipVerification {
527 return true, nil, nil
528 }
529 return false, nil, nil
530 }
531
532 var (
533 reference = "sha256:19dbd2e48e921426ee8ace4dc892edfb2ecdc1d1a72d5416c83670c30acecef0"
534 artifactReference = "local/oci-layout@sha256:19dbd2e48e921426ee8ace4dc892edfb2ecdc1d1a72d5416c83670c30acecef0"
535 signaturePath = filepath.FromSlash("./internal/testdata/cose_signature.sig")
536 )
537
538 type ociDummySigner struct{}
539
540 func (s *ociDummySigner) Sign(_ context.Context, _ ocispec.Descriptor, opts SignerSignOptions) ([]byte, *signature.SignerInfo, error) {
541 sigBlob, err := os.ReadFile(signaturePath)
542 if err != nil {
543 return nil, nil, err
544 }
545 sigEnv, err := signature.ParseEnvelope(opts.SignatureMediaType, sigBlob)
546 if err != nil {
547 return nil, nil, err
548 }
549 content, err := sigEnv.Content()
550 if err != nil {
551 return nil, nil, err
552 }
553 return sigBlob, &content.SignerInfo, nil
554 }
555
556 func TestLocalContent(t *testing.T) {
557 // create a temp OCI layout
558 ociLayoutTestDataPath, err := filepath.Abs(filepath.Join("internal", "testdata", "oci-layout"))
559 if err != nil {
560 t.Fatalf("failed to get oci layout path: %v", err)
561 }
562 newOCILayoutPath := t.TempDir()
563 if err := ocilayout.Copy(ociLayoutTestDataPath, newOCILayoutPath, "v2"); err != nil {
564 t.Fatalf("failed to create temp oci layout: %v", err)
565 }
566 repo, err := registry.NewOCIRepository(newOCILayoutPath, registry.RepositoryOptions{})
567 if err != nil {
568 t.Fatal(err)
569 }
570
571 t.Run("sign the local content", func(t *testing.T) {
572 // sign the artifact
573 signOpts := SignOptions{
574 SignerSignOptions: SignerSignOptions{
575 SignatureMediaType: cose.MediaTypeEnvelope,
576 },
577 ArtifactReference: reference,
578 }
579 _, err = Sign(context.Background(), &ociDummySigner{}, repo, signOpts)
580 if err != nil {
581 t.Fatalf("failed to Sign: %v", err)
582 }
583 })
584
585 t.Run("verify local content", func(t *testing.T) {
586 // verify the artifact
587 verifyOpts := VerifyOptions{
588 ArtifactReference: artifactReference,
•589 MaxSignatureAttempts: math.MaxInt,
590 }
591 policyDocument := dummyPolicyDocument()
592 verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict, false}
593 // verify signatures inside the OCI layout folder
594 _, _, err = Verify(context.Background(), &verifier, repo, verifyOpts)
595 if err != nil {
596 t.Fatalf("failed to verify local content: %v", err)
597 }
598 })
599 }
600
601 func TestUserMetadata(t *testing.T) {
602 t.Run("EnvelopeContent is nil", func(t *testing.T) {
603 outcome := &VerificationOutcome{}
604 _, err := outcome.UserMetadata()
605 if err == nil {
606 t.Fatal("expected an error, got nil")
607 }
608 if err.Error() != "unable to find envelope content for verification outcome" {
609 t.Fatalf("expected error message 'unable to find envelope content for verification outcome', got '%s'", err.Error())
610 }
611 })
612
613 t.Run("EnvelopeContent is valid", func(t *testing.T) {
614 payload := envelope.Payload{
615 TargetArtifact: ocispec.Descriptor{
616 Annotations: map[string]string{
617 "key": "value",
618 },
619 },
620 }
621 payloadBytes, err := json.Marshal(payload)
622 if err != nil {
623 t.Fatalf("unexpected error marshaling payload: %v", err)
624 }
625
626 outcome := &VerificationOutcome{
627 EnvelopeContent: &signature.EnvelopeContent{
628 Payload: signature.Payload{
629 Content: payloadBytes,
630 },
631 },
632 }
633 metadata, err := outcome.UserMetadata()
634 if err != nil {
635 t.Fatalf("unexpected error getting user metadata: %v", err)
636 }
637 if len(metadata) != 1 || metadata["key"] != "value" {
638 t.Fatalf("expected metadata map[key]=value, got %v", metadata)
639 }
640 })
641
642 t.Run("Annotation is nil", func(t *testing.T) {
643 payload := envelope.Payload{
644 TargetArtifact: ocispec.Descriptor{},
645 }
646 payloadBytes, err := json.Marshal(payload)
647 if err != nil {
648 t.Fatalf("unexpected error marshaling payload: %v", err)
649 }
650
651 outcome := &VerificationOutcome{
652 EnvelopeContent: &signature.EnvelopeContent{
653 Payload: signature.Payload{
654 Content: payloadBytes,
655 },
656 },
657 }
658 metadata, err := outcome.UserMetadata()
659 if err != nil {
660 t.Fatalf("unexpected error getting user metadata: %v", err)
661 }
662 if len(metadata) != 0 {
663 t.Fatalf("expected empty metadata, got %v", metadata)
664 }
665 })
666 }