/
resource_attest.go
478 lines (422 loc) · 16.4 KB
/
resource_attest.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
package provider
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"github.com/chainguard-dev/terraform-provider-cosign/internal/secant"
stypes "github.com/chainguard-dev/terraform-provider-cosign/internal/secant/types"
"github.com/chainguard-dev/terraform-provider-oci/pkg/validators"
"github.com/google/go-containerregistry/pkg/name"
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-log/tflog"
"github.com/sigstore/cosign/v2/cmd/cosign/cli/options"
)
var (
_ resource.Resource = &AttestResource{}
_ resource.ResourceWithImportState = &AttestResource{}
)
func NewAttestResource() resource.Resource {
return &AttestResource{}
}
type AttestResource struct {
FulcioURL types.String
RekorURL types.String
popts *ProviderOpts
}
type PredicateObject struct {
PredicateType types.String `tfsdk:"type"`
Predicate types.String `tfsdk:"json"`
PredicateFile types.List `tfsdk:"file"`
}
type AttestResourceModel struct {
Id types.String `tfsdk:"id"`
Image types.String `tfsdk:"image"`
Conflict types.String `tfsdk:"conflict"`
// PredicateObject, left for backward compat.
PredicateType types.String `tfsdk:"predicate_type"`
Predicate types.String `tfsdk:"predicate"`
PredicateFile types.List `tfsdk:"predicate_file"`
Predicates types.List `tfsdk:"predicates"`
AttestedRef types.String `tfsdk:"attested_ref"`
FulcioURL types.String `tfsdk:"fulcio_url"`
RekorURL types.String `tfsdk:"rekor_url"`
}
func (r *AttestResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_attest"
}
func (r *AttestResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "This attests the provided image digest with cosign.",
Attributes: map[string]schema.Attribute{
"id": schema.StringAttribute{
Computed: true,
MarkdownDescription: "The immutable digest this resource attests.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"image": schema.StringAttribute{
MarkdownDescription: "The digest of the container image to attest.",
Optional: false,
Required: true,
Validators: []validator.String{validators.DigestValidator{}},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"conflict": schema.StringAttribute{
MarkdownDescription: "How to handle conflicting predicate values",
Computed: true,
Optional: true,
Required: false,
Default: stringdefault.StaticString("APPEND"),
Validators: []validator.String{ConflictValidator{}},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"predicate_type": schema.StringAttribute{
MarkdownDescription: "The in-toto predicate type of the claim being attested.",
Optional: true,
Required: false,
DeprecationMessage: "Use predicates instead.",
Validators: []validator.String{validators.URLValidator{}},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"predicate": schema.StringAttribute{
MarkdownDescription: "The JSON body of the in-toto predicate's claim.",
Optional: true,
Required: false,
DeprecationMessage: "Use predicates instead.",
Validators: []validator.String{
validators.JSONValidator{},
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"attested_ref": schema.StringAttribute{
MarkdownDescription: "This always matches the input digest, but is a convenience for composition.",
Computed: true,
},
"fulcio_url": schema.StringAttribute{
MarkdownDescription: "Address of sigstore PKI server (default https://fulcio.sigstore.dev).",
Optional: true,
Computed: true,
Default: stringdefault.StaticString("https://fulcio.sigstore.dev"),
PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()},
},
"rekor_url": schema.StringAttribute{
MarkdownDescription: "Address of rekor transparency log server (default https://rekor.sigstore.dev).",
Optional: true,
Computed: true,
Default: stringdefault.StaticString("https://rekor.sigstore.dev"),
PlanModifiers: []planmodifier.String{stringplanmodifier.RequiresReplace()},
},
},
Blocks: map[string]schema.Block{
"predicate_file": schema.ListNestedBlock{
MarkdownDescription: "The path and sha256 hex of the predicate to attest.",
Validators: []validator.List{listvalidator.SizeBetween(1, 1)},
DeprecationMessage: "Use predicates instead.",
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"sha256": schema.StringAttribute{
MarkdownDescription: "The sha256 hex hash of the predicate body.",
Optional: true,
Required: false,
Validators: []validator.String{
stringvalidator.AlsoRequires(path.MatchRoot("predicate_file").AtListIndex(0).AtName("path")),
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"path": schema.StringAttribute{
MarkdownDescription: "The path to a file containing the predicate to attest.",
Optional: true,
Required: false,
Validators: []validator.String{
stringvalidator.AlsoRequires(path.MatchRoot("predicate_file").AtListIndex(0).AtName("sha256")),
},
},
},
},
},
"predicates": schema.ListNestedBlock{
MarkdownDescription: "The path and sha256 hex of the predicate to attest.",
Validators: []validator.List{listvalidator.SizeAtLeast(1)},
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"type": schema.StringAttribute{
MarkdownDescription: "The in-toto predicate type of the claim being attested.",
Optional: false,
Required: true,
Validators: []validator.String{validators.URLValidator{}},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"json": schema.StringAttribute{
MarkdownDescription: "The JSON body of the in-toto predicate's claim.",
Optional: true,
Required: false,
Validators: []validator.String{
validators.JSONValidator{},
stringvalidator.ExactlyOneOf(
path.MatchRelative(),
path.MatchRelative().AtParent().AtName("file").AtListIndex(0).AtName("sha256"),
),
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
},
Blocks: map[string]schema.Block{
"file": schema.ListNestedBlock{
MarkdownDescription: "The path and sha256 hex of the predicate to attest.",
Validators: []validator.List{listvalidator.SizeBetween(1, 1)},
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"sha256": schema.StringAttribute{
MarkdownDescription: "The sha256 hex hash of the predicate body.",
Optional: true,
Required: false,
Validators: []validator.String{
stringvalidator.ExactlyOneOf(
path.MatchRelative(),
path.MatchRelative().AtParent().AtParent().AtParent().AtName("json"),
),
stringvalidator.AlsoRequires(path.MatchRelative().AtParent().AtName("path")),
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"path": schema.StringAttribute{
MarkdownDescription: "The path to a file containing the predicate to attest.",
Optional: true,
Required: false,
Validators: []validator.String{
stringvalidator.AlsoRequires(path.MatchRelative().AtParent().AtName("sha256")),
},
},
},
},
},
},
},
},
},
}
}
func (r *AttestResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
popts, ok := req.ProviderData.(*ProviderOpts)
if !ok || popts == nil {
resp.Diagnostics.AddError("Client Error", "invalid provider data")
return
}
r.popts = popts
}
func toPredObjects(ctx context.Context, arm *AttestResourceModel) ([]PredicateObject, diag.Diagnostics) {
preds := []PredicateObject{}
diags := arm.Predicates.ElementsAs(ctx, &preds, false)
if obj := toPredObject(arm); obj != nil {
preds = append(preds, *obj)
}
return preds, diags
}
// TODO: Remove this when we deprecate top-level predicate.
func toPredObject(data *AttestResourceModel) *PredicateObject {
if data.Predicate.ValueString() != "" || len(data.PredicateFile.Elements()) > 0 {
return &PredicateObject{
PredicateType: data.PredicateType,
PredicateFile: data.PredicateFile,
Predicate: data.Predicate,
}
}
return nil
}
func (r *AttestResource) doAttest(ctx context.Context, arm *AttestResourceModel, preds []PredicateObject) (string, error, error) {
digest, err := name.NewDigest(arm.Image.ValueString())
if err != nil {
return "", nil, errors.New("unable to parse image digest")
}
if os.Getenv("TF_COSIGN_DISABLE") != "" {
return digest.String(), errors.New("TF_COSIGN_DISABLE is set, skipping attesting"), nil
}
if !r.popts.oidc.Enabled(ctx) {
return digest.String(), errors.New("no ambient credentials are available to attest with, skipping attesting"), nil
}
statements := []*stypes.Statement{}
for _, data := range preds {
// Write the attestation to a temporary file.
var path string
switch {
// Write the predicate to a file to pass to attest.
case data.Predicate.ValueString() != "":
file, err := os.CreateTemp("", "")
if err != nil {
return "", nil, err
}
defer os.Remove(file.Name())
if _, err := file.WriteString(data.Predicate.ValueString()); err != nil {
return "", nil, err
}
if err := file.Close(); err != nil {
return "", nil, err
}
path = file.Name()
case len(data.PredicateFile.Elements()) > 0:
attrs := data.PredicateFile.Elements()[0].(basetypes.ObjectValue).Attributes()
path = attrs["path"].(basetypes.StringValue).ValueString()
expectedHash := attrs["sha256"].(basetypes.StringValue).ValueString()
contents, err := os.ReadFile(path)
if err != nil {
return "", nil, err
}
rawHash := sha256.Sum256(contents)
if got, want := hex.EncodeToString(rawHash[:]), expectedHash; got != want {
return "", nil, fmt.Errorf("sha256(%q) = %s, expected %s", path, got, want)
}
default:
return "", nil, errors.New("one of predicate or predicate_file must be specified")
}
predicate, err := os.Open(path)
if err != nil {
return "", nil, fmt.Errorf("open %q: %w", path, err)
}
stmt, err := secant.NewStatement(digest, predicate, data.PredicateType.ValueString())
if err != nil {
return "", nil, fmt.Errorf("creating attestation statement: %w", err)
}
statements = append(statements, stmt)
}
sv, err := r.popts.signerVerifier(arm.FulcioURL.ValueString())
if err != nil {
return "", nil, fmt.Errorf("creating signer: %w", err)
}
rekorClient, err := r.popts.rekorClient(arm.RekorURL.ValueString())
if err != nil {
return "", nil, fmt.Errorf("creating rekor client: %w", err)
}
ctx, cancel := context.WithTimeout(ctx, options.DefaultTimeout)
defer cancel()
if err := secant.Attest(ctx, arm.Conflict.ValueString(), statements, sv, rekorClient, r.popts.ropts); err != nil {
return "", nil, fmt.Errorf("unable to attest image %q: %w", digest.String(), err)
}
return digest.String(), nil, nil
}
func (r *AttestResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var data *AttestResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
preds, diags := toPredObjects(ctx, data)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
digest, warning, err := r.doAttest(ctx, data, preds)
if err != nil {
resp.Diagnostics.AddError("error while attesting", err.Error())
return
} else if warning != nil {
resp.Diagnostics.AddWarning("warning while attesting", warning.Error())
}
data.Id = types.StringValue(digest)
data.AttestedRef = types.StringValue(digest)
tflog.Trace(ctx, "created a resource")
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *AttestResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var data *AttestResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
digest, err := name.NewDigest(data.Image.ValueString())
if err != nil {
resp.Diagnostics.AddError("Client Error", fmt.Sprintf("Unable to parse image digest: %v", err))
return
}
data.Id = types.StringValue(digest.String())
data.AttestedRef = types.StringValue(digest.String())
// TODO(mattmoor): should we check that the signature didn't disappear?
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *AttestResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var data *AttestResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
preds, diags := toPredObjects(ctx, data)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
digest, warning, err := r.doAttest(ctx, data, preds)
if err != nil {
resp.Diagnostics.AddError("error while attesting", err.Error())
return
} else if warning != nil {
resp.Diagnostics.AddWarning("warning while attesting", warning.Error())
}
data.Id = types.StringValue(digest)
data.AttestedRef = types.StringValue(digest)
tflog.Trace(ctx, "updated a resource")
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *AttestResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var data *AttestResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
// TODO: If we ever want to delete the image from the registry, we can do it here.
}
func (r *AttestResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
}
// ConflictValidator is a string validator that checks that the string is valid OCI reference by digest.
type ConflictValidator struct{}
var _ validator.String = ConflictValidator{}
func (v ConflictValidator) Description(context.Context) string {
return "value must be one of (`APPEND`, `REPLACE`, `SKIPSAME`)"
}
func (v ConflictValidator) MarkdownDescription(ctx context.Context) string { return v.Description(ctx) }
func (v ConflictValidator) ValidateString(ctx context.Context, req validator.StringRequest, resp *validator.StringResponse) {
if req.ConfigValue.IsNull() || req.ConfigValue.IsUnknown() {
return
}
val := req.ConfigValue.ValueString()
switch val {
case "APPEND", "REPLACE", "SKIPSAME":
return
default:
resp.Diagnostics.AddError("error validating conflict", v.Description(ctx))
}
}