-
Notifications
You must be signed in to change notification settings - Fork 70
/
enrollments.go
531 lines (455 loc) · 20.6 KB
/
enrollments.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
package cps
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"github.com/akamai/AkamaiOPEN-edgegrid-golang/v9/pkg/session"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
type (
// ListEnrollmentsResponse represents list of CPS enrollment objects under given contractId. It is used as a response body while fetching enrollments by contractId
ListEnrollmentsResponse struct {
Enrollments []Enrollment `json:"enrollments"`
}
// GetEnrollmentResponse contains response body from GetEnrollment operation
GetEnrollmentResponse Enrollment
// Enrollment represents a CPS enrollment object. It is used as a response body while fetching enrollment by ID and listing multiple enrollments
Enrollment struct {
ID int `json:"id"`
ProductionSlots []int `json:"productionSlots"`
StagingSlots []int `json:"stagingSlots"`
AssignedSlots []int `json:"assignedSlots"`
AdminContact *Contact `json:"adminContact"`
AutoRenewalStartTime string `json:"autoRenewalStartTime,omitempty"`
CertificateChainType string `json:"certificateChainType,omitempty"`
CertificateType string `json:"certificateType"`
ChangeManagement bool `json:"changeManagement"`
CSR *CSR `json:"csr"`
EnableMultiStackedCertificates bool `json:"enableMultiStackedCertificates"`
Location string `json:"location,omitempty"`
MaxAllowedSanNames int `json:"maxAllowedSanNames,omitempty"`
MaxAllowedWildcardSanNames int `json:"maxAllowedWildcardSanNames,omitempty"`
NetworkConfiguration *NetworkConfiguration `json:"networkConfiguration"`
Org *Org `json:"org"`
OrgID *int `json:"orgId"`
PendingChanges []PendingChange `json:"pendingChanges,omitempty"`
RA string `json:"ra"`
SignatureAlgorithm string `json:"signatureAlgorithm,omitempty"`
TechContact *Contact `json:"techContact"`
ThirdParty *ThirdParty `json:"thirdParty,omitempty"`
ValidationType string `json:"validationType"`
}
// Contact contains contact information
Contact struct {
AddressLineOne string `json:"addressLineOne,omitempty"`
AddressLineTwo string `json:"addressLineTwo,omitempty"`
City string `json:"city,omitempty"`
Country string `json:"country,omitempty"`
Email string `json:"email,omitempty"`
FirstName string `json:"firstName,omitempty"`
LastName string `json:"lastName,omitempty"`
OrganizationName string `json:"organizationName,omitempty"`
Phone string `json:"phone,omitempty"`
PostalCode string `json:"postalCode,omitempty"`
Region string `json:"region,omitempty"`
Title string `json:"title,omitempty"`
}
// CSR is a Certificate Signing Request object
CSR struct {
C string `json:"c,omitempty"`
CN string `json:"cn"`
L string `json:"l,omitempty"`
O string `json:"o,omitempty"`
OU string `json:"ou,omitempty"`
PreferredTrustChain string `json:"preferredTrustChain,omitempty"`
SANS []string `json:"sans,omitempty"`
ST string `json:"st,omitempty"`
}
// NetworkConfiguration contains settings that specify any network information and TLS Metadata you want CPS to use to push the completed certificate to the network
NetworkConfiguration struct {
ClientMutualAuthentication *ClientMutualAuthentication `json:"clientMutualAuthentication,omitempty"`
DisallowedTLSVersions []string `json:"disallowedTlsVersions,omitempty"`
DNSNameSettings *DNSNameSettings `json:"dnsNameSettings,omitempty"`
Geography string `json:"geography,omitempty"`
MustHaveCiphers string `json:"mustHaveCiphers,omitempty"`
OCSPStapling OCSPStapling `json:"ocspStapling,omitempty"`
PreferredCiphers string `json:"preferredCiphers,omitempty"`
QuicEnabled bool `json:"quicEnabled"`
SecureNetwork string `json:"secureNetwork,omitempty"`
SNIOnly bool `json:"sniOnly"`
}
// ClientMutualAuthentication specifies the trust chain that is used to verify client certificates and some configuration options
ClientMutualAuthentication struct {
AuthenticationOptions *AuthenticationOptions `json:"authenticationOptions,omitempty"`
SetID string `json:"setId,omitempty"`
}
// AuthenticationOptions contain the configuration options for the selected trust chain
AuthenticationOptions struct {
OCSP *OCSP `json:"ocsp,omitempty"`
SendCAListToClient *bool `json:"sendCaListToClient,omitempty"`
}
// OCSP specifies whether you want to enable ocsp stapling for client certificates
OCSP struct {
Enabled *bool `json:"enabled,omitempty"`
}
// DNSNameSettings contain DNS name setting in given network configuration
DNSNameSettings struct {
CloneDNSNames bool `json:"cloneDnsNames"`
DNSNames []string `json:"dnsNames,omitempty"`
}
// Org represents organization information
Org struct {
AddressLineOne string `json:"addressLineOne,omitempty"`
AddressLineTwo string `json:"addressLineTwo,omitempty"`
City string `json:"city,omitempty"`
Country string `json:"country,omitempty"`
Name string `json:"name,omitempty"`
Phone string `json:"phone,omitempty"`
PostalCode string `json:"postalCode,omitempty"`
Region string `json:"region,omitempty"`
}
// PendingChange represents pending change information
PendingChange struct {
ChangeType string `json:"changeType,omitempty"`
Location string `json:"location,omitempty"`
}
// ThirdParty specifies that you want to use a third party certificate
ThirdParty struct {
ExcludeSANS bool `json:"excludeSans"`
}
// ListEnrollmentsRequest contains Contract ID of enrollments that are to be fetched with ListEnrollments
ListEnrollmentsRequest struct {
ContractID string
}
// GetEnrollmentRequest contains ID of an enrollment that is to be fetched with GetEnrollment
GetEnrollmentRequest struct {
EnrollmentID int
}
// CreateEnrollmentRequest contains request body and path parameters used to create an enrollment
CreateEnrollmentRequest struct {
EnrollmentRequestBody
ContractID string
DeployNotAfter string
DeployNotBefore string
AllowDuplicateCN bool
}
// EnrollmentRequestBody represents request body parameters specific to the enrollment
EnrollmentRequestBody struct {
AdminContact *Contact `json:"adminContact"`
AutoRenewalStartTime string `json:"autoRenewalStartTime,omitempty"`
CertificateChainType string `json:"certificateChainType,omitempty"`
CertificateType string `json:"certificateType"`
ChangeManagement bool `json:"changeManagement"`
CSR *CSR `json:"csr"`
EnableMultiStackedCertificates bool `json:"enableMultiStackedCertificates"`
NetworkConfiguration *NetworkConfiguration `json:"networkConfiguration"`
Org *Org `json:"org"`
OrgID *int `json:"orgId,omitempty"`
RA string `json:"ra"`
SignatureAlgorithm string `json:"signatureAlgorithm,omitempty"`
TechContact *Contact `json:"techContact"`
ThirdParty *ThirdParty `json:"thirdParty,omitempty"`
ValidationType string `json:"validationType"`
}
// CreateEnrollmentResponse contains response body returned after successful enrollment creation
CreateEnrollmentResponse struct {
ID int
Enrollment string `json:"enrollment"`
Changes []string `json:"changes"`
}
// UpdateEnrollmentRequest contains request body and path parameters used to update an enrollment
UpdateEnrollmentRequest struct {
EnrollmentRequestBody
EnrollmentID int
AllowCancelPendingChanges *bool
AllowStagingBypass *bool
DeployNotAfter string
DeployNotBefore string
ForceRenewal *bool
RenewalDateCheckOverride *bool
}
// UpdateEnrollmentResponse contains response body returned after successful enrollment update
UpdateEnrollmentResponse struct {
ID int
Enrollment string `json:"enrollment"`
Changes []string `json:"changes"`
}
// RemoveEnrollmentRequest contains parameters necessary to send a RemoveEnrollment request
RemoveEnrollmentRequest struct {
EnrollmentID int
AllowCancelPendingChanges *bool
DeployNotAfter string
DeployNotBefore string
}
// RemoveEnrollmentResponse contains response body returned after successful enrollment deletion
RemoveEnrollmentResponse struct {
Enrollment string `json:"enrollment"`
Changes []string `json:"changes"`
}
// OCSPStapling is used to enable OCSP stapling for an enrollment
OCSPStapling string
)
const (
// OCSPStaplingOn parameter value
OCSPStaplingOn OCSPStapling = "on"
// OCSPStaplingOff parameter value
OCSPStaplingOff OCSPStapling = "off"
// OCSPStaplingNotSet parameter value
OCSPStaplingNotSet OCSPStapling = "not-set"
)
// Validate performs validation on EnrollmentRequestBody
func (e EnrollmentRequestBody) Validate() error {
errs := validation.Errors{
"adminContact": validation.Validate(e.AdminContact, validation.Required),
"certificateType": validation.Validate(e.CertificateType, validation.Required),
"csr": validation.Validate(e.CSR, validation.Required),
"networkConfiguration": validation.Validate(e.NetworkConfiguration, validation.Required),
"org": validation.Validate(e.Org, validation.Required),
"ra": validation.Validate(e.RA, validation.Required),
"techContact": validation.Validate(e.TechContact, validation.Required),
"validationType": validation.Validate(e.ValidationType, validation.Required),
"thirdParty": validation.Validate(e.ThirdParty),
}
if e.CSR != nil {
errs["csr.preferredTrustChain"] = validation.Validate(e.CSR.PreferredTrustChain,
validation.When(e.ValidationType != "dv", validation.Empty.Error("must be blank when 'validationType' is not 'dv'")))
}
return errs.Filter()
}
// Validate performs validation on CSR
func (c CSR) Validate() error {
return validation.Errors{
"cn": validation.Validate(c.CN, validation.Required),
}.Filter()
}
// Validate performs validation on NetworkConfiguration
func (n NetworkConfiguration) Validate() error {
return validation.Errors{
"ocspStapling": validation.Validate(n.OCSPStapling, validation.In(OCSPStaplingOn, OCSPStaplingOff, OCSPStaplingNotSet)),
}.Filter()
}
// Validate performs validation on ListEnrollmentsRequest
func (e ListEnrollmentsRequest) Validate() error {
return validation.Errors{
"contractId": validation.Validate(e.ContractID, validation.Required),
}.Filter()
}
// Validate performs validation on GetEnrollmentRequest
func (e GetEnrollmentRequest) Validate() error {
return validation.Errors{
"enrollmentId": validation.Validate(e.EnrollmentID, validation.Required),
}.Filter()
}
// Validate performs validation on CreateEnrollmentRequest
func (e CreateEnrollmentRequest) Validate() error {
return validation.Errors{
"enrollment": validation.Validate(e.EnrollmentRequestBody, validation.Required),
"contractId": validation.Validate(e.ContractID, validation.Required),
}.Filter()
}
// Validate performs validation on UpdateEnrollmentRequest
func (e UpdateEnrollmentRequest) Validate() error {
return validation.Errors{
"enrollment": validation.Validate(e.EnrollmentRequestBody, validation.Required),
"enrollmentId": validation.Validate(e.EnrollmentID, validation.Required),
}.Filter()
}
// Validate performs validation on RemoveEnrollmentRequest
func (e RemoveEnrollmentRequest) Validate() error {
return validation.Errors{
"enrollmentId": validation.Validate(e.EnrollmentID, validation.Required),
}.Filter()
}
var (
// ErrListEnrollments is returned when ListEnrollments fails
ErrListEnrollments = errors.New("fetching enrollments")
// ErrGetEnrollment is returned when GetEnrollment fails
ErrGetEnrollment = errors.New("fetching enrollment")
// ErrCreateEnrollment is returned when CreateEnrollment fails
ErrCreateEnrollment = errors.New("create enrollment")
// ErrUpdateEnrollment is returned when UpdateEnrollment fails
ErrUpdateEnrollment = errors.New("update enrollment")
// ErrRemoveEnrollment is returned when RemoveEnrollment fails
ErrRemoveEnrollment = errors.New("remove enrollment")
)
func (c *cps) ListEnrollments(ctx context.Context, params ListEnrollmentsRequest) (*ListEnrollmentsResponse, error) {
if err := params.Validate(); err != nil {
return nil, fmt.Errorf("%s: %w: %s", ErrListEnrollments, ErrStructValidation, err)
}
logger := c.Log(ctx)
logger.Debug("ListEnrollments")
uri := fmt.Sprintf("/cps/v2/enrollments?contractId=%s", params.ContractID)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return nil, fmt.Errorf("%w: failed to create request: %s", ErrListEnrollments, err)
}
req.Header.Set("Accept", "application/vnd.akamai.cps.enrollments.v11+json")
var result ListEnrollmentsResponse
resp, err := c.Exec(req, &result)
if err != nil {
return nil, fmt.Errorf("%w: request failed: %s", ErrListEnrollments, err)
}
defer session.CloseResponseBody(resp)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %w", ErrListEnrollments, c.Error(resp))
}
return &result, nil
}
func (c *cps) GetEnrollment(ctx context.Context, params GetEnrollmentRequest) (*GetEnrollmentResponse, error) {
if err := params.Validate(); err != nil {
return nil, fmt.Errorf("%s: %w: %s", ErrGetEnrollment, ErrStructValidation, err)
}
logger := c.Log(ctx)
logger.Debug("GetEnrollment")
uri := fmt.Sprintf("/cps/v2/enrollments/%d", params.EnrollmentID)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return nil, fmt.Errorf("%w: failed to create request: %s", ErrGetEnrollment, err)
}
req.Header.Set("Accept", "application/vnd.akamai.cps.enrollment.v11+json")
var result GetEnrollmentResponse
resp, err := c.Exec(req, &result)
if err != nil {
return nil, fmt.Errorf("%w: request failed: %s", ErrGetEnrollment, err)
}
defer session.CloseResponseBody(resp)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %w", ErrGetEnrollment, c.Error(resp))
}
return &result, nil
}
func (c *cps) CreateEnrollment(ctx context.Context, params CreateEnrollmentRequest) (*CreateEnrollmentResponse, error) {
if err := params.Validate(); err != nil {
return nil, fmt.Errorf("%s: %w: %s", ErrCreateEnrollment, ErrStructValidation, err)
}
logger := c.Log(ctx)
logger.Debug("CreateEnrollment")
uri, err := url.Parse(fmt.Sprintf("/cps/v2/enrollments?contractId=%s", params.ContractID))
if err != nil {
return nil, fmt.Errorf("%w: parsing URL: %s", ErrCreateEnrollment, err)
}
query := uri.Query()
if params.DeployNotAfter != "" {
query.Add("deploy-not-after", params.DeployNotAfter)
}
if params.DeployNotBefore != "" {
query.Add("deploy-not-before", params.DeployNotBefore)
}
if params.AllowDuplicateCN {
query.Add("allow-duplicate-cn", "true")
}
uri.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, uri.String(), nil)
if err != nil {
return nil, fmt.Errorf("%w: failed to create request: %s", ErrCreateEnrollment, err)
}
req.Header.Set("Accept", "application/vnd.akamai.cps.enrollment-status.v1+json")
req.Header.Set("Content-Type", "application/vnd.akamai.cps.enrollment.v11+json; charset=utf-8")
var result CreateEnrollmentResponse
resp, err := c.Exec(req, &result, params.EnrollmentRequestBody)
if err != nil {
return nil, fmt.Errorf("%w: request failed: %s", ErrCreateEnrollment, err)
}
defer session.CloseResponseBody(resp)
if resp.StatusCode != http.StatusAccepted {
return nil, fmt.Errorf("%s: %w", ErrCreateEnrollment, c.Error(resp))
}
id, err := GetIDFromLocation(result.Enrollment)
if err != nil {
return nil, fmt.Errorf("%s: %w: %s", ErrCreateEnrollment, ErrInvalidLocation, err)
}
result.ID = id
return &result, nil
}
func (c *cps) UpdateEnrollment(ctx context.Context, params UpdateEnrollmentRequest) (*UpdateEnrollmentResponse, error) {
if err := params.Validate(); err != nil {
return nil, fmt.Errorf("%s: %w: %s", ErrCreateEnrollment, ErrStructValidation, err)
}
logger := c.Log(ctx)
logger.Debug("UpdateEnrollment")
uri, err := url.Parse(fmt.Sprintf("/cps/v2/enrollments/%d", params.EnrollmentID))
if err != nil {
return nil, fmt.Errorf("%w: parsing URL: %s", ErrUpdateEnrollment, err)
}
query := uri.Query()
if params.AllowCancelPendingChanges != nil {
query.Add("allow-cancel-pending-changes", strconv.FormatBool(*params.AllowCancelPendingChanges))
}
if params.AllowStagingBypass != nil {
query.Add("allow-staging-bypass", strconv.FormatBool(*params.AllowStagingBypass))
}
if params.DeployNotAfter != "" {
query.Add("deploy-not-after", params.DeployNotAfter)
}
if params.DeployNotBefore != "" {
query.Add("deploy-not-before", params.DeployNotBefore)
}
if params.ForceRenewal != nil {
query.Add("force-renewal", strconv.FormatBool(*params.ForceRenewal))
}
if params.RenewalDateCheckOverride != nil {
query.Add("renewal-date-check-override", strconv.FormatBool(*params.RenewalDateCheckOverride))
}
uri.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodPut, uri.String(), nil)
if err != nil {
return nil, fmt.Errorf("%w: failed to create request: %s", ErrUpdateEnrollment, err)
}
req.Header.Set("Accept", "application/vnd.akamai.cps.enrollment-status.v1+json")
req.Header.Set("Content-Type", "application/vnd.akamai.cps.enrollment.v11+json; charset=utf-8")
var result UpdateEnrollmentResponse
resp, err := c.Exec(req, &result, params.EnrollmentRequestBody)
if err != nil {
return nil, fmt.Errorf("%w: request failed: %s", ErrUpdateEnrollment, err)
}
defer session.CloseResponseBody(resp)
if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %w", ErrUpdateEnrollment, c.Error(resp))
}
id, err := GetIDFromLocation(result.Enrollment)
if err != nil {
return nil, fmt.Errorf("%s: %w: %s", ErrCreateEnrollment, ErrInvalidLocation, err)
}
result.ID = id
return &result, nil
}
func (c *cps) RemoveEnrollment(ctx context.Context, params RemoveEnrollmentRequest) (*RemoveEnrollmentResponse, error) {
if err := params.Validate(); err != nil {
return nil, fmt.Errorf("%s: %w: %s", ErrRemoveEnrollment, ErrStructValidation, err)
}
logger := c.Log(ctx)
logger.Debug("RemoveEnrollment")
uri, err := url.Parse(fmt.Sprintf("/cps/v2/enrollments/%d", params.EnrollmentID))
if err != nil {
return nil, fmt.Errorf("%w: parsing URL: %s", ErrRemoveEnrollment, err)
}
query := uri.Query()
if params.AllowCancelPendingChanges != nil {
query.Add("allow-cancel-pending-changes", strconv.FormatBool(*params.AllowCancelPendingChanges))
}
if params.DeployNotAfter != "" {
query.Add("deploy-not-after", params.DeployNotAfter)
}
if params.DeployNotBefore != "" {
query.Add("deploy-not-before", params.DeployNotBefore)
}
uri.RawQuery = query.Encode()
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, uri.String(), nil)
if err != nil {
return nil, fmt.Errorf("%w: failed to create request: %s", ErrRemoveEnrollment, err)
}
req.Header.Set("Accept", "application/vnd.akamai.cps.enrollment-status.v1+json")
var result RemoveEnrollmentResponse
resp, err := c.Exec(req, &result)
if err != nil {
return nil, fmt.Errorf("%w: request failed: %s", ErrRemoveEnrollment, err)
}
defer session.CloseResponseBody(resp)
if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%s: %w", ErrRemoveEnrollment, c.Error(resp))
}
return &result, nil
}