-
Notifications
You must be signed in to change notification settings - Fork 103
/
resource_self_signed_cert.go
457 lines (421 loc) · 16.7 KB
/
resource_self_signed_cert.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package provider
import (
"context"
"crypto/x509"
"fmt"
"net"
"net/url"
"strings"
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/listvalidator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"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-log/tflog"
"github.com/hashicorp/terraform-provider-tls/internal/provider/attribute_plan_modifier_bool"
)
type selfSignedCertResource struct{}
var (
_ resource.Resource = (*selfSignedCertResource)(nil)
_ resource.ResourceWithModifyPlan = (*selfSignedCertResource)(nil)
)
func NewSelfSignedCertResource() resource.Resource {
return &selfSignedCertResource{}
}
func (r *selfSignedCertResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_self_signed_cert"
}
func (r *selfSignedCertResource) Schema(_ context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
// Required attributes
"private_key_pem": schema.StringAttribute{
Required: true,
PlanModifiers: []planmodifier.String{
requireReplaceIfStateContainsPEMString(),
},
Sensitive: true,
Description: "Private key in [PEM (RFC 1421)](https://datatracker.ietf.org/doc/html/rfc1421) format, " +
"that the certificate will belong to. " +
"This can be read from a separate file using the [`file`](https://www.terraform.io/language/functions/file) " +
"interpolation function. ",
},
"validity_period_hours": schema.Int64Attribute{
Required: true,
PlanModifiers: []planmodifier.Int64{
int64planmodifier.RequiresReplace(),
},
Validators: []validator.Int64{
int64validator.AtLeast(0),
},
Description: "Number of hours, after initial issuing, that the certificate will remain valid for.",
},
"allowed_uses": schema.ListAttribute{
ElementType: types.StringType,
Required: true,
PlanModifiers: []planmodifier.List{
listplanmodifier.RequiresReplace(),
},
Validators: []validator.List{
listvalidator.ValueStringsAre(
stringvalidator.OneOf(supportedKeyUsagesStr()...),
),
},
Description: "List of key usages allowed for the issued certificate. " +
"Values are defined in [RFC 5280](https://datatracker.ietf.org/doc/html/rfc5280) " +
"and combine flags defined by both " +
"[Key Usages](https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.3) " +
"and [Extended Key Usages](https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.12). " +
fmt.Sprintf("Accepted values: `%s`.", strings.Join(supportedKeyUsagesStr(), "`, `")),
},
// Optional attributes
"dns_names": schema.ListAttribute{
ElementType: types.StringType,
Optional: true,
PlanModifiers: []planmodifier.List{
listplanmodifier.RequiresReplace(),
},
Description: "List of DNS names for which a certificate is being requested (i.e. certificate subjects).",
},
"ip_addresses": schema.ListAttribute{
ElementType: types.StringType,
Optional: true,
PlanModifiers: []planmodifier.List{
listplanmodifier.RequiresReplace(),
},
Validators: []validator.List{
listvalidator.ValueStringsAre(
stringvalidator.LengthAtLeast(1),
),
},
Description: "List of IP addresses for which a certificate is being requested (i.e. certificate subjects).",
},
"uris": schema.ListAttribute{
ElementType: types.StringType,
Optional: true,
PlanModifiers: []planmodifier.List{
listplanmodifier.RequiresReplace(),
},
Validators: []validator.List{
listvalidator.ValueStringsAre(
stringvalidator.LengthAtLeast(1),
),
},
Description: "List of URIs for which a certificate is being requested (i.e. certificate subjects).",
},
"early_renewal_hours": schema.Int64Attribute{
Optional: true,
Computed: true,
Default: int64default.StaticInt64(0),
Validators: []validator.Int64{
int64validator.AtLeast(0),
},
Description: "The resource will consider the certificate to have expired the given number of hours " +
"before its actual expiry time. This can be useful to deploy an updated certificate in advance of " +
"the expiration of the current certificate. " +
"However, the old certificate remains valid until its true expiration time, since this resource " +
"does not (and cannot) support certificate revocation. " +
"Also, this advance update can only be performed should the Terraform configuration be applied " +
"during the early renewal period. (default: `0`)",
},
"is_ca_certificate": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.RequiresReplace(),
},
Description: "Is the generated certificate representing a Certificate Authority (CA) (default: `false`).",
},
"set_subject_key_id": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.RequiresReplace(),
},
Description: "Should the generated certificate include a " +
"[subject key identifier](https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.2) (default: `false`).",
},
"set_authority_key_id": schema.BoolAttribute{
Optional: true,
Computed: true,
Default: booldefault.StaticBool(false),
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.RequiresReplace(),
},
Description: "Should the generated certificate include an " +
"[authority key identifier](https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.1): " +
"for self-signed certificates this is the same value as the " +
"[subject key identifier](https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.2) (default: `false`).",
},
// Computed attributes
"cert_pem": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Description: "Certificate data in [PEM (RFC 1421)](https://datatracker.ietf.org/doc/html/rfc1421) format. " +
"**NOTE**: the [underlying](https://pkg.go.dev/encoding/pem#Encode) " +
"[libraries](https://pkg.go.dev/golang.org/x/crypto/ssh#MarshalAuthorizedKey) that generate this " +
"value append a `\\n` at the end of the PEM. " +
"In case this disrupts your use case, we recommend using " +
"[`trimspace()`](https://www.terraform.io/language/functions/trimspace).",
},
"ready_for_renewal": schema.BoolAttribute{
Computed: true,
Default: booldefault.StaticBool(false),
PlanModifiers: []planmodifier.Bool{
attribute_plan_modifier_bool.ReadyForRenewal(),
},
Description: "Is the certificate either expired (i.e. beyond the `validity_period_hours`) " +
"or ready for an early renewal (i.e. within the `early_renewal_hours`)?",
},
"validity_start_time": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Description: "The time after which the certificate is valid, " +
"expressed as an [RFC3339](https://tools.ietf.org/html/rfc3339) timestamp.",
},
"validity_end_time": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Description: "The time until which the certificate is invalid, " +
"expressed as an [RFC3339](https://tools.ietf.org/html/rfc3339) timestamp.",
},
"key_algorithm": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Description: "Name of the algorithm used when generating the private key provided in `private_key_pem`. ",
},
"id": schema.StringAttribute{
Computed: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
Description: "Unique identifier for this resource: the certificate serial number.",
},
},
Blocks: map[string]schema.Block{
"subject": schema.ListNestedBlock{
// TODO Remove the validators below, once a fix for https://github.com/hashicorp/terraform-plugin-framework/issues/421 ships
Validators: []validator.List{
listvalidator.SizeBetween(0, 1),
},
PlanModifiers: []planmodifier.List{
listplanmodifier.RequiresReplace(),
},
NestedObject: schema.NestedBlockObject{
Attributes: map[string]schema.Attribute{
"organization": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "Distinguished name: `O`",
},
"common_name": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "Distinguished name: `CN`",
},
"organizational_unit": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "Distinguished name: `OU`",
},
"street_address": schema.ListAttribute{
ElementType: types.StringType,
Optional: true,
PlanModifiers: []planmodifier.List{
listplanmodifier.RequiresReplace(),
},
Description: "Distinguished name: `STREET`",
},
"locality": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "Distinguished name: `L`",
},
"province": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "Distinguished name: `ST`",
},
"country": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "Distinguished name: `C`",
},
"postal_code": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "Distinguished name: `PC`",
},
"serial_number": schema.StringAttribute{
Optional: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
Description: "Distinguished name: `SERIALNUMBER`",
},
},
},
MarkdownDescription: "The subject for which a certificate is being requested. " +
"The acceptable arguments are all optional and their naming is based upon " +
"[Issuer Distinguished Names (RFC5280)](https://tools.ietf.org/html/rfc5280#section-4.1.2.4) section.",
},
},
MarkdownDescription: "Creates a **self-signed** TLS certificate in " +
"[PEM (RFC 1421)](https://datatracker.ietf.org/doc/html/rfc1421) format.",
}
}
func (r *selfSignedCertResource) Create(ctx context.Context, req resource.CreateRequest, res *resource.CreateResponse) {
tflog.Debug(ctx, "Creating self signed certificate resource")
// Load entire configuration into the model
var newState selfSignedCertResourceModel
res.Diagnostics.Append(req.Plan.Get(ctx, &newState)...)
if res.Diagnostics.HasError() {
return
}
tflog.Debug(ctx, "Loaded self signed certificate configuration", map[string]interface{}{
"selfSignedCertConfig": fmt.Sprintf("%+v", newState),
})
// Parse the Private Key PEM
tflog.Debug(ctx, "Parsing private key PEM")
prvKey, algorithm, err := parsePrivateKeyPEM([]byte(newState.PrivateKeyPEM.ValueString()))
if err != nil {
res.Diagnostics.AddError("Failed to parse private key PEM", err.Error())
return
}
// Set the Algorithm of the Private Key
tflog.Debug(ctx, "Detected key algorithm of private key", map[string]interface{}{
"keyAlgorithm": algorithm,
})
newState.KeyAlgorithm = types.StringValue(algorithm.String())
cert := x509.Certificate{BasicConstraintsValid: true}
// Add Subject if provided
if !newState.Subject.IsNull() && !newState.Subject.IsUnknown() && len(newState.Subject.Elements()) > 0 {
tflog.Debug(ctx, "Adding subject on certificate", map[string]interface{}{
"subject": newState.Subject,
})
subject := make([]certificateSubjectModel, 1)
res.Diagnostics.Append(newState.Subject.ElementsAs(ctx, &subject, false)...)
if res.Diagnostics.HasError() {
return
}
cert.Subject = createSubjectDistinguishedNames(ctx, subject[0])
}
// Add DNS names if provided
if !newState.DNSNames.IsNull() && !newState.DNSNames.IsUnknown() {
tflog.Debug(ctx, "Adding DNS names on certificate", map[string]interface{}{
"dnsNames": newState.DNSNames,
})
newState.DNSNames.ElementsAs(ctx, &cert.DNSNames, false)
}
// Add IP addresses if provided
if !newState.IPAddresses.IsNull() && !newState.IPAddresses.IsUnknown() {
tflog.Debug(ctx, "Adding IP addresses on certificate", map[string]interface{}{
"ipAddresses": newState.IPAddresses,
})
var ipAddresses []string
res.Diagnostics.Append(newState.IPAddresses.ElementsAs(ctx, &ipAddresses, false)...)
if res.Diagnostics.HasError() {
return
}
for _, ipStr := range ipAddresses {
ip := net.ParseIP(ipStr)
if ip == nil {
res.Diagnostics.AddError(
"Invalid IP address",
fmt.Sprintf("Failed to parse %#v", ipStr),
)
return
}
cert.IPAddresses = append(cert.IPAddresses, ip)
}
}
// Add URIs if provided
if !newState.URIs.IsNull() && !newState.URIs.IsUnknown() {
tflog.Debug(ctx, "Adding URIs on certificate", map[string]interface{}{
"URIs": newState.URIs,
})
var uris []string
res.Diagnostics.Append(newState.URIs.ElementsAs(ctx, &uris, false)...)
if res.Diagnostics.HasError() {
return
}
for _, uriStr := range uris {
uri, err := url.Parse(uriStr)
if err != nil {
res.Diagnostics.AddError(
"Invalid URI",
fmt.Sprintf("Failed to parse %#v: %v", uriStr, err.Error()),
)
return
}
cert.URIs = append(cert.URIs, uri)
}
}
pubKey, err := privateKeyToPublicKey(prvKey)
if err != nil {
res.Diagnostics.AddError("Failed to get public key from private key", err.Error())
return
}
certificate, diags := createCertificate(ctx, &cert, &cert, pubKey, prvKey, &req.Plan)
if diags.HasError() {
res.Diagnostics.Append(diags...)
return
}
// Store the certificate into the state
tflog.Debug(ctx, "Storing self signed certificate into the state")
newState.ID = types.StringValue(certificate.id)
newState.CertPEM = types.StringValue(certificate.certPem)
newState.ValidityStartTime = types.StringValue(certificate.validityStartTime)
newState.ValidityEndTime = types.StringValue(certificate.validityEndTime)
res.Diagnostics.Append(res.State.Set(ctx, newState)...)
}
func (r *selfSignedCertResource) Read(ctx context.Context, req resource.ReadRequest, res *resource.ReadResponse) {
tflog.Debug(ctx, "Reading self signed certificate from state")
modifyStateIfCertificateReadyForRenewal(ctx, req, res)
}
func (r *selfSignedCertResource) Update(ctx context.Context, req resource.UpdateRequest, res *resource.UpdateResponse) {
tflog.Debug(ctx, "Updating self signed certificate")
updatedUsingPlan(ctx, &req, res, &selfSignedCertResourceModel{})
}
func (r *selfSignedCertResource) Delete(ctx context.Context, _ resource.DeleteRequest, _ *resource.DeleteResponse) {
// NO-OP: Returning no error is enough for the framework to remove the resource from state.
tflog.Debug(ctx, "Removing self signed certificate from state")
}
func (r *selfSignedCertResource) ModifyPlan(ctx context.Context, req resource.ModifyPlanRequest, res *resource.ModifyPlanResponse) {
modifyPlanIfCertificateReadyForRenewal(ctx, &req, res)
}