-
Notifications
You must be signed in to change notification settings - Fork 26
/
v02.go
343 lines (280 loc) · 9.22 KB
/
v02.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
//
// Copyright 2024 The Chainloop Authors.
//
// 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 chainloop
import (
"crypto/sha256"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
v1 "github.com/chainloop-dev/chainloop/internal/attestation/crafter/api/attestation/v1"
crv1 "github.com/google/go-containerregistry/pkg/v1"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/structpb"
schemaapi "github.com/chainloop-dev/chainloop/app/controlplane/api/workflowcontract/v1"
intoto "github.com/in-toto/attestation/go/v1"
)
// Replace custom material type with https://github.com/in-toto/attestation/blob/main/spec/v1.0/resource_descriptor.md
const PredicateTypeV02 = "chainloop.dev/attestation/v0.2"
type ProvenancePredicateV02 struct {
*ProvenancePredicateCommon
Materials []*intoto.ResourceDescriptor `json:"materials,omitempty"`
}
type RendererV02 struct {
*RendererCommon
}
func NewChainloopRendererV02(att *v1.Attestation, builderVersion, builderDigest string) *RendererV02 {
return &RendererV02{&RendererCommon{
PredicateTypeV02, att, &builderInfo{builderVersion, builderDigest}},
}
}
func (r *RendererV02) Statement() (*intoto.Statement, error) {
subject, err := r.subject()
if err != nil {
return nil, fmt.Errorf("error creating subject: %w", err)
}
predicate, err := r.predicate()
if err != nil {
return nil, fmt.Errorf("error creating predicate: %w", err)
}
statement := &intoto.Statement{
Type: intoto.StatementTypeUri,
Subject: subject,
PredicateType: r.predicateType,
Predicate: predicate,
}
return statement, nil
}
func commitAnnotations(c *v1.Commit) (*structpb.Struct, error) {
annotationsRaw := map[string]interface{}{
subjectGitAnnotationWhen: c.GetDate().AsTime().Format(time.RFC3339),
subjectGitAnnotationAuthorEmail: c.GetAuthorEmail(),
subjectGitAnnotationAuthorName: c.GetAuthorName(),
subjectGitAnnotationMessage: c.GetMessage(),
}
if remotes := c.GetRemotes(); len(remotes) > 0 {
remotesRaw := []interface{}{}
for _, r := range remotes {
remotesRaw = append(remotesRaw, map[string]interface{}{
"name": r.GetName(),
"url": r.GetUrl(),
})
}
annotationsRaw[subjectGitAnnotationRemotes] = remotesRaw
}
return structpb.NewStruct(annotationsRaw)
}
func (r *RendererV02) subject() ([]*intoto.ResourceDescriptor, error) {
raw, err := json.Marshal(r.att)
if err != nil {
return nil, err
}
// We might don't want this and just force the existence of one material with output = true
subject := []*intoto.ResourceDescriptor{
{
Name: prefixed(fmt.Sprintf("workflow.%s", r.att.GetWorkflow().Name)),
Digest: map[string]string{
"sha256": fmt.Sprintf("%x", sha256.Sum256(raw)),
},
},
}
if head := r.att.GetHead(); head != nil {
annotations, err := commitAnnotations(head)
if err != nil {
return nil, fmt.Errorf("error creating annotations: %w", err)
}
subject = append(subject, &intoto.ResourceDescriptor{
Name: SubjectGitHead,
Digest: map[string]string{"sha1": head.GetHash()},
Annotations: annotations,
})
}
normalizedMaterials, err := outputMaterials(r.att, true)
if err != nil {
return nil, fmt.Errorf("error normalizing materials: %w", err)
}
for _, m := range normalizedMaterials {
if m.Digest != nil {
subject = append(subject, &intoto.ResourceDescriptor{
Name: m.Name,
Digest: m.Digest,
Annotations: m.Annotations,
})
}
}
return subject, nil
}
func (r *RendererV02) predicate() (*structpb.Struct, error) {
normalizedMaterials, err := outputMaterials(r.att, false)
if err != nil {
return nil, fmt.Errorf("error normalizing materials: %w", err)
}
p := ProvenancePredicateV02{
ProvenancePredicateCommon: predicateCommon(r.builder, r.att),
Materials: normalizedMaterials,
}
// transform to structpb.Struct in a two steps process
// 1 - ProvenancePredicate -> json
// 2 - json -> structpb.Struct
predicateJSON, err := json.Marshal(p)
if err != nil {
return nil, fmt.Errorf("error marshaling predicate: %w", err)
}
predicate := &structpb.Struct{}
if err := protojson.Unmarshal(predicateJSON, predicate); err != nil {
return nil, fmt.Errorf("error unmarshaling predicate: %w", err)
}
return predicate, nil
}
func outputMaterials(att *v1.Attestation, onlyOutput bool) ([]*intoto.ResourceDescriptor, error) {
// Sort material keys to stabilize output
keys := make([]string, 0, len(att.GetMaterials()))
for k := range att.GetMaterials() {
keys = append(keys, k)
}
sort.Strings(keys)
res := []*intoto.ResourceDescriptor{}
materials := att.GetMaterials()
for _, mdefName := range keys {
mdef := materials[mdefName]
artifactType := mdef.MaterialType
nMaterial, err := mdef.NormalizedOutput()
if err != nil {
return nil, fmt.Errorf("error normalizing material: %w", err)
}
// Skip if we are expecting to show only the materials marked as output
if onlyOutput && !nMaterial.IsOutput {
continue
}
material := &intoto.ResourceDescriptor{}
if artifactType == schemaapi.CraftingSchema_Material_STRING {
material.Content = nMaterial.Content
}
if digest := nMaterial.Digest; digest != "" {
parts := strings.Split(digest, ":")
material.Digest = map[string]string{
parts[0]: parts[1],
}
material.Name = nMaterial.Name
material.Content = nMaterial.Content
}
// Required, built-in annotations
annotationsM := map[string]interface{}{
AnnotationMaterialType: artifactType.String(),
AnnotationMaterialName: mdefName,
}
// Set the special annotations for container images
if artifactType == schemaapi.CraftingSchema_Material_CONTAINER_IMAGE {
if tag := mdef.GetContainerImage().GetTag(); tag != "" {
annotationsM[annotationContainerTag] = tag
}
}
// Custom annotations, it does not override the built-in ones
for k, v := range mdef.Annotations {
_, ok := annotationsM[k]
if !ok {
annotationsM[k] = v
}
}
if mdef.UploadedToCas {
annotationsM[AnnotationMaterialCAS] = true
} else if mdef.InlineCas {
annotationsM[annotationMaterialInlineCAS] = true
}
material.Annotations, err = structpb.NewStruct(annotationsM)
if err != nil {
return nil, fmt.Errorf("error creating annotations: %w", err)
}
res = append(res, material)
}
return res, nil
}
// Implement NormalizablePredicate interface
func (p *ProvenancePredicateV02) GetMaterials() []*NormalizedMaterial {
res := make([]*NormalizedMaterial, 0, len(p.Materials))
for _, material := range p.Materials {
m, err := normalizeMaterial(material)
if err != nil {
continue
}
res = append(res, m)
}
return res
}
// Translate a ResourceDescriptor to a NormalizedMaterial
func normalizeMaterial(material *intoto.ResourceDescriptor) (*NormalizedMaterial, error) {
m := &NormalizedMaterial{}
// Set custom annotations
m.Annotations = make(map[string]string)
mAnnotationsMap := material.Annotations.GetFields()
for k, v := range mAnnotationsMap {
// if the annotation key doesn't start with chainloop.
// we set it as a custom annotation
if strings.HasPrefix(k, rendererPrefix) {
continue
}
m.Annotations[k] = v.GetStringValue()
}
mType, ok := mAnnotationsMap[AnnotationMaterialType]
if !ok {
return nil, fmt.Errorf("material type not found")
}
// Set the type
m.Type = mType.GetStringValue()
mName, ok := mAnnotationsMap[AnnotationMaterialName]
if !ok {
return nil, fmt.Errorf("material name not found")
}
// Set the Material Name
m.Name = mName.GetStringValue()
// Set the Value
// If we have a string material, we just set the value
if m.Type == schemaapi.CraftingSchema_Material_STRING.String() {
if material.Content == nil {
return nil, fmt.Errorf("material content not found")
}
m.Value = string(material.Content)
return m, nil
}
// for the rest of the materials we use both the name and the digest
d, ok := material.Digest["sha256"]
if !ok {
return nil, fmt.Errorf("material digest not found")
}
m.Hash = &crv1.Hash{Algorithm: "sha256", Hex: d}
// material.Name in a container image is the path to the image
// in an artifact type or derivative means the name of the file
if material.Name == "" {
return nil, fmt.Errorf("material name not found")
}
// In the case of container images for example the value is in the name field
m.Value = material.Name
if v, ok := mAnnotationsMap[AnnotationMaterialCAS]; ok && v.GetBoolValue() {
m.UploadedToCAS = true
}
if v, ok := mAnnotationsMap[annotationMaterialInlineCAS]; ok && v.GetBoolValue() {
m.EmbeddedInline = true
}
// In the case of an artifact type or derivative the filename is set and the inline content if any
if m.EmbeddedInline || m.UploadedToCAS {
m.Filename = material.Name
m.Value = ""
}
if m.EmbeddedInline {
m.Value = string(material.Content)
}
return m, nil
}