-
Notifications
You must be signed in to change notification settings - Fork 114
/
string.go
400 lines (349 loc) · 12.4 KB
/
string.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
// Package provider string.go provides shared functionality between `resource_string` and `resource_password`.
// There is no intent to permanently couple their implementations.
// Over time, they could diverge, or one becomes deprecated.
package provider
import (
"context"
"crypto/rand"
"errors"
"fmt"
"math/big"
"sort"
"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"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
// passwordSchemaV2 uses passwordSchemaV1 to obtain the V1 version of the Schema key-value entries but requires that
// the numeric entry be configured and that the number entry be altered to include ConflictsWith.
func passwordSchemaV2() map[string]*schema.Schema {
passwordSchema := passwordSchemaV1()
passwordSchema["number"] = &schema.Schema{
Description: "Include numeric characters in the result. Default value is `true`. " +
"**NOTE**: This is deprecated, use `numeric` instead.",
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"numeric"},
Deprecated: "Use numeric instead.",
}
passwordSchema["numeric"] = &schema.Schema{
Description: "Include numeric characters in the result. Default value is `true`.",
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"number"},
}
return passwordSchema
}
// passwordSchemaV1 uses passwordSchemaV0 to obtain the V0 version of the Schema key-value entries but requires that
// the bcrypt_hash entry be configured.
func passwordSchemaV1() map[string]*schema.Schema {
passwordSchema := passwordSchemaV0()
passwordSchema["bcrypt_hash"] = &schema.Schema{
Description: "A bcrypt hash of the generated random string.",
Type: schema.TypeString,
Computed: true,
Sensitive: true,
}
return passwordSchema
}
// passwordSchemaV0 uses passwordStringSchema to obtain the default Schema key-value entries but requires that the id
// description, result sensitive and bcrypt_hash entries be configured.
func passwordSchemaV0() map[string]*schema.Schema {
passwordSchema := passwordStringSchema()
passwordSchema["id"].Description = "A static value used internally by Terraform, this should not be referenced in configurations."
passwordSchema["result"].Sensitive = true
return passwordSchema
}
// stringSchemaV2 uses stringSchemaV1 to obtain the V1 version of the Schema key-value entries but requires that
// the numeric entry be configured and that the number entry be altered to include ConflictsWith.
func stringSchemaV2() map[string]*schema.Schema {
stringSchema := stringSchemaV1()
stringSchema["number"] = &schema.Schema{
Description: "Include numeric characters in the result. Default value is `true`. " +
"**NOTE**: This is deprecated, use `numeric` instead.",
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"numeric"},
Deprecated: "Use numeric instead.",
}
stringSchema["numeric"] = &schema.Schema{
Description: "Include numeric characters in the result. Default value is `true`.",
Type: schema.TypeBool,
Optional: true,
Computed: true,
ForceNew: true,
ConflictsWith: []string{"number"},
}
return stringSchema
}
// stringSchemaV1 uses passwordStringSchema to obtain the default Schema key-value entries but requires that the id
// description be configured.
func stringSchemaV1() map[string]*schema.Schema {
stringSchema := passwordStringSchema()
stringSchema["id"].Description = "The generated random string."
return stringSchema
}
// passwordStringSchema returns map[string]*schema.Schema with all keys and values that are common to both the
// password and string resources.
func passwordStringSchema() map[string]*schema.Schema {
return map[string]*schema.Schema{
"keepers": {
Description: "Arbitrary map of values that, when changed, will trigger recreation of " +
"resource. See [the main provider documentation](../index.html) for more information.",
Type: schema.TypeMap,
Optional: true,
ForceNew: true,
},
"length": {
Description: "The length of the string desired. The minimum value for length is 1 and, length " +
"must also be >= (`min_upper` + `min_lower` + `min_numeric` + `min_special`).",
Type: schema.TypeInt,
Required: true,
ForceNew: true,
ValidateDiagFunc: validation.ToDiagFunc(validation.IntAtLeast(1)),
},
"special": {
Description: "Include special characters in the result. These are `!@#$%&*()-_=+[]{}<>:?`. Default value is `true`.",
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},
"upper": {
Description: "Include uppercase alphabet characters in the result. Default value is `true`.",
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},
"lower": {
Description: "Include lowercase alphabet characters in the result. Default value is `true`.",
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},
"number": {
Description: "Include numeric characters in the result. Default value is `true`.",
Type: schema.TypeBool,
Optional: true,
Default: true,
ForceNew: true,
},
"min_numeric": {
Description: "Minimum number of numeric characters in the result. Default value is `0`.",
Type: schema.TypeInt,
Optional: true,
Default: 0,
ForceNew: true,
},
"min_upper": {
Description: "Minimum number of uppercase alphabet characters in the result. Default value is `0`.",
Type: schema.TypeInt,
Optional: true,
Default: 0,
ForceNew: true,
},
"min_lower": {
Description: "Minimum number of lowercase alphabet characters in the result. Default value is `0`.",
Type: schema.TypeInt,
Optional: true,
Default: 0,
ForceNew: true,
},
"min_special": {
Description: "Minimum number of special characters in the result. Default value is `0`.",
Type: schema.TypeInt,
Optional: true,
Default: 0,
ForceNew: true,
},
"override_special": {
Description: "Supply your own list of special characters to use for string generation. This " +
"overrides the default character list in the special argument. The `special` argument must " +
"still be set to true for any overwritten characters to be used in generation.",
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"result": {
Description: "The generated random string.",
Type: schema.TypeString,
Computed: true,
},
"id": {
Computed: true,
Type: schema.TypeString,
},
}
}
func createStringFunc(sensitive bool) func(_ context.Context, d *schema.ResourceData, _ interface{}) diag.Diagnostics {
return func(_ context.Context, d *schema.ResourceData, _ interface{}) diag.Diagnostics {
const numChars = "0123456789"
const lowerChars = "abcdefghijklmnopqrstuvwxyz"
const upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var (
specialChars = "!@#$%&*()-_=+[]{}<>:?"
diags diag.Diagnostics
)
length := d.Get("length").(int)
upper := d.Get("upper").(bool)
minUpper := d.Get("min_upper").(int)
lower := d.Get("lower").(bool)
minLower := d.Get("min_lower").(int)
number := d.Get("number").(bool)
numeric := d.Get("numeric").(bool)
minNumeric := d.Get("min_numeric").(int)
special := d.Get("special").(bool)
minSpecial := d.Get("min_special").(int)
overrideSpecial := d.Get("override_special").(string)
if length < minUpper+minLower+minNumeric+minSpecial {
return append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: fmt.Sprintf("length (%d) must be >= min_upper + min_lower + min_numeric + min_special (%d)", length, minUpper+minLower+minNumeric+minSpecial),
})
}
if overrideSpecial != "" {
specialChars = overrideSpecial
}
var chars = string("")
if upper {
chars += upperChars
}
if lower {
chars += lowerChars
}
if numeric {
chars += numChars
}
if special {
chars += specialChars
}
minMapping := map[string]int{
numChars: minNumeric,
lowerChars: minLower,
upperChars: minUpper,
specialChars: minSpecial,
}
var result = make([]byte, 0, length)
for k, v := range minMapping {
s, err := generateRandomBytes(&k, v)
if err != nil {
return append(diags, diag.Errorf("error generating random bytes: %s", err)...)
}
result = append(result, s...)
}
s, err := generateRandomBytes(&chars, length-len(result))
if err != nil {
return append(diags, diag.Errorf("error generating random bytes: %s", err)...)
}
result = append(result, s...)
order := make([]byte, len(result))
if _, err := rand.Read(order); err != nil {
return append(diags, diag.Errorf("error generating random bytes: %s", err)...)
}
sort.Slice(result, func(i, j int) bool {
return order[i] < order[j]
})
if err := d.Set("result", string(result)); err != nil {
return append(diags, diag.Errorf("error setting result: %s", err)...)
}
if err := d.Set("number", number); err != nil {
return append(diags, diag.Errorf("error setting number: %s", err)...)
}
if err := d.Set("numeric", numeric); err != nil {
return append(diags, diag.Errorf("error setting numeric: %s", err)...)
}
if sensitive {
d.SetId("none")
} else {
d.SetId(string(result))
}
return nil
}
}
func generateRandomBytes(charSet *string, length int) ([]byte, error) {
bytes := make([]byte, length)
setLen := big.NewInt(int64(len(*charSet)))
for i := range bytes {
idx, err := rand.Int(rand.Reader, setLen)
if err != nil {
return nil, err
}
bytes[i] = (*charSet)[idx.Int64()]
}
return bytes, nil
}
func readNil(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
return nil
}
func resourceStateUpgradeAddNumeric(resourceName string) func(_ context.Context, rawState map[string]interface{}, _ interface{}) (map[string]interface{}, error) {
return func(_ context.Context, rawState map[string]interface{}, _ interface{}) (map[string]interface{}, error) {
if rawState == nil {
return nil, fmt.Errorf("resource %s state upgrade failed, state is nil", resourceName)
}
number, ok := rawState["number"].(bool)
if !ok {
return nil, fmt.Errorf("resource %s state upgrade failed, number is not a boolean: %T", resourceName, rawState["number"])
}
rawState["numeric"] = number
return rawState, nil
}
}
// planDefaultIfAllNull handles ensuring that both `number` and `numeric` attributes default to `true` when neither are set
// in the config and, they had been previously set to `false`. This behaviour mimics setting `Default: true` on the
// attributes. Usage of `Default` is avoided as `Default` cannot be used with CustomizeDiffFunc(s) which are required in
// order to keep `number` and `numeric` in-sync (see planSyncIfChange).
func planDefaultIfAllNull(defaultVal interface{}, keys ...string) []schema.CustomizeDiffFunc {
var result []schema.CustomizeDiffFunc
for _, key := range keys {
result = append(result, customdiff.IfValue(
key,
func(ctx context.Context, value, meta interface{}) bool {
return !value.(bool)
},
func(_ context.Context, d *schema.ResourceDiff, _ interface{}) error {
vm := d.GetRawConfig().AsValueMap()
number, ok := vm["number"]
if !ok {
return errors.New("number is absent from raw config")
}
numeric, ok := vm["numeric"]
if !ok {
return errors.New("numeric is absent from raw config")
}
if number.IsNull() && numeric.IsNull() {
err := d.SetNew("number", defaultVal)
if err != nil {
return err
}
err = d.SetNew("numeric", defaultVal)
if err != nil {
return err
}
}
return nil
},
))
}
return result
}
// planSyncIfChange handles keeping `number` and `numeric` in-sync. If either is changed the value of both is
// set to the new value of the attribute that has changed.
func planSyncIfChange(key, keyToSync string) func(context.Context, *schema.ResourceDiff, interface{}) error {
return customdiff.IfValueChange(
key,
func(ctx context.Context, oldValue, newValue, meta interface{}) bool {
return oldValue != newValue
},
func(_ context.Context, d *schema.ResourceDiff, _ interface{}) error {
return d.SetNew(keyToSync, d.Get(key))
},
)
}