/
utilities.go
517 lines (456 loc) · 14.8 KB
/
utilities.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
// Copyright (c) 2022 IndyKite
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package indykite
import (
"encoding/base64"
"errors"
"fmt"
"reflect"
"regexp"
"strings"
"time"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
sdkerrors "github.com/indykite/indykite-sdk-go/errors"
configpb "github.com/indykite/indykite-sdk-go/gen/indykite/config/v1beta1"
"google.golang.org/protobuf/types/known/timestamppb"
"google.golang.org/protobuf/types/known/wrapperspb"
"gopkg.in/yaml.v3"
)
var (
nameCheck = regexp.MustCompile(`^[a-z]+[-a-z0-9]*[a-z0-9]+$`)
// TODO improve the regexp pattern.
emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") //nolint:lll
// pemRegex defines regex to match PEM Private key format.
pemRegex = regexp.MustCompile(`^-----BEGIN PRIVATE KEY-----(?:(?s).*)-----END PRIVATE KEY-----(?:\n)?$`)
)
var supportedSigningAlgs = []string{
"RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384",
"ES512", "ES256K", "HS256", "HS384", "HS512", "EdDSA",
}
// ValidateName is Terraform validation helper to verify value is valid name.
func ValidateName(i any, path cty.Path) diag.Diagnostics {
var ret diag.Diagnostics
v, ok := i.(string)
if !ok {
return append(ret, buildPluginErrorWithPath(
fmt.Sprintf("validateName failed, expected string, got %T", i),
path,
))
}
if l := len(v); l < 2 || l > 254 {
ret = append(ret, diag.Diagnostic{
Severity: diag.Error,
Summary: fmt.Sprintf("expected string value betweem 2 and 254 runes but received %d", l),
AttributePath: path,
})
}
if !nameCheck.MatchString(v) {
ret = append(ret, diag.Diagnostic{
Severity: diag.Error,
Summary: "Invalid name",
Detail: "Value can have lowercase letters, digits, or hyphens. It must start with a lowercase letter and end with a letter or number.",
AttributePath: path,
})
}
return ret
}
// ValidateEmail is Terraform validation helper to verify value is valid email.
func ValidateEmail(i any, path cty.Path) diag.Diagnostics {
var ret diag.Diagnostics
v, ok := i.(string)
if !ok {
return append(ret, buildPluginErrorWithPath(
fmt.Sprintf("validateEmail failed, expected string, got %T", i),
path,
))
}
if l := len(v); l < 2 || l > 254 {
ret = append(ret, diag.Diagnostic{
Severity: diag.Error,
Summary: fmt.Sprintf("expected string value betweem 2 and 254 runes but received %d", l),
AttributePath: path,
})
}
if !emailRegex.MatchString(v) {
ret = append(ret, diag.Diagnostic{
Severity: diag.Error,
Summary: "Value is not valid email address",
AttributePath: path,
})
}
return ret
}
// ValidateGID is Terraform validation helper to verify value is valid gid.
func ValidateGID(i any, path cty.Path) diag.Diagnostics {
v, ok := i.(string)
var errSummary string
switch {
case !ok:
errSummary = "expected type to be string"
case !strings.HasPrefix(v, "gid:"):
errSummary = "expected to have 'gid:' prefix"
case len(v) < 22, len(v) > 254:
errSummary = "expected to have len between 22 and 254 characters"
default:
if _, err := base64.RawURLEncoding.DecodeString(v[4:]); err != nil {
errSummary = "expected to be a valid Raw URL Base64 string with 'gid:' prefix, got " + err.Error()
}
}
if errSummary != "" {
return diag.Diagnostics{{
Severity: diag.Error,
Detail: errSummary,
Summary: "Invalid ID value",
AttributePath: path,
}}
}
return nil
}
// ValidateYaml is Terraform validation helper to verify value is valid YAML.
func ValidateYaml(i any, path cty.Path) diag.Diagnostics {
var ret diag.Diagnostics
v, ok := i.(string)
if !ok {
return append(ret, buildPluginErrorWithPath(
fmt.Sprintf("validateYaml failed, expected string, got %T", i),
path,
))
}
var y any
if err := yaml.Unmarshal([]byte(v), &y); err != nil {
return diag.Diagnostics{{
Severity: diag.Error,
Summary: err.Error(),
AttributePath: path,
}}
}
return nil
}
// DisplayNameDiffSuppress suppress Terraform changes when it contains name returned from API.
func DisplayNameDiffSuppress(k, old, newVal string, d *schema.ResourceData) bool {
if k == displayNameKey && old == d.Get(nameKey).(string) && newVal == "" {
return true
}
return false
}
// DisplayNameCredentialDiffSuppress suppress Terraform changes when it contains KID returned from API.
func DisplayNameCredentialDiffSuppress(k, old, newVal string, d *schema.ResourceData) bool {
if k == displayNameKey && old == d.Get(kidKey).(string) && newVal == "" {
return true
}
return false
}
// SuppressYamlDiff verify that 2 YAML strings are the same in value and suppress Terraform changes.
func SuppressYamlDiff(_, old, newVal string, _ *schema.ResourceData) bool {
var oldMap, newMap map[string]any
if err := yaml.Unmarshal([]byte(old), &oldMap); err != nil {
return false
}
if err := yaml.Unmarshal([]byte(newVal), &newMap); err != nil {
return false
}
return reflect.DeepEqual(oldMap, newMap)
}
// SuppressDurationDiff compares duration written as string and compare if value is the same or not.
// So values like 1h or 60m is the same.
func SuppressDurationDiff(_, oldValue, newValue string, _ *schema.ResourceData) bool {
if oldValue == newValue {
return true
}
var oldDur, newDur time.Duration
var err error
if oldDur, err = time.ParseDuration(oldValue); err != nil {
return false
}
if newDur, err = time.ParseDuration(newValue); err != nil {
return false
}
return oldDur == newDur
}
func optionalString(data *schema.ResourceData, key string) *wrapperspb.StringValue {
v, ok := data.Get(key).(string)
if !ok || v == "" {
return nil
}
return wrapperspb.String(v)
}
func stringOrEmpty(data *schema.ResourceData, key string) string {
v, _ := data.Get(key).(string)
return v
}
// flattenOptionalString returns String if v is not nil and v is not empty else returns nil.
func flattenOptionalString(v *wrapperspb.StringValue) any {
if v != nil && v.Value != "" {
return v.Value
}
return nil
}
func flattenOptionalMap(data map[string]string) map[string]string {
if len(data) == 0 {
return nil
}
return data
}
func flattenOptionalArray(data []string) []string {
if len(data) == 0 {
return nil
}
return data
}
func updateOptionalString(data *schema.ResourceData, key string) *wrapperspb.StringValue {
if !data.HasChange(key) {
return nil
}
v, ok := data.Get(key).(string)
if !ok {
return nil
}
return wrapperspb.String(v)
}
func setData(d *diag.Diagnostics, data *schema.ResourceData, attr string, value any) {
if valOf := reflect.ValueOf(value); value == nil || (valOf.Kind() == reflect.Ptr && valOf.IsNil()) {
if err := data.Set(attr, nil); err != nil {
*d = append(*d, diag.Diagnostic{
Severity: diag.Error,
Detail: err.Error(),
Summary: "Cannot add attribute",
AttributePath: cty.Path{cty.GetAttrStep{Name: attr}},
})
return
}
}
switch v := value.(type) {
case *wrapperspb.StringValue:
value = v.GetValue()
case *wrapperspb.Int32Value:
value = v.GetValue()
case *wrapperspb.Int64Value:
value = v.GetValue()
case *wrapperspb.UInt32Value:
value = v.GetValue()
case *wrapperspb.UInt64Value:
value = v.GetValue()
case *wrapperspb.BoolValue:
value = v.GetValue()
case *wrapperspb.BytesValue:
value = v.GetValue()
case *wrapperspb.FloatValue:
value = v.GetValue()
case *timestamppb.Timestamp:
if v == nil {
return
}
t := v.AsTime()
if t.IsZero() {
return
}
value = t.Format(time.RFC3339Nano)
}
if err := data.Set(attr, value); err != nil {
*d = append(*d, diag.Diagnostic{
Severity: diag.Error,
Detail: err.Error(),
Summary: "Cannot add attribute",
AttributePath: cty.Path{cty.GetAttrStep{Name: attr}},
})
}
}
// hasDeleteProtection returns true if resource is protected from deletion.
func hasDeleteProtection(d *diag.Diagnostics, data *schema.ResourceData) bool {
if v, ok := data.GetOk(deletionProtectionKey); ok && v.(bool) {
*d = append(*d, diag.Diagnostic{
Severity: diag.Error,
Summary: "Delete Protection is enabled",
Detail: "Cannot destroy instance without setting deletion_protection=false and running `terraform apply`",
})
return true
}
return false
}
// HasFailed checks if error is not nil and if it is, it will add it to diagnostics.
func HasFailed(d *diag.Diagnostics, err error) bool {
switch {
case err == nil:
return false
case sdkerrors.IsServiceError(err):
*d = append(*d, diag.Diagnostic{
Severity: diag.Error,
Summary: "Communication with IndyKite failed, please try again later",
Detail: err.Error(),
})
case sdkerrors.IsNotFoundError(err):
*d = append(*d, diag.Diagnostic{
Severity: diag.Warning,
Summary: "Resource not found",
Detail: err.Error(),
})
default:
*d = append(*d, buildPluginError(err.Error()))
}
return true
}
func readHasFailed(d *diag.Diagnostics, err error, data *schema.ResourceData) bool {
if HasFailed(d, err) {
if sdkerrors.IsNotFoundError(err) {
_ = schema.RemoveFromState(data, nil)
}
return true
}
return false
}
// rawArrayToStringArray casts raw data to []any and next to []string.
func rawArrayToStringArray(rawData any) []string {
strArr := make([]string, len(rawData.([]any)))
if len(strArr) == 0 {
return nil
}
for i, el := range rawData.([]any) {
strArr[i] = el.(string)
}
return strArr
}
// rawMapToStringMap casts raw data to map[string]any and next convert to map[string]string.
func rawMapToStringMap(rawData any) map[string]string {
out := make(map[string]string)
for i, el := range rawData.(map[string]any) {
out[i] = el.(string)
}
if len(out) == 0 {
return nil
}
return out
}
func stringToOptionalStringWrapper(in string) *wrapperspb.StringValue {
if in == "" {
return nil
}
return wrapperspb.String(in)
}
func buildPluginError(summary string) diag.Diagnostic {
return diag.Diagnostic{
Severity: diag.Error,
Summary: summary,
Detail: "This is IndyKite plugin error, please report this issue to us! Thank you",
}
}
func buildPluginErrorWithAttrName(summary, attr string) diag.Diagnostic {
d := buildPluginError(summary)
d.AttributePath = cty.Path{cty.GetAttrStep{Name: attr}}
return d
}
func buildPluginErrorWithPath(summary string, path cty.Path) diag.Diagnostic {
d := buildPluginError(summary)
d.AttributePath = path
return d
}
func getMapStringKeys[V any](in map[string]V) []string {
keys := make([]string, 0, len(in))
for k := range in {
keys = append(keys, k)
}
return keys
}
// ReverseProtoEnumMap create reverse map, where value is key and key is value of Proto Enum.
func ReverseProtoEnumMap[Key, Value comparable](in map[Key]Value) map[Value]Key {
reversed := make(map[Value]Key)
for k, v := range in {
reversed[v] = k
}
return reversed
}
// OAuth2GrantTypes defines all supported GrantTypes and its mapping.
var OAuth2GrantTypes = map[string]configpb.GrantType{
"authorization_code": configpb.GrantType_GRANT_TYPE_AUTHORIZATION_CODE,
"implicit": configpb.GrantType_GRANT_TYPE_IMPLICIT,
"password": configpb.GrantType_GRANT_TYPE_PASSWORD,
"client_credentials": configpb.GrantType_GRANT_TYPE_CLIENT_CREDENTIALS,
"refresh_token": configpb.GrantType_GRANT_TYPE_REFRESH_TOKEN,
}
// OAuth2ResponseTypes defines all supported ResponseTypes and its mapping.
var OAuth2ResponseTypes = map[string]configpb.ResponseType{
"token": configpb.ResponseType_RESPONSE_TYPE_TOKEN,
"code": configpb.ResponseType_RESPONSE_TYPE_CODE,
"id_token": configpb.ResponseType_RESPONSE_TYPE_ID_TOKEN,
}
// OAuth2TokenEndpointAuthMethods defines all supported Token Endpoint Auth Methods and its mapping.
var OAuth2TokenEndpointAuthMethods = map[string]configpb.TokenEndpointAuthMethod{
"client_secret_basic": configpb.TokenEndpointAuthMethod_TOKEN_ENDPOINT_AUTH_METHOD_CLIENT_SECRET_BASIC,
"client_secret_post": configpb.TokenEndpointAuthMethod_TOKEN_ENDPOINT_AUTH_METHOD_CLIENT_SECRET_POST,
"private_key_jwt": configpb.TokenEndpointAuthMethod_TOKEN_ENDPOINT_AUTH_METHOD_PRIVATE_KEY_JWT,
"none": configpb.TokenEndpointAuthMethod_TOKEN_ENDPOINT_AUTH_METHOD_NONE,
}
// OAuth2TokenEndpointAuthMethodsReverse defines all supported Token Endpoint Auth Methods and its reversed mapping.
var OAuth2TokenEndpointAuthMethodsReverse = ReverseProtoEnumMap(OAuth2TokenEndpointAuthMethods)
// OAuth2ClientSubjectTypes defines all supported Client Subjects and its mapping.
var OAuth2ClientSubjectTypes = map[string]configpb.ClientSubjectType{
"public": configpb.ClientSubjectType_CLIENT_SUBJECT_TYPE_PUBLIC,
"pairwise": configpb.ClientSubjectType_CLIENT_SUBJECT_TYPE_PAIRWISE,
}
// OAuth2ClientSubjectTypesReverse defines all supported Client Subjects and its reversed mapping.
var OAuth2ClientSubjectTypesReverse = ReverseProtoEnumMap(OAuth2ClientSubjectTypes)
// AuthorizationPolicyStatusTypes defines all supported StatusTypes and its mapping.
var AuthorizationPolicyStatusTypes = map[string]configpb.AuthorizationPolicyConfig_Status{
"active": configpb.AuthorizationPolicyConfig_STATUS_ACTIVE,
"inactive": configpb.AuthorizationPolicyConfig_STATUS_INACTIVE,
}
// ProtoValidateError tries to define interface for all Proto Validation errors,
// so we can generate better errors back to user.
type ProtoValidateError interface {
Field() string
Reason() string
Cause() error
Key() bool
ErrorName() string
}
func betterValidationErrorWithPath(err error) error {
var protoValidErr ProtoValidateError
if errors.As(err, &protoValidErr) {
err = handleProtoValidationError(protoValidErr, true)
}
return err
}
func handleProtoValidationError(err ProtoValidateError, withPath bool) error {
path := []string{
err.Field(),
}
for err.Cause() != nil {
var causeErr ProtoValidateError
if !errors.As(err.Cause(), &causeErr) {
break
}
path = append(path, causeErr.Field())
err = causeErr
}
cause := ""
if err.Cause() != nil {
cause = " caused by: " + err.Cause().Error()
}
var attribute string
if withPath {
attribute = strings.Join(path, ".")
} else {
attribute = path[len(attribute)-1]
}
return fmt.Errorf("invalid %s: %s%s", attribute, err.Reason(), cause)
}
func contains[E comparable](arr []E, el E) bool {
for _, v := range arr {
if v == el {
return true
}
}
return false
}