/
resource_webhook.go
474 lines (423 loc) · 15.6 KB
/
resource_webhook.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
package cloudsmith
import (
"context"
"fmt"
"strings"
"time"
"github.com/cloudsmith-io/cloudsmith-api-go"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/samber/lo"
)
var (
eventTypes = []string{
"*",
"package.created",
"package.deleted",
"package.downloaded",
"package.failed",
"package.security_scanned",
"package.synced",
"package.syncing",
"package.tags_updated",
}
requestBodyFormatMap = map[int]string{
0: "JSON Object",
1: "JSON Array",
2: "Form Encoded JSON Object",
3: "Handlebars Template",
}
requestBodyTemplateFormatMap = map[int]string{
0: "Generic (user-defined)",
1: "JSON (application/json)",
2: "XML (application/xml)",
}
)
// expandEvents extracts "events" from TF state as a *schema.Set and converts to
// a slice of strings we can use when interacting with the Cloudsmith API.
func expandEvents(d *schema.ResourceData) []string {
set := d.Get("events").(*schema.Set)
return lo.Map(set.List(), func(item interface{}, _ int) string {
return item.(string)
})
}
// flattenEvents takes a slice of strings as returned by the Cloudsmith API and
// converts to a *schema.Set that can be stored in TF state.
func flattenEvents(events []string) *schema.Set {
set := schema.NewSet(schema.HashString, []interface{}{})
for _, event := range events {
set.Add(event)
}
return set
}
// expandRequestBodyFormat extracts the request body format from TF state as a
// human-readable string (if set) and converts it to an int64 that can be used
// to interact with the Cloudsmith API.
func expandRequestBodyFormat(d *schema.ResourceData) *int64 {
value := optionalString(d, "request_body_format")
if value == nil {
return nil
}
m := lo.Invert(requestBodyFormatMap)
v, ok := m[*value]
if !ok {
return nil
}
return cloudsmith.PtrInt64(int64(v))
}
// flattenRequestBodyFormat takes an int64 as returned by the Cloudsmith API and
// converts it to a human readable string that can be stored/used in TF state.
func flattenRequestBodyFormat(fmt int64) string {
return requestBodyFormatMap[int(fmt)]
}
// expandRequestBodyTemplateFormat extracts the request body template format
// from TF state as a human-readable string (if set) and converts it to an int64
// that can be used to interact with the Cloudsmith API.
func expandRequestBodyTemplateFormat(d *schema.ResourceData) *int64 {
value := optionalString(d, "request_body_template_format")
if value == nil {
return nil
}
m := lo.Invert(requestBodyTemplateFormatMap)
v, ok := m[*value]
if !ok {
return nil
}
return cloudsmith.PtrInt64(int64(v))
}
// flattenRequestBodyTemplateFormat takes an int64 as returned by the Cloudsmith API and
// converts it to a human readable string that can be stored/used in TF state.
func flattenRequestBodyTemplateFormat(fmt int64) string {
return requestBodyTemplateFormatMap[int(fmt)]
}
// expandEvents extracts "events" from TF state as a *schema.Set and converts to
// a slice of strings we can use when interacting with the Cloudsmith API.
func expandTemplates(d *schema.ResourceData) []cloudsmith.WebhookTemplate {
set := d.Get("template").(*schema.Set)
return lo.Map(set.List(), func(x interface{}, index int) cloudsmith.WebhookTemplate {
m := x.(map[string]interface{})
t := cloudsmith.WebhookTemplate{}
t.SetEvent(m["event"].(string))
t.SetTemplate(m["template"].(string))
return t
})
}
// flattenTemplates takes a slice of cloudsmith.WebhookTemplate as returned by
// the Cloudsmith API and converts to a *schema.Set that can be stored in TF
// state.
func flattenTemplates(templates []cloudsmith.WebhookTemplate) *schema.Set {
templateSchema := resourceWebhook().Schema["template"].Elem.(*schema.Resource)
set := schema.NewSet(schema.HashResource(templateSchema), []interface{}{})
for _, template := range templates {
set.Add(map[string]interface{}{
"event": template.GetEvent(),
"template": template.GetTemplate(),
})
}
return set
}
func importWebhook(ctx context.Context, d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
idParts := strings.Split(d.Id(), ".")
if len(idParts) != 3 {
return nil, fmt.Errorf(
"invalid import ID, must be of the form <organization_slug>.<repository_slug>.<webhook_slug>, got: %s", d.Id(),
)
}
d.Set("namespace", idParts[0])
d.Set("repository", idParts[1])
d.SetId(idParts[2])
return []*schema.ResourceData{d}, nil
}
func resourceWebhookCreate(d *schema.ResourceData, m interface{}) error {
pc := m.(*providerConfig)
namespace := requiredString(d, "namespace")
repository := requiredString(d, "repository")
req := pc.APIClient.WebhooksApi.WebhooksCreate(pc.Auth, namespace, repository)
req = req.Data(cloudsmith.RepositoryWebhookRequest{
Events: expandEvents(d),
IsActive: optionalBool(d, "is_active"),
PackageQuery: nullableString(d, "package_query"),
RequestBodyFormat: expandRequestBodyFormat(d),
RequestBodyTemplateFormat: expandRequestBodyTemplateFormat(d),
RequestContentType: nullableString(d, "request_content_type"),
SecretHeader: nullableString(d, "secret_header"),
SecretValue: nullableString(d, "secret_value"),
SignatureKey: optionalString(d, "signature_key"),
TargetUrl: requiredString(d, "target_url"),
Templates: expandTemplates(d),
VerifySsl: optionalBool(d, "verify_ssl"),
})
webhook, _, err := pc.APIClient.WebhooksApi.WebhooksCreateExecute(req)
if err != nil {
return err
}
d.SetId(webhook.GetSlugPerm())
checkerFunc := func() error {
req := pc.APIClient.WebhooksApi.WebhooksRead(pc.Auth, namespace, repository, d.Id())
if _, resp, err := pc.APIClient.WebhooksApi.WebhooksReadExecute(req); err != nil {
if is404(resp) {
return errKeepWaiting
}
return err
}
return nil
}
if err := waiter(checkerFunc, defaultCreationTimeout, defaultCreationInterval); err != nil {
return fmt.Errorf("error waiting for webhook (%s) to be created: %w", d.Id(), err)
}
return resourceWebhookRead(d, m)
}
func resourceWebhookRead(d *schema.ResourceData, m interface{}) error {
pc := m.(*providerConfig)
namespace := requiredString(d, "namespace")
repository := requiredString(d, "repository")
req := pc.APIClient.WebhooksApi.WebhooksRead(pc.Auth, namespace, repository, d.Id())
webhook, resp, err := pc.APIClient.WebhooksApi.WebhooksReadExecute(req)
if err != nil {
if is404(resp) {
d.SetId("")
return nil
}
return err
}
d.Set("created_at", timeToString(webhook.GetCreatedAt()))
d.Set("created_by", webhook.GetCreatedBy())
d.Set("disable_reason", webhook.GetDisableReasonStr())
d.Set("events", flattenEvents(webhook.GetEvents()))
d.Set("is_active", webhook.GetIsActive())
d.Set("package_query", webhook.GetPackageQuery())
d.Set("request_body_format", flattenRequestBodyFormat(webhook.GetRequestBodyFormat()))
d.Set("request_body_template_format", flattenRequestBodyTemplateFormat(webhook.GetRequestBodyTemplateFormat()))
d.Set("request_content_type", webhook.GetRequestContentType())
d.Set("secret_header", webhook.GetSecretHeader())
d.Set("slug_perm", webhook.GetSlugPerm())
d.Set("target_url", webhook.GetTargetUrl())
d.Set("template", flattenTemplates(webhook.GetTemplates()))
d.Set("updated_at", timeToString(webhook.GetUpdatedAt()))
d.Set("updated_by", webhook.GetUpdatedBy())
d.Set("verify_ssl", webhook.GetVerifySsl())
// namespace and repository are not returned from the entitlement read
// endpoint, so we can use the values stored in resource state. We rely on
// ForceNew to ensure if either changes a new resource is created.
d.Set("namespace", namespace)
d.Set("repository", repository)
return nil
}
func resourceWebhookUpdate(d *schema.ResourceData, m interface{}) error {
pc := m.(*providerConfig)
namespace := requiredString(d, "namespace")
repository := requiredString(d, "repository")
req := pc.APIClient.WebhooksApi.WebhooksPartialUpdate(pc.Auth, namespace, repository, d.Id())
req = req.Data(cloudsmith.RepositoryWebhookRequestPatch{
Events: expandEvents(d),
IsActive: optionalBool(d, "is_active"),
PackageQuery: nullableString(d, "package_query"),
RequestBodyFormat: expandRequestBodyFormat(d),
RequestBodyTemplateFormat: expandRequestBodyTemplateFormat(d),
RequestContentType: nullableString(d, "request_content_type"),
SecretHeader: nullableString(d, "secret_header"),
SecretValue: nullableString(d, "secret_value"),
SignatureKey: optionalString(d, "signature_key"),
TargetUrl: optionalString(d, "target_url"),
Templates: expandTemplates(d),
VerifySsl: optionalBool(d, "verify_ssl"),
})
webhook, _, err := pc.APIClient.WebhooksApi.WebhooksPartialUpdateExecute(req)
if err != nil {
return err
}
d.SetId(webhook.GetSlugPerm())
checkerFunc := func() error {
// this is somewhat of a hack until we have a better way to poll for an
// entitlement being updated (changes incoming on the API side)
time.Sleep(time.Second * 5)
return nil
}
if err := waiter(checkerFunc, defaultUpdateTimeout, defaultUpdateInterval); err != nil {
return fmt.Errorf("error waiting for webhook (%s) to be updated: %w", d.Id(), err)
}
return resourceWebhookRead(d, m)
}
func resourceWebhookDelete(d *schema.ResourceData, m interface{}) error {
pc := m.(*providerConfig)
namespace := requiredString(d, "namespace")
repository := requiredString(d, "repository")
req := pc.APIClient.WebhooksApi.WebhooksDelete(pc.Auth, namespace, repository, d.Id())
_, err := pc.APIClient.WebhooksApi.WebhooksDeleteExecute(req)
if err != nil {
return err
}
checkerFunc := func() error {
req := pc.APIClient.WebhooksApi.WebhooksRead(pc.Auth, namespace, repository, d.Id())
if _, resp, err := pc.APIClient.WebhooksApi.WebhooksReadExecute(req); err != nil {
if is404(resp) {
return nil
}
return err
}
return errKeepWaiting
}
if err := waiter(checkerFunc, defaultDeletionTimeout, defaultDeletionInterval); err != nil {
return fmt.Errorf("error waiting for webhook (%s) to be deleted: %w", d.Id(), err)
}
return nil
}
//nolint:funlen
func resourceWebhook() *schema.Resource {
return &schema.Resource{
Create: resourceWebhookCreate,
Read: resourceWebhookRead,
Update: resourceWebhookUpdate,
Delete: resourceWebhookDelete,
Importer: &schema.ResourceImporter{
StateContext: importWebhook,
},
Schema: map[string]*schema.Schema{
"created_at": {
Type: schema.TypeString,
Description: "ISO 8601 timestamp at which the webhook was created.",
Computed: true,
},
"created_by": {
Type: schema.TypeString,
Description: "The user/account that created the webhook.",
Computed: true,
},
"disable_reason": {
Type: schema.TypeString,
Description: "Why this webhook has been disabled.",
Computed: true,
},
"events": {
Type: schema.TypeSet,
Description: "List of events for which this webhook will be fired.",
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validation.StringInSlice(eventTypes, false),
},
MinItems: 1,
Required: true,
},
"is_active": {
Type: schema.TypeBool,
Description: "If enabled, the webhook will trigger on subscribed events and send payloads to the configured target URL.",
Optional: true,
Computed: true,
},
"namespace": {
Type: schema.TypeString,
Description: "Namespace to which this webhook belongs.",
Required: true,
ForceNew: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"package_query": {
Type: schema.TypeString,
Description: "The package-based search query for webhooks to fire. This uses the same " +
"syntax as the standard search used for repositories, and also supports boolean " +
"logic operators such as OR/AND/NOT and parentheses for grouping. If a package does " +
"not match, the webhook will not fire.",
Optional: true,
},
"repository": {
Type: schema.TypeString,
Description: "Repository to which this webhook belongs.",
Required: true,
ForceNew: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"request_body_format": {
Type: schema.TypeString,
Description: "The format of the payloads for webhook requests.",
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice(lo.Values(requestBodyFormatMap), false),
},
"request_body_template_format": {
Type: schema.TypeString,
Description: "The format of the payloads for webhook requests.",
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice(lo.Values(requestBodyTemplateFormatMap), false),
},
"request_content_type": {
Type: schema.TypeString,
Description: "The value that will be sent for the 'Content Type' header.",
Optional: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"secret_header": {
Type: schema.TypeString,
Description: "The header to send the predefined secret in. This must be unique from existing " +
"headers or it won't be sent. You can use this as a form of authentication on the endpoint side.",
Optional: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"secret_value": {
Type: schema.TypeString,
Description: "The value for the predefined secret (note: this is treated as a passphrase and is " +
"encrypted when we store it). You can use this as a form of authentication on the endpoint side.",
Optional: true,
Sensitive: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"signature_key": {
Type: schema.TypeString,
Description: "The value for the signature key - This is used to generate an HMAC-based hex digest of " +
"the request body, which we send as the X-Cloudsmith-Signature header so that you can ensure that " +
"the request wasn't modified by a malicious party (note: this is treated as a passphrase and is " +
"encrypted when we store it).",
Optional: true,
Sensitive: true,
ValidateFunc: validation.StringIsNotEmpty,
},
"slug_perm": {
Type: schema.TypeString,
Description: "The slug_perm immutably identifies the webhook. " +
"It will never change once a webhook has been created.",
Computed: true,
},
"target_url": {
Type: schema.TypeString,
Description: "The destination URL that webhook payloads will be POST'ed to.",
Required: true,
ValidateFunc: validation.IsURLWithHTTPorHTTPS,
},
"template": {
Type: schema.TypeSet,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"event": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice(eventTypes, false),
},
"template": {
Type: schema.TypeString,
Optional: true,
},
},
},
Optional: true,
},
"updated_at": {
Type: schema.TypeString,
Description: "ISO 8601 timestamp at which the webhook was updated.",
Computed: true,
},
"updated_by": {
Type: schema.TypeString,
Description: "The user/account that updated the webhook.",
Computed: true,
},
"verify_ssl": {
Type: schema.TypeBool,
Description: "If enabled, SSL certificates is verified when webhooks are sent. It's recommended to " +
"leave this enabled as not verifying the integrity of SSL certificates leaves you susceptible " +
"to Man-in-the-Middle (MITM) attacks.",
Optional: true,
Computed: true,
},
},
}
}