-
Notifications
You must be signed in to change notification settings - Fork 21
/
verify_test.go
430 lines (372 loc) · 13.3 KB
/
verify_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
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
// Copyright 2024 The Witness Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package witness
import (
"bytes"
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"fmt"
"path/filepath"
"testing"
"time"
"github.com/in-toto/go-witness/attestation"
"github.com/in-toto/go-witness/attestation/commandrun"
"github.com/in-toto/go-witness/attestation/material"
"github.com/in-toto/go-witness/attestation/product"
"github.com/in-toto/go-witness/cryptoutil"
"github.com/in-toto/go-witness/dsse"
"github.com/in-toto/go-witness/policy"
"github.com/in-toto/go-witness/source"
"github.com/invopop/jsonschema"
"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func TestVerify(t *testing.T) {
testPolicy, functionarySigner := makePolicyWithPublicKeyFunctionary(t)
policyEnvelope, _, policyVerifier := signPolicyRSA(t, testPolicy)
workingDir := t.TempDir()
step1Result, err := Run(
"step01",
RunWithSigners(functionarySigner),
RunWithAttestors([]attestation.Attestor{
material.New(),
commandrun.New(
commandrun.WithCommand([]string{"bash", "-c", "echo 'test01' > test.txt"}),
),
product.New(),
}),
RunWithAttestationOpts(
attestation.WithWorkingDir(workingDir),
),
)
require.NoError(t, err)
subjects := []cryptoutil.DigestSet{}
artifactSubject, err := cryptoutil.CalculateDigestSetFromFile(
filepath.Join(workingDir, "test.txt"),
[]cryptoutil.DigestValue{
{
GitOID: false,
Hash: crypto.SHA256,
},
},
)
require.NoError(t, err)
subjects = append(subjects, artifactSubject)
step2Result, err := Run(
"step02",
RunWithSigners(functionarySigner),
RunWithAttestors([]attestation.Attestor{
material.New(),
commandrun.New(
commandrun.WithCommand([]string{"bash", "-c", "echo 'test02' >> test.txt"}),
),
product.New(),
}),
RunWithAttestationOpts(
attestation.WithWorkingDir(workingDir),
),
)
require.NoError(t, err)
artifactSubject, err = cryptoutil.CalculateDigestSetFromFile(
filepath.Join(workingDir, "test.txt"),
[]cryptoutil.DigestValue{
{
GitOID: false,
Hash: crypto.SHA256,
},
},
)
require.NoError(t, err)
subjects = append(subjects, artifactSubject)
t.Run("Pass", func(t *testing.T) {
memorySource := source.NewMemorySource()
require.NoError(t, memorySource.LoadEnvelope("step01", step1Result.SignedEnvelope))
require.NoError(t, memorySource.LoadEnvelope("step02", step2Result.SignedEnvelope))
results, err := Verify(
context.Background(),
policyEnvelope,
[]cryptoutil.Verifier{policyVerifier},
VerifyWithCollectionSource(memorySource),
VerifyWithSubjectDigests(subjects),
)
require.NoError(t, err, fmt.Sprintf("failed with results: %+v", results))
})
t.Run("Fail with missing collection", func(t *testing.T) {
memorySource := source.NewMemorySource()
require.NoError(t, memorySource.LoadEnvelope("step01", step1Result.SignedEnvelope))
results, err := Verify(
context.Background(),
policyEnvelope,
[]cryptoutil.Verifier{policyVerifier},
VerifyWithCollectionSource(memorySource),
VerifyWithSubjectDigests(subjects),
)
require.Error(t, err, fmt.Sprintf("passed with results: %+v", results))
})
t.Run("Fail with missing attestation", func(t *testing.T) {
functionaryVerifier, err := functionarySigner.Verifier()
require.NoError(t, err)
policyFunctionary, policyPk := functionaryFromVerifier(t, functionaryVerifier)
failPolicy := makePolicy(policyFunctionary, policyPk, map[string]policy.Root{})
step1 := failPolicy.Steps["step01"]
step1.Attestations = append(step1.Attestations, policy.Attestation{Type: "nonexistent atttestation"})
failPolicy.Steps["step01"] = step1
failPolicyEnvelope, _, failPolicyVerifier := signPolicyRSA(t, failPolicy)
memorySource := source.NewMemorySource()
require.NoError(t, memorySource.LoadEnvelope("step01", step1Result.SignedEnvelope))
require.NoError(t, memorySource.LoadEnvelope("step02", step2Result.SignedEnvelope))
results, err := Verify(
context.Background(),
failPolicyEnvelope,
[]cryptoutil.Verifier{failPolicyVerifier},
VerifyWithCollectionSource(memorySource),
VerifyWithSubjectDigests(subjects),
)
require.Error(t, err, fmt.Sprintf("passed with results: %+v", results))
})
t.Run("Fail with incorrect signer", func(t *testing.T) {
functionaryVerifier, err := functionarySigner.Verifier()
require.NoError(t, err)
policyFunctionary, policyPk := functionaryFromVerifier(t, functionaryVerifier)
failPolicy := makePolicy(policyFunctionary, policyPk, map[string]policy.Root{})
// create a new key and functionary, and replace the step's functionary with it.
// the attestation would not have been signed with this key, so verification should fail.
newSigner := createTestRSAKey(t)
newVerifier, err := newSigner.Verifier()
require.NoError(t, err)
failPolicyFunctionary, failPolicyPk := functionaryFromVerifier(t, newVerifier)
failPolicy.PublicKeys[failPolicyPk.KeyID] = failPolicyPk
step1 := failPolicy.Steps["step01"]
step1.Functionaries = []policy.Functionary{failPolicyFunctionary}
failPolicy.Steps["step01"] = step1
failPolicyEnvelope, _, failPolicyVerifier := signPolicyRSA(t, failPolicy)
memorySource := source.NewMemorySource()
require.NoError(t, memorySource.LoadEnvelope("step01", step1Result.SignedEnvelope))
require.NoError(t, memorySource.LoadEnvelope("step02", step2Result.SignedEnvelope))
results, err := Verify(
context.Background(),
failPolicyEnvelope,
[]cryptoutil.Verifier{failPolicyVerifier},
VerifyWithCollectionSource(memorySource),
VerifyWithSubjectDigests(subjects),
)
require.Error(t, err, fmt.Sprintf("passed with results: %+v", results))
})
}
func TestBackRefs(t *testing.T) {
registerDummyAttestors()
testPolicy, functionarySigner := makePolicyWithPublicKeyFunctionary(t)
policyEnvelope, _, policyVerifier := signPolicyRSA(t, testPolicy)
workingDir := t.TempDir()
step1Result, err := Run(
"step01",
RunWithSigners(functionarySigner),
RunWithAttestors([]attestation.Attestor{
material.New(),
&dummySubjectAttestor{Data: "test"},
commandrun.New(
commandrun.WithCommand([]string{"bash", "-c", "echo 'test01' > test.txt"}),
),
product.New(),
}),
RunWithAttestationOpts(
attestation.WithWorkingDir(workingDir),
),
)
require.NoError(t, err)
step2Result, err := Run(
"step02",
RunWithSigners(functionarySigner),
RunWithAttestors([]attestation.Attestor{
material.New(),
&dummyBackrefAttestor{},
commandrun.New(
commandrun.WithCommand([]string{"bash", "-c", "echo 'test02' >> test.txt"}),
),
product.New(),
}),
RunWithAttestationOpts(
attestation.WithWorkingDir(workingDir),
),
)
require.NoError(t, err)
artifactSubject, err := cryptoutil.CalculateDigestSetFromFile(
filepath.Join(workingDir, "test.txt"),
[]cryptoutil.DigestValue{
{
GitOID: false,
Hash: crypto.SHA256,
},
},
)
require.NoError(t, err)
memorySource := source.NewMemorySource()
require.NoError(t, memorySource.LoadEnvelope("step01", step1Result.SignedEnvelope))
require.NoError(t, memorySource.LoadEnvelope("step02", step2Result.SignedEnvelope))
results, err := Verify(
context.Background(),
policyEnvelope,
[]cryptoutil.Verifier{policyVerifier},
VerifyWithCollectionSource(memorySource),
VerifyWithSubjectDigests([]cryptoutil.DigestSet{artifactSubject}),
)
require.NoError(t, err, fmt.Sprintf("failed with results: %+v", results))
}
func makePolicy(functionary policy.Functionary, publicKey policy.PublicKey, roots map[string]policy.Root) policy.Policy {
step01 := policy.Step{
Name: "step01",
Functionaries: []policy.Functionary{functionary},
Attestations: []policy.Attestation{{Type: commandrun.Type}},
}
step02 := policy.Step{
Name: "step02",
Functionaries: []policy.Functionary{functionary},
Attestations: []policy.Attestation{{Type: commandrun.Type}},
ArtifactsFrom: []string{"step01"},
}
p := policy.Policy{
Expires: metav1.Time{Time: time.Now().Add(1 * time.Hour)},
PublicKeys: map[string]policy.PublicKey{},
Steps: map[string]policy.Step{},
}
if functionary.CertConstraint.Roots != nil {
p.Roots = roots
}
p.Steps = make(map[string]policy.Step)
p.Steps[step01.Name] = step01
p.Steps[step02.Name] = step02
if publicKey.KeyID != "" {
p.PublicKeys[publicKey.KeyID] = publicKey
}
return p
}
func makePolicyWithPublicKeyFunctionary(t *testing.T) (policy.Policy, cryptoutil.Signer) {
signer := createTestRSAKey(t)
verifier, err := signer.Verifier()
require.NoError(t, err)
functionary, pk := functionaryFromVerifier(t, verifier)
p := makePolicy(functionary, pk, nil)
return p, signer
}
func functionaryFromVerifier(t *testing.T, v cryptoutil.Verifier) (policy.Functionary, policy.PublicKey) {
keyID, err := v.KeyID()
require.NoError(t, err)
keyBytes, err := v.Bytes()
require.NoError(t, err)
return policy.Functionary{
Type: "PublicKey",
PublicKeyID: keyID,
},
policy.PublicKey{
KeyID: keyID,
Key: keyBytes,
}
}
func signPolicyRSA(t *testing.T, p policy.Policy) (dsse.Envelope, cryptoutil.Signer, cryptoutil.Verifier) {
signer := createTestRSAKey(t)
env := signPolicy(t, p, signer)
verifier, err := signer.Verifier()
require.NoError(t, err)
return env, signer, verifier
}
func signPolicy(t *testing.T, p policy.Policy, signer cryptoutil.Signer) dsse.Envelope {
pBytes, err := json.Marshal(p)
require.NoError(t, err)
reader := bytes.NewReader(pBytes)
outBytes := []byte{}
writer := bytes.NewBuffer(outBytes)
require.NoError(t, Sign(reader, policy.PolicyPredicate, writer, dsse.SignWithSigners(signer)))
env := dsse.Envelope{}
require.NoError(t, json.Unmarshal(writer.Bytes(), &env))
return env
}
func createTestRSAKey(t *testing.T) cryptoutil.Signer {
privKey, err := rsa.GenerateKey(rand.Reader, 512)
require.NoError(t, err)
signer := cryptoutil.NewRSASigner(privKey, crypto.SHA256)
return signer
}
const (
dummySubjectAttestorName = "subject attestor"
dummySubjectAttestorType = "test/subjectattestor"
dummyBackrefAttestorName = "backref attestor"
dummyBackrefAttestorType = "test/backrefattestor"
matchSubjectName = "matchSubject"
)
// policy verification currently needs attestors to be registers to properly validate them
func registerDummyAttestors() {
attestation.RegisterAttestation(dummyBackrefAttestorName, dummyBackrefAttestorType, attestation.PreMaterialRunType, func() attestation.Attestor { return &dummyBackrefAttestor{} })
attestation.RegisterAttestation(dummySubjectAttestorName, dummySubjectAttestorType, attestation.PreMaterialRunType, func() attestation.Attestor { return &dummySubjectAttestor{} })
}
// dummySubjectAttestor is a test attestor used to create a subject on an attestation.
// this subject will be used to discover this attestor when searching by back ref subjects
// from a subsequent step in the policy.
type dummySubjectAttestor struct {
Data string
}
func (a *dummySubjectAttestor) Name() string {
return dummySubjectAttestorName
}
func (a *dummySubjectAttestor) Type() string {
return dummySubjectAttestorType
}
func (a *dummySubjectAttestor) RunType() attestation.RunType {
return attestation.PreMaterialRunType
}
func (a *dummySubjectAttestor) Attest(ctx *attestation.AttestationContext) error {
return nil
}
func (a *dummySubjectAttestor) Schema() *jsonschema.Schema {
return nil
}
func (a *dummySubjectAttestor) Subjects() map[string]cryptoutil.DigestSet {
return map[string]cryptoutil.DigestSet{
matchSubjectName: {
{Hash: crypto.SHA256}: "abcde",
},
}
}
// dummyBackrefAttestor is a test attestor used to expose a back ref subject, used to find
// attestations from preceding steps.
// for a practical example of this, consider policy that enforces two steps: a test step and a build step that produces a binary.
// when we begin policy evaluation, we only know two things: the hash of the binary, and the steps the policy expects.
// when we look up attestations that contain a product matching the binary's hash and satisfies the build step of the policy.
// that build attestation may contain a back ref subject that is the hash of the git commit, which also appears on the test attestation.
// we can then use this back ref subject to link the test attestation to the build attestation during policy evaluation.
type dummyBackrefAttestor struct{}
func (a *dummyBackrefAttestor) Name() string {
return dummyBackrefAttestorName
}
func (a *dummyBackrefAttestor) Type() string {
return dummyBackrefAttestorType
}
func (a *dummyBackrefAttestor) RunType() attestation.RunType {
return attestation.PreMaterialRunType
}
func (a *dummyBackrefAttestor) Attest(ctx *attestation.AttestationContext) error {
return nil
}
func (a *dummyBackrefAttestor) Schema() *jsonschema.Schema {
return nil
}
func (a *dummyBackrefAttestor) BackRefs() map[string]cryptoutil.DigestSet {
return map[string]cryptoutil.DigestSet{
matchSubjectName: {
{Hash: crypto.SHA256}: "abcde",
},
}
}