forked from GoogleCloudPlatform/magic-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprivateca_ca_utils.go
283 lines (248 loc) · 9.58 KB
/
privateca_ca_utils.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
package privateca
import (
"fmt"
"log"
"math/rand"
"regexp"
"time"
"github.com/hashicorp/terraform-provider-google/google/tpgresource"
transport_tpg "github.com/hashicorp/terraform-provider-google/google/transport"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
// CA related utilities.
func enableCA(config *transport_tpg.Config, d *schema.ResourceData, project string, billingProject string, userAgent string) error {
enableUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:enable")
if err != nil {
return err
}
log.Printf("[DEBUG] Enabling CertificateAuthority")
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: enableUrl,
UserAgent: userAgent,
})
if err != nil {
return fmt.Errorf("Error enabling CertificateAuthority: %s", err)
}
var opRes map[string]interface{}
err = PrivatecaOperationWaitTimeWithResponse(
config, res, &opRes, project, "Enabling CertificateAuthority", userAgent,
d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf("Error waiting to enable CertificateAuthority: %s", err)
}
return nil
}
func disableCA(config *transport_tpg.Config, d *schema.ResourceData, project string, billingProject string, userAgent string) error {
disableUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:disable")
if err != nil {
return err
}
log.Printf("[DEBUG] Disabling CA")
dRes, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: disableUrl,
UserAgent: userAgent,
})
if err != nil {
return fmt.Errorf("Error disabling CA: %s", err)
}
var opRes map[string]interface{}
err = PrivatecaOperationWaitTimeWithResponse(
config, dRes, &opRes, project, "Disabling CA", userAgent,
d.Timeout(schema.TimeoutDelete))
if err != nil {
return fmt.Errorf("Error waiting to disable CA: %s", err)
}
return nil
}
func activateSubCAWithThirdPartyIssuer(config *transport_tpg.Config, d *schema.ResourceData, project string, billingProject string, userAgent string) error {
// 1. prepare parameters
signedCACert := d.Get("pem_ca_certificate").(string)
sc, ok := d.GetOk("subordinate_config")
if !ok {
return fmt.Errorf("subordinate_config is required to activate subordinate CA")
}
c := sc.([]interface{})
if len(c) == 0 || c[0] == nil {
return fmt.Errorf("subordinate_config is required to activate subordinate CA")
}
chain, ok := c[0].(map[string]interface{})["pem_issuer_chain"]
if !ok {
return fmt.Errorf("subordinate_config.pem_issuer_chain is required to activate subordinate CA with third party issuer")
}
issuerChain := chain.([]interface{})
if len(issuerChain) == 0 || issuerChain[0] == nil {
return fmt.Errorf("subordinate_config.pem_issuer_chain is required to activate subordinate CA with third party issuer")
}
pc := issuerChain[0].(map[string]interface{})["pem_certificates"].([]interface{})
pemIssuerChain := make([]string, 0, len(pc))
for _, pem := range pc {
pemIssuerChain = append(pemIssuerChain, pem.(string))
}
// 2. activate CA
activateObj := make(map[string]interface{})
activateObj["pemCaCertificate"] = signedCACert
activateObj["subordinateConfig"] = make(map[string]interface{})
activateObj["subordinateConfig"].(map[string]interface{})["pemIssuerChain"] = make(map[string]interface{})
activateObj["subordinateConfig"].(map[string]interface{})["pemIssuerChain"].(map[string]interface{})["pemCertificates"] = pemIssuerChain
activateUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:activate")
if err != nil {
return err
}
log.Printf("[DEBUG] Activating CertificateAuthority: %#v", activateObj)
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: activateUrl,
UserAgent: userAgent,
Body: activateObj,
})
if err != nil {
return fmt.Errorf("Error enabling CertificateAuthority: %s", err)
}
var opRes map[string]interface{}
err = PrivatecaOperationWaitTimeWithResponse(
config, res, &opRes, project, "Activating CertificateAuthority", userAgent,
d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf("Error waiting to actiavte CertificateAuthority: %s", err)
}
return nil
}
func activateSubCAWithFirstPartyIssuer(config *transport_tpg.Config, d *schema.ResourceData, project string, billingProject string, userAgent string) error {
// 1. get issuer
sc, ok := d.GetOk("subordinate_config")
if !ok {
return fmt.Errorf("subordinate_config is required to activate subordinate CA")
}
c := sc.([]interface{})
if len(c) == 0 || c[0] == nil {
return fmt.Errorf("subordinate_config is required to activate subordinate CA")
}
ca, ok := c[0].(map[string]interface{})["certificate_authority"]
if !ok {
return fmt.Errorf("subordinate_config.certificate_authority is required to activate subordinate CA with first party issuer")
}
issuer := ca.(string)
// 2. fetch CSR
fetchCSRUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:fetch")
if err != nil {
return err
}
res, err := transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "GET",
Project: billingProject,
RawURL: fetchCSRUrl,
UserAgent: userAgent,
})
if err != nil {
return fmt.Errorf("failed to fetch CSR: %v", err)
}
csr := res["pemCsr"]
// 3. sign the CSR with first party issuer
genCertId := func() string {
currentTime := time.Now()
dateStr := currentTime.Format("20060102")
rand.Seed(time.Now().UnixNano())
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
rand1 := make([]byte, 3)
for i := range rand1 {
rand1[i] = letters[rand.Intn(len(letters))]
}
rand2 := make([]byte, 3)
for i := range rand2 {
rand2[i] = letters[rand.Intn(len(letters))]
}
return fmt.Sprintf("subordinate-%v-%v-%v", dateStr, string(rand1), string(rand2))
}
// parseCAName parses a CA name and return the CaPool name and CaId.
parseCAName := func(n string) (string, string, error) {
parts := regexp.MustCompile(`(projects/[a-z0-9-]+/locations/[a-z0-9-]+/caPools/[a-zA-Z0-9-]+)/certificateAuthorities/([a-zA-Z0-9-]+)`).FindStringSubmatch(n)
if len(parts) != 3 {
return "", "", fmt.Errorf("failed to parse CA name: %v, parts: %v", n, parts)
}
return parts[1], parts[2], err
}
obj := make(map[string]interface{})
obj["pemCsr"] = csr
obj["lifetime"] = d.Get("lifetime")
certId := genCertId()
poolName, issuerId, err := parseCAName(issuer)
if err != nil {
return err
}
PrivatecaBasePath, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}")
if err != nil {
return err
}
signUrl := fmt.Sprintf("%v%v/certificates?certificateId=%v", PrivatecaBasePath, poolName, certId)
signUrl, err = transport_tpg.AddQueryParams(signUrl, map[string]string{"issuingCertificateAuthorityId": issuerId})
if err != nil {
return err
}
log.Printf("[DEBUG] Signing CA Certificate: %#v", obj)
res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: signUrl,
UserAgent: userAgent,
Body: obj,
Timeout: d.Timeout(schema.TimeoutCreate),
})
if err != nil {
return fmt.Errorf("Error creating Certificate: %s", err)
}
signedCACert := res["pemCertificate"]
signerCertChain := res["pemCertificateChain"]
// 4. activate sub CA with the signed CA cert.
activateObj := make(map[string]interface{})
activateObj["pemCaCertificate"] = signedCACert
activateObj["subordinateConfig"] = make(map[string]interface{})
activateObj["subordinateConfig"].(map[string]interface{})["pemIssuerChain"] = make(map[string]interface{})
activateObj["subordinateConfig"].(map[string]interface{})["pemIssuerChain"].(map[string]interface{})["pemCertificates"] = signerCertChain
activateUrl, err := tpgresource.ReplaceVars(d, config, "{{PrivatecaBasePath}}projects/{{project}}/locations/{{location}}/caPools/{{pool}}/certificateAuthorities/{{certificate_authority_id}}:activate")
if err != nil {
return err
}
log.Printf("[DEBUG] Activating CertificateAuthority: %#v", activateObj)
res, err = transport_tpg.SendRequest(transport_tpg.SendRequestOptions{
Config: config,
Method: "POST",
Project: billingProject,
RawURL: activateUrl,
UserAgent: userAgent,
Body: activateObj,
})
if err != nil {
return fmt.Errorf("Error enabling CertificateAuthority: %s", err)
}
var opRes map[string]interface{}
err = PrivatecaOperationWaitTimeWithResponse(
config, res, &opRes, project, "Enabling CertificateAuthority", userAgent,
d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf("Error waiting to actiavte CertificateAuthority: %s", err)
}
return nil
}
// These setters are used for tests
func (u *PrivatecaCaPoolIamUpdater) SetProject(project string) {
u.project = project
}
func (u *PrivatecaCaPoolIamUpdater) SetLocation(location string) {
u.location = location
}
func (u *PrivatecaCaPoolIamUpdater) SetCaPool(caPool string) {
u.caPool = caPool
}
func (u *PrivatecaCaPoolIamUpdater) SetResourceData(d tpgresource.TerraformResourceData) {
u.d = d
}