forked from notaryproject/notation-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
notation_test.go
362 lines (311 loc) · 12.2 KB
/
notation_test.go
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
package notation
import (
"context"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"testing"
"time"
"github.com/notaryproject/notation-core-go/signature"
"github.com/notaryproject/notation-core-go/signature/cose"
"github.com/notaryproject/notation-go/internal/mock"
"github.com/notaryproject/notation-go/plugin"
"github.com/notaryproject/notation-go/registry"
"github.com/notaryproject/notation-go/verifier/trustpolicy"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)
var expectedMetadata = map[string]string{"foo": "bar", "bar": "foo"}
func TestSignSuccess(t *testing.T) {
repo := mock.NewRepository()
testCases := []struct {
name string
dur time.Duration
}{
{"expiryInHours", 24 * time.Hour},
{"oneSecondExpiry", 1 * time.Second},
{"zeroExpiry", 0},
}
for _, tc := range testCases {
t.Run(tc.name, func(b *testing.T) {
opts := SignOptions{}
opts.ExpiryDuration = tc.dur
opts.ArtifactReference = mock.SampleArtifactUri
_, err := Sign(context.Background(), &dummySigner{}, repo, opts)
if err != nil {
b.Fatalf("Sign failed with error: %v", err)
}
})
}
}
func TestSignSuccessWithUserMetadata(t *testing.T) {
repo := mock.NewRepository()
opts := SignOptions{}
opts.ArtifactReference = mock.SampleArtifactUri
opts.UserMetadata = expectedMetadata
_, err := Sign(context.Background(), &verifyMetadataSigner{}, repo, opts)
if err != nil {
t.Fatalf("error: %v", err)
}
}
func TestSignWithInvalidExpiry(t *testing.T) {
repo := mock.NewRepository()
testCases := []struct {
name string
dur time.Duration
}{
{"negativeExpiry", -24 * time.Hour},
{"splitSecondExpiry", 1 * time.Millisecond},
}
for _, tc := range testCases {
t.Run(tc.name, func(b *testing.T) {
opts := SignOptions{}
opts.ExpiryDuration = tc.dur
_, err := Sign(context.Background(), &dummySigner{}, repo, opts)
if err == nil {
b.Fatalf("Expected error but not found")
}
})
}
}
func TestSignWithInvalidUserMetadata(t *testing.T) {
repo := mock.NewRepository()
testCases := []struct {
name string
metadata map[string]string
}{
{"reservedAnnotationKey", map[string]string{reservedAnnotationPrefixes[0] + ".foo": "bar"}},
{"keyConflict", map[string]string{"key": "value2"}},
}
for _, tc := range testCases {
t.Run(tc.name, func(b *testing.T) {
_, err := Sign(context.Background(), &dummySigner{}, repo, SignOptions{UserMetadata: tc.metadata})
if err == nil {
b.Fatalf("Expected error but not found")
}
})
}
}
func TestRegistryResolveError(t *testing.T) {
policyDocument := dummyPolicyDocument()
repo := mock.NewRepository()
verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict}
errorMessage := "network error"
expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
// mock the repository
repo.ResolveError = errors.New("network error")
opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
_, _, err := Verify(context.Background(), &verifier, repo, opts)
if err == nil || err.Error() != errorMessage {
t.Fatalf("RegistryResolve expected: %v got: %v", expectedErr, err)
}
}
func TestVerifyEmptyReference(t *testing.T) {
policyDocument := dummyPolicyDocument()
repo := mock.NewRepository()
verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict}
errorMessage := "reference is missing digest or tag"
expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
// mock the repository
opts := VerifyOptions{ArtifactReference: "localhost/test", MaxSignatureAttempts: 50}
_, _, err := Verify(context.Background(), &verifier, repo, opts)
if err == nil || err.Error() != errorMessage {
t.Fatalf("VerifyTagReference expected: %v got: %v", expectedErr, err)
}
}
func TestVerifyTagReferenceFailed(t *testing.T) {
policyDocument := dummyPolicyDocument()
repo := mock.NewRepository()
verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict}
errorMessage := "invalid reference: invalid repository"
expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
// mock the repository
opts := VerifyOptions{ArtifactReference: "localhost/UPPERCASE/test", MaxSignatureAttempts: 50}
_, _, err := Verify(context.Background(), &verifier, repo, opts)
if err == nil || err.Error() != errorMessage {
t.Fatalf("VerifyTagReference expected: %v got: %v", expectedErr, err)
}
}
func TestSkippedSignatureVerification(t *testing.T) {
policyDocument := dummyPolicyDocument()
repo := mock.NewRepository()
verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelSkip}
opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
_, outcomes, err := Verify(context.Background(), &verifier, repo, opts)
if err != nil || outcomes[0].VerificationLevel.Name != trustpolicy.LevelSkip.Name {
t.Fatalf("\"skip\" verification level must pass overall signature verification")
}
}
func TestRegistryNoSignatureManifests(t *testing.T) {
policyDocument := dummyPolicyDocument()
repo := mock.NewRepository()
verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict}
errorMessage := fmt.Sprintf("no signature is associated with %q, make sure the artifact was signed successfully", mock.SampleArtifactUri)
expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
// mock the repository
repo.ListSignaturesResponse = []ocispec.Descriptor{}
opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
_, _, err := Verify(context.Background(), &verifier, repo, opts)
if err == nil || !errors.Is(err, expectedErr) {
t.Fatalf("RegistryNoSignatureManifests expected: %v got: %v", expectedErr, err)
}
}
func TestRegistryFetchSignatureBlobError(t *testing.T) {
policyDocument := dummyPolicyDocument()
repo := mock.NewRepository()
verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict}
errorMessage := fmt.Sprintf("unable to retrieve digital signature with digest %q associated with %q from the Repository, error : network error", mock.SampleDigest, mock.SampleArtifactUri)
expectedErr := ErrorSignatureRetrievalFailed{Msg: errorMessage}
// mock the repository
repo.FetchSignatureBlobError = errors.New("network error")
opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
_, _, err := Verify(context.Background(), &verifier, repo, opts)
if err == nil || !errors.Is(err, expectedErr) {
t.Fatalf("RegistryFetchSignatureBlob expected: %v got: %v", expectedErr, err)
}
}
func TestVerifyValid(t *testing.T) {
policyDocument := dummyPolicyDocument()
repo := mock.NewRepository()
verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict}
// mock the repository
opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
_, _, err := Verify(context.Background(), &verifier, repo, opts)
if err != nil {
t.Fatalf("SignaureMediaTypeMismatch expected: %v got: %v", nil, err)
}
}
func TestMaxSignatureAttemptsMissing(t *testing.T) {
policyDocument := dummyPolicyDocument()
repo := mock.NewRepository()
verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict}
expectedErr := ErrorSignatureRetrievalFailed{Msg: fmt.Sprintf("verifyOptions.MaxSignatureAttempts expects a positive number, got %d", 0)}
// mock the repository
opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri}
_, _, err := Verify(context.Background(), &verifier, repo, opts)
if err == nil || !errors.Is(err, expectedErr) {
t.Fatalf("VerificationFailed expected: %v got: %v", expectedErr, err)
}
}
func TestVerifyFailed(t *testing.T) {
policyDocument := dummyPolicyDocument()
repo := mock.NewRepository()
verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, true, *trustpolicy.LevelStrict}
expectedErr := ErrorVerificationFailed{}
// mock the repository
opts := VerifyOptions{ArtifactReference: mock.SampleArtifactUri, MaxSignatureAttempts: 50}
_, _, err := Verify(context.Background(), &verifier, repo, opts)
if err == nil || !errors.Is(err, expectedErr) {
t.Fatalf("VerificationFailed expected: %v got: %v", expectedErr, err)
}
}
func dummyPolicyDocument() (policyDoc trustpolicy.Document) {
policyDoc = trustpolicy.Document{
Version: "1.0",
TrustPolicies: []trustpolicy.TrustPolicy{dummyPolicyStatement()},
}
return
}
func dummyPolicyStatement() (policyStatement trustpolicy.TrustPolicy) {
policyStatement = trustpolicy.TrustPolicy{
Name: "test-statement-name",
RegistryScopes: []string{"registry.acme-rockets.io/software/net-monitor"},
SignatureVerification: trustpolicy.SignatureVerification{VerificationLevel: "strict"},
TrustStores: []string{"ca:valid-trust-store", "signingAuthority:valid-trust-store"},
TrustedIdentities: []string{"x509.subject:CN=Notation Test Root,O=Notary,L=Seattle,ST=WA,C=US"},
}
return
}
type dummySigner struct{}
func (s *dummySigner) Sign(ctx context.Context, desc ocispec.Descriptor, opts SignerSignOptions) ([]byte, *signature.SignerInfo, error) {
return []byte("ABC"), &signature.SignerInfo{
SignedAttributes: signature.SignedAttributes{
SigningTime: time.Now(),
},
}, nil
}
type verifyMetadataSigner struct{}
func (s *verifyMetadataSigner) Sign(ctx context.Context, desc ocispec.Descriptor, opts SignerSignOptions) ([]byte, *signature.SignerInfo, error) {
for k, v := range expectedMetadata {
if desc.Annotations[k] != v {
return nil, nil, errors.New("expected metadata not present in descriptor")
}
}
return []byte("ABC"), &signature.SignerInfo{
SignedAttributes: signature.SignedAttributes{
SigningTime: time.Now(),
},
}, nil
}
type dummyVerifier struct {
TrustPolicyDoc *trustpolicy.Document
PluginManager plugin.Manager
FailVerify bool
VerificationLevel trustpolicy.VerificationLevel
}
func (v *dummyVerifier) Verify(ctx context.Context, desc ocispec.Descriptor, signature []byte, opts VerifierVerifyOptions) (*VerificationOutcome, error) {
outcome := &VerificationOutcome{
VerificationResults: []*ValidationResult{},
VerificationLevel: &v.VerificationLevel,
}
if v.FailVerify {
return outcome, errors.New("failed verify")
}
return outcome, nil
}
var (
ociLayoutPath = filepath.FromSlash("./internal/testdata/oci-layout")
reference = "sha256:19dbd2e48e921426ee8ace4dc892edfb2ecdc1d1a72d5416c83670c30acecef0"
artifactReference = "local/oci-layout@sha256:19dbd2e48e921426ee8ace4dc892edfb2ecdc1d1a72d5416c83670c30acecef0"
signaturePath = filepath.FromSlash("./internal/testdata/cose_signature.sig")
)
type ociDummySigner struct{}
func (s *ociDummySigner) Sign(ctx context.Context, desc ocispec.Descriptor, opts SignerSignOptions) ([]byte, *signature.SignerInfo, error) {
sigBlob, err := os.ReadFile(signaturePath)
if err != nil {
return nil, nil, err
}
sigEnv, err := signature.ParseEnvelope(opts.SignatureMediaType, sigBlob)
if err != nil {
return nil, nil, err
}
content, err := sigEnv.Content()
if err != nil {
return nil, nil, err
}
return sigBlob, &content.SignerInfo, nil
}
func TestSignLocalContent(t *testing.T) {
repo, err := registry.NewOCIRepository(ociLayoutPath, registry.RepositoryOptions{OCIImageManifest: true})
if err != nil {
t.Fatal(err)
}
signOpts := SignOptions{
SignerSignOptions: SignerSignOptions{
SignatureMediaType: cose.MediaTypeEnvelope,
},
ArtifactReference: reference,
}
_, err = Sign(context.Background(), &ociDummySigner{}, repo, signOpts)
if err != nil {
t.Fatalf("failed to Sign: %v", err)
}
}
func TestVerifyLocalContent(t *testing.T) {
repo, err := registry.NewOCIRepository(ociLayoutPath, registry.RepositoryOptions{OCIImageManifest: true})
if err != nil {
t.Fatalf("failed to create oci.Store as registry.Repository: %v", err)
}
verifyOpts := VerifyOptions{
ArtifactReference: artifactReference,
MaxSignatureAttempts: math.MaxInt64,
}
policyDocument := dummyPolicyDocument()
verifier := dummyVerifier{&policyDocument, mock.PluginManager{}, false, *trustpolicy.LevelStrict}
// verify signatures inside the OCI layout folder
_, _, err = Verify(context.Background(), &verifier, repo, verifyOpts)
if err != nil {
t.Fatalf("failed to verify local content: %v", err)
}
}