-
Notifications
You must be signed in to change notification settings - Fork 96
/
resource_akamai_cps_dv_enrollment.go
643 lines (609 loc) · 20.1 KB
/
resource_akamai_cps_dv_enrollment.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
package cps
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/cps"
"github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session"
"github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools"
"github.com/akamai/terraform-provider-akamai/v5/pkg/common/tf"
"github.com/akamai/terraform-provider-akamai/v5/pkg/common/timeouts"
"github.com/akamai/terraform-provider-akamai/v5/pkg/meta"
cpstools "github.com/akamai/terraform-provider-akamai/v5/pkg/providers/cps/tools"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
var (
// PollForChangeStatusInterval defines retry interval for getting status of a pending change
PollForChangeStatusInterval = 10 * time.Second
)
func resourceCPSDVEnrollment() *schema.Resource {
return &schema.Resource{
CreateContext: resourceCPSDVEnrollmentCreate,
ReadContext: resourceCPSDVEnrollmentRead,
UpdateContext: resourceCPSDVEnrollmentUpdate,
DeleteContext: resourceCPSDVEnrollmentDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceCPSDVEnrollmentImport,
},
Schema: map[string]*schema.Schema{
"common_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Common name used for enrollment",
},
"allow_duplicate_common_name": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Allow to duplicate common name",
},
"sans": {
Type: schema.TypeSet,
Optional: true,
Elem: &schema.Schema{Type: schema.TypeString},
Description: "List of SANs",
},
"secure_network": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "Type of TLS deployment network",
},
"sni_only": {
Type: schema.TypeBool,
Required: true,
ForceNew: true,
Description: "Whether Server Name Indication is used for enrollment",
},
"acknowledge_pre_verification_warnings": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Whether acknowledge warnings before certificate verification",
},
"admin_contact": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
MaxItems: 1,
Elem: contact,
Description: "Contact information for the certificate administrator to use at organization",
},
"certificate_chain_type": {
Type: schema.TypeString,
Default: "default",
Optional: true,
Description: "Certificate trust chain type",
},
"csr": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
MaxItems: 1,
Elem: csr,
Description: "Certificate signing request generated during enrollment creation",
},
"network_configuration": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
MaxItems: 1,
Elem: networkConfiguration,
Description: "Settings containing network information and TLS Metadata used by CPS",
},
"signature_algorithm": {
Type: schema.TypeString,
Required: true,
Description: "SHA algorithm type",
},
"tech_contact": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
MaxItems: 1,
Elem: contact,
Description: "Contact information for an administrator at Akamai",
},
"organization": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
MaxItems: 1,
Elem: organization,
Description: "Organization information",
},
"contract_id": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
DiffSuppressFunc: tf.FieldPrefixSuppress("ctr_"),
Description: "Contract ID for which enrollment is retrieved",
},
"certificate_type": {
Type: schema.TypeString,
Computed: true,
Description: "Certificate type of enrollment",
},
"validation_type": {
Type: schema.TypeString,
Computed: true,
Description: "Enrolment validation type",
},
"registration_authority": {
Type: schema.TypeString,
Computed: true,
Description: "The registration authority or certificate authority (CA) used to obtain a certificate",
},
"dns_challenges": {
Type: schema.TypeSet,
Computed: true,
Description: "DNS challenge information",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"domain": {
Type: schema.TypeString,
Computed: true,
Description: "Domain for which the challenges were completed",
},
"full_path": {
Type: schema.TypeString,
Computed: true,
Description: "The domain name where Akamai publishes the response body to validate",
},
"response_body": {
Type: schema.TypeString,
Computed: true,
Description: "The unique content of the challenge",
},
},
},
Set: cpstools.HashFromChallengesMap,
},
"http_challenges": {
Type: schema.TypeSet,
Computed: true,
Description: "HTTP challenge information",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"domain": {
Type: schema.TypeString,
Computed: true,
Description: "Domain for which the challenges were completed",
},
"full_path": {
Type: schema.TypeString,
Computed: true,
Description: "The URL where Akamai publishes the response body to validate",
},
"response_body": {
Type: schema.TypeString,
Computed: true,
Description: "The unique content of the challenge",
},
},
},
Set: cpstools.HashFromChallengesMap,
},
"timeouts": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Description: "Enables to set timeout for processing",
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"default": {
Type: schema.TypeString,
Optional: true,
ValidateDiagFunc: timeouts.ValidateDurationFormat,
},
},
},
},
},
CustomizeDiff: customdiff.Sequence(
func(ctx context.Context, diff *schema.ResourceDiff, i interface{}) error {
if !diff.HasChange("sans") {
return nil
}
domainsToValidate := []interface{}{map[string]interface{}{
"domain": strings.ToLower(diff.Get("common_name").(string)),
}}
if sans, ok := diff.Get("sans").(*schema.Set); ok {
for _, san := range sans.List() {
domain := map[string]interface{}{"domain": strings.ToLower(san.(string))}
domainsToValidate = append(domainsToValidate, domain)
}
}
if err := diff.SetNew("http_challenges", schema.NewSet(cpstools.HashFromChallengesMap, domainsToValidate)); err != nil {
return fmt.Errorf("%w: %s", tf.ErrValueSet, err.Error())
}
if err := diff.SetNew("dns_challenges", schema.NewSet(cpstools.HashFromChallengesMap, domainsToValidate)); err != nil {
return fmt.Errorf("%w: %s", tf.ErrValueSet, err.Error())
}
return nil
}),
Timeouts: &schema.ResourceTimeout{
Default: &timeouts.SDKDefaultTimeout,
},
}
}
func resourceCPSDVEnrollmentCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
meta := meta.Must(m)
logger := meta.Log("CPS", "resourceCPSDVEnrollmentCreate")
// create a context with logging for api calls
ctx = session.ContextWithOptions(
ctx,
session.WithContextLog(logger),
)
client := inst.Client(meta)
logger.Debug("Creating enrollment")
enrollment := cps.Enrollment{
CertificateType: "san",
ValidationType: "dv",
RA: "lets-encrypt",
}
if err := d.Set("certificate_type", enrollment.CertificateType); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
if err := d.Set("validation_type", enrollment.ValidationType); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
if err := d.Set("registration_authority", enrollment.RA); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
adminContactSet, err := tf.GetSetValue("admin_contact", d)
if err != nil {
return diag.FromErr(err)
}
adminContact, err := cpstools.GetContactInfo(adminContactSet)
if err != nil {
return diag.Errorf("'admin_contact' - %s", err)
}
enrollment.AdminContact = adminContact
techContactSet, err := tf.GetSetValue("tech_contact", d)
if err != nil {
return diag.FromErr(err)
}
techContact, err := cpstools.GetContactInfo(techContactSet)
if err != nil {
return diag.Errorf("'tech_contact' - %s", err)
}
enrollment.TechContact = techContact
certificateChainType, err := tf.GetStringValue("certificate_chain_type", d)
if err != nil && !errors.Is(err, tf.ErrNotFound) {
return diag.FromErr(err)
}
enrollment.CertificateChainType = certificateChainType
csr, err := cpstools.GetCSR(d)
if err != nil {
return diag.FromErr(err)
}
enrollment.CSR = csr
// DV does not support multi stack certificates
enrollment.EnableMultiStackedCertificates = false
networkConfig, err := cpstools.GetNetworkConfig(d)
if err != nil {
return diag.FromErr(err)
}
enrollment.NetworkConfiguration = networkConfig
signatureAlgorithm, err := tf.GetStringValue("signature_algorithm", d)
if err != nil {
return diag.FromErr(err)
}
enrollment.SignatureAlgorithm = signatureAlgorithm
organization, err := cpstools.GetOrg(d)
if err != nil {
return diag.FromErr(err)
}
enrollment.Org = organization
contractID, err := tf.GetStringValue("contract_id", d)
if err != nil {
return diag.FromErr(err)
}
allowDuplicateCN, err := tf.GetBoolValue("allow_duplicate_common_name", d)
if err != nil {
return diag.FromErr(err)
}
// save ClientMutualAuthentication and unset it in enrollment request struct
// create request must not have it set; in case its not nil, we will run update later to add it
clientMutualAuthentication := enrollment.NetworkConfiguration.ClientMutualAuthentication
enrollment.NetworkConfiguration.ClientMutualAuthentication = nil
req := cps.CreateEnrollmentRequest{
Enrollment: enrollment,
ContractID: strings.TrimPrefix(contractID, "ctr_"),
AllowDuplicateCN: allowDuplicateCN,
}
res, err := client.CreateEnrollment(ctx, req)
if err != nil {
return diag.FromErr(err)
}
d.SetId(strconv.Itoa(res.ID))
acknowledgeWarnings, err := tf.GetBoolValue("acknowledge_pre_verification_warnings", d)
if err != nil && !errors.Is(err, tf.ErrNotFound) {
return diag.FromErr(err)
}
// when clientMutualAuthentication was provided, insert it back to enrollment and send the update request
if clientMutualAuthentication != nil {
logger.Debug("Updating ClientMutualAuthentication configuration")
enrollment.NetworkConfiguration.ClientMutualAuthentication = clientMutualAuthentication
req := cps.UpdateEnrollmentRequest{
EnrollmentID: res.ID,
Enrollment: enrollment,
AllowCancelPendingChanges: tools.BoolPtr(true),
}
_, err := client.UpdateEnrollment(ctx, req)
if err != nil {
return diag.FromErr(err)
}
}
if err = waitForVerification(ctx, logger, client, res.ID, acknowledgeWarnings, nil); err != nil {
return diag.FromErr(err)
}
return resourceCPSDVEnrollmentRead(ctx, d, m)
}
func resourceCPSDVEnrollmentRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
meta := meta.Must(m)
logger := meta.Log("CPS", "resourceCPSDVEnrollmentRead")
// create a context with logging for api calls
ctx = session.ContextWithOptions(
ctx,
session.WithContextLog(logger),
)
client := inst.Client(meta)
logger.Debug("Reading enrollment")
enrollmentID, err := strconv.Atoi(d.Id())
if err != nil {
return diag.FromErr(err)
}
req := cps.GetEnrollmentRequest{EnrollmentID: enrollmentID}
enrollment, err := client.GetEnrollment(ctx, req)
if err != nil {
return diag.FromErr(err)
}
attrs, err := readAttrs(enrollment, d)
if err != nil {
return diag.FromErr(err)
}
attrs["certificate_type"] = enrollment.CertificateType
attrs["validation_type"] = enrollment.ValidationType
attrs["registration_authority"] = enrollment.RA
err = tf.SetAttrs(d, attrs)
if err != nil {
return diag.FromErr(err)
}
dnsChallenges := make([]interface{}, 0)
httpChallenges := make([]interface{}, 0)
changeID, err := cpstools.GetChangeIDFromPendingChanges(enrollment.PendingChanges)
if err != nil {
if errors.Is(err, cpstools.ErrNoPendingChanges) {
logger.Debugf("No pending changes found on the enrollment")
if err := d.Set("http_challenges", httpChallenges); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
if err := d.Set("dns_challenges", schema.NewSet(cpstools.HashFromChallengesMap, dnsChallenges)); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
return nil
}
return diag.FromErr(err)
}
changeStatusReq := cps.GetChangeStatusRequest{
EnrollmentID: enrollmentID,
ChangeID: changeID,
}
status, err := client.GetChangeStatus(ctx, changeStatusReq)
if err != nil {
return diag.FromErr(err)
}
if len(status.AllowedInput) < 1 || status.AllowedInput[0].Type != "lets-encrypt-challenges" {
if err := d.Set("http_challenges", httpChallenges); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
if err := d.Set("dns_challenges", schema.NewSet(cpstools.HashFromChallengesMap, dnsChallenges)); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
return nil
}
getChallengesReq := cps.GetChangeRequest{
EnrollmentID: enrollmentID,
ChangeID: changeID,
}
challenges, err := client.GetChangeLetsEncryptChallenges(ctx, getChallengesReq)
if err != nil {
return diag.FromErr(err)
}
for _, dv := range challenges.DV {
if dv.ValidationStatus == "VALIDATED" {
continue
}
for _, challenge := range dv.Challenges {
if challenge.Status != "pending" {
continue
}
if challenge.Type == "http-01" {
httpChallenges = append(httpChallenges, map[string]interface{}{
"full_path": challenge.FullPath,
"response_body": challenge.ResponseBody,
"domain": dv.Domain,
})
}
if challenge.Type == "dns-01" {
dnsChallenges = append(dnsChallenges, map[string]interface{}{
"full_path": challenge.FullPath,
"response_body": challenge.ResponseBody,
"domain": dv.Domain,
})
}
}
}
if err := d.Set("http_challenges", httpChallenges); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
if err := d.Set("dns_challenges", schema.NewSet(cpstools.HashFromChallengesMap, dnsChallenges)); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
return nil
}
func resourceCPSDVEnrollmentUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
meta := meta.Must(m)
logger := meta.Log("CPS", "resourceCPSDVEnrollmentUpdate")
ctx = session.ContextWithOptions(
ctx,
session.WithContextLog(logger),
)
client := inst.Client(meta)
logger.Debug("Updating enrollment")
if !d.HasChangeExcept("timeouts") {
logger.Debug("Only timeouts were updated, skipping")
return nil
}
acknowledgeWarnings, err := tf.GetBoolValue("acknowledge_pre_verification_warnings", d)
if err != nil && !errors.Is(err, tf.ErrNotFound) {
return diag.FromErr(err)
}
enrollmentID, err := strconv.Atoi(d.Id())
if err != nil {
return diag.FromErr(err)
}
if !d.HasChanges(
"sans",
"admin_contact",
"tech_contact",
"certificate_chain_type",
"csr",
"network_configuration",
"signature_algorithm",
"organization",
) {
logger.Debug("Enrollment does not have to be updated. Verifying status.")
if err = waitForVerification(ctx, logger, client, enrollmentID, acknowledgeWarnings, nil); err != nil {
return diag.FromErr(err)
}
return resourceCPSDVEnrollmentRead(ctx, d, m)
}
enrollment := cps.Enrollment{
CertificateType: "san",
ValidationType: "dv",
RA: "lets-encrypt",
}
if err := d.Set("certificate_type", "san"); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
if err := d.Set("validation_type", "dv"); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
if err := d.Set("registration_authority", "lets-encrypt"); err != nil {
return diag.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
adminContactSet, err := tf.GetSetValue("admin_contact", d)
if err != nil {
return diag.FromErr(err)
}
adminContact, err := cpstools.GetContactInfo(adminContactSet)
if err != nil {
return diag.Errorf("'admin_contact' - %s", err)
}
enrollment.AdminContact = adminContact
techContactSet, err := tf.GetSetValue("tech_contact", d)
if err != nil {
return diag.FromErr(err)
}
techContact, err := cpstools.GetContactInfo(techContactSet)
if err != nil {
return diag.Errorf("'tech_contact' - %s", err)
}
enrollment.TechContact = techContact
certificateChainType, err := tf.GetStringValue("certificate_chain_type", d)
if err != nil && !errors.Is(err, tf.ErrNotFound) {
return diag.FromErr(err)
}
enrollment.CertificateChainType = certificateChainType
csr, err := cpstools.GetCSR(d)
if err != nil {
return diag.FromErr(err)
}
enrollment.CSR = csr
// DV does not support multi stack certificates
enrollment.EnableMultiStackedCertificates = false
networkConfig, err := cpstools.GetNetworkConfig(d)
if err != nil {
return diag.FromErr(err)
}
enrollment.NetworkConfiguration = networkConfig
signatureAlgorithm, err := tf.GetStringValue("signature_algorithm", d)
if err != nil && !errors.Is(err, tf.ErrNotFound) {
return diag.FromErr(err)
}
enrollment.SignatureAlgorithm = signatureAlgorithm
organization, err := cpstools.GetOrg(d)
if err != nil {
return diag.FromErr(err)
}
enrollment.Org = organization
allowCancel := true
req := cps.UpdateEnrollmentRequest{
Enrollment: enrollment,
EnrollmentID: enrollmentID,
AllowCancelPendingChanges: &allowCancel,
}
if _, err := client.UpdateEnrollment(ctx, req); err != nil {
return diag.FromErr(err)
}
d.SetId(strconv.Itoa(enrollmentID))
if err = waitForVerification(ctx, logger, client, enrollmentID, acknowledgeWarnings, nil); err != nil {
return diag.FromErr(err)
}
return resourceCPSDVEnrollmentRead(ctx, d, m)
}
func resourceCPSDVEnrollmentDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
return enrollmentDelete(ctx, d, m, "resourceCPSDVEnrollmentDelete")
}
func resourceCPSDVEnrollmentImport(ctx context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
meta := meta.Must(m)
logger := meta.Log("CPS", "resourceCPSDVEnrollmentImport")
// create a context with logging for api calls
ctx = session.ContextWithOptions(
ctx,
session.WithContextLog(logger),
)
logger.Debug("Importing enrollment")
parts := strings.Split(d.Id(), ",")
if len(parts) != 2 {
return nil, fmt.Errorf("import id has to be a comma separated list of enrollment id and contract id")
}
enrollmentID := parts[0]
contractID := parts[1]
if enrollmentID == "" || contractID == "" {
return nil, fmt.Errorf("enrollment and contract IDs must have non empty values")
}
eid, err := strconv.Atoi(enrollmentID)
if err != nil {
return nil, fmt.Errorf("enrollment ID must be a number: %s", err)
}
client := inst.Client(meta)
req := cps.GetEnrollmentRequest{EnrollmentID: eid}
enrollment, err := client.GetEnrollment(ctx, req)
if err != nil {
return nil, fmt.Errorf("unable to fetch enrollment: %s", err)
}
if enrollment.ValidationType != "dv" {
return nil, fmt.Errorf("unable to import: wrong validation type: expected 'dv', got '%s'", enrollment.ValidationType)
}
if err := d.Set("allow_duplicate_common_name", false); err != nil {
return nil, fmt.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
if err := d.Set("acknowledge_pre_verification_warnings", false); err != nil {
return nil, fmt.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
if err := d.Set("contract_id", contractID); err != nil {
return nil, fmt.Errorf("%v: %s", tf.ErrValueSet, err.Error())
}
d.SetId(enrollmentID)
return []*schema.ResourceData{d}, nil
}