-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathresource_apikey_test.go
More file actions
567 lines (499 loc) · 16.4 KB
/
Copy pathresource_apikey_test.go
File metadata and controls
567 lines (499 loc) · 16.4 KB
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
package ns1
import (
"fmt"
"log"
"reflect"
"regexp"
"sort"
"testing"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
ns1 "gopkg.in/ns1/ns1-go.v2/rest"
"gopkg.in/ns1/ns1-go.v2/rest/model/account"
)
func TestAccAPIKey_basic(t *testing.T) {
var apiKey account.APIKey
name := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyBasic(name),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
testAccCheckAPIKeyIPWhitelists(&apiKey, []string{"1.1.1.1", "2.2.2.2"}),
testAccCheckAPIKeyNotEmpty(&apiKey),
resource.TestCheckResourceAttr("ns1_apikey.it", "ip_whitelist_strict", "true"),
),
},
{
ResourceName: "ns1_apikey.it",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"key"}, // importing existing key won't have the key
},
},
})
}
func TestAccAPIKey_updated(t *testing.T) {
var apiKey account.APIKey
name := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
updatedName := fmt.Sprintf("%s-updated", name)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyBasic(name),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
testAccCheckAPIKeyIPWhitelists(&apiKey, []string{"1.1.1.1", "2.2.2.2"}),
testAccCheckAPIKeyNotEmpty(&apiKey),
resource.TestCheckResourceAttr("ns1_apikey.it", "ip_whitelist_strict", "true"),
),
},
{
Config: testAccAPIKeyUpdated(updatedName),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, updatedName),
testAccCheckAPIKeyIPWhitelists(&apiKey, []string{}),
testAccCheckAPIKeyNotEmpty(&apiKey),
resource.TestCheckResourceAttr("ns1_apikey.it", "ip_whitelist_strict", "false"),
),
},
{
ResourceName: "ns1_apikey.it",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"key"}, // importing existing key won't have the key
},
},
})
}
func TestAccAPIKey_ManualDelete(t *testing.T) {
var apiKey account.APIKey
name := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyBasic(name),
Check: testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
},
// Simulate a manual deletion of the API key and verify that the plan has a diff.
{
PreConfig: testAccManualDeleteAPIKey(&apiKey),
Config: testAccAPIKeyBasic(name),
PlanOnly: true,
ExpectNonEmptyPlan: true,
},
// Then re-create and make sure it is there again.
{
Config: testAccAPIKeyBasic(name),
Check: testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
},
},
})
}
func TestAccAPIKey_teamKey(t *testing.T) {
var apiKey account.APIKey
rString := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
name := fmt.Sprintf("terraform acc test key %s", rString)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyPermissionsOnTeam(rString),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
testAccCheckAPIKeyNotEmpty(&apiKey),
),
},
{
ResourceName: "ns1_apikey.it",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"key"}, // importing existing key won't have the key
},
},
})
}
func TestAccAPIKey_permissions(t *testing.T) {
var apiKey account.APIKey
rString := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
name := fmt.Sprintf("terraform acc test key %s", rString)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyPermissionsNoTeam(rString),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
testAccCheckAPIKeyNotEmpty(&apiKey),
),
},
{
Config: testAccAPIKeyPermissionsOnTeam(rString),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
testAccCheckAPIKeyNotEmpty(&apiKey),
),
},
{
Config: testAccAPIKeyPermissionsNoTeam(rString),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
testAccCheckAPIKeyNotEmpty(&apiKey),
// The key should still have this permission, it would have inherited it from the team.
resource.TestCheckResourceAttr("ns1_apikey.it", "account_manage_account_settings", "true"),
resource.TestCheckResourceAttr("ns1_apikey.it", "account_manage_ip_whitelist", "true"),
),
ExpectNonEmptyPlan: true,
},
{
Config: testAccAPIKeyPermissionsNoTeam(rString),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
testAccCheckAPIKeyNotEmpty(&apiKey),
// But if an apply is ran again, the permission will be removed.
resource.TestCheckResourceAttr("ns1_apikey.it", "account_manage_account_settings", "false"),
resource.TestCheckResourceAttr("ns1_apikey.it", "account_manage_ip_whitelist", "false"),
),
},
{
ResourceName: "ns1_apikey.it",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"key"}, // importing existing key won't have the key
},
},
})
}
func TestAccAPIKey_emptyIPWhitelist(t *testing.T) {
var apiKey account.APIKey
name := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyEmptyIPWhitelist(name),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
resource.TestCheckResourceAttr("ns1_apikey.it", "ip_whitelist.#", "0"),
resource.TestCheckResourceAttr("ns1_apikey.it", "ip_whitelist_strict", "false"),
testAccCheckAPIKeyIPWhitelists(&apiKey, []string{}),
),
},
},
})
}
func testAccAPIKeyEmptyIPWhitelist(name string) string {
return fmt.Sprintf(`
resource "ns1_apikey" "it" {
name = "%s"
ip_whitelist_strict = false
ip_whitelist = []
dns_view_zones = false
account_manage_users = false
}
`, name)
}
func testAccCheckAPIKeyExists(n string, apiKey *account.APIKey) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("no ID is set")
}
client := testAccProvider.Meta().(*ns1.Client)
foundAPIKey, _, err := client.APIKeys.Get(rs.Primary.Attributes["id"])
p := rs.Primary
if err != nil {
return err
}
if foundAPIKey.ID != p.Attributes["id"] {
return fmt.Errorf("API key not found")
}
*apiKey = *foundAPIKey
return nil
}
}
func testAccCheckAPIKeyName(apiKey *account.APIKey, expected string) resource.TestCheckFunc {
return func(s *terraform.State) error {
if apiKey.Name != expected {
return fmt.Errorf("apiKey: got: %s want: %s", apiKey.Name, expected)
}
return nil
}
}
func testAccCheckAPIKeyDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*ns1.Client)
var apiKey string
for _, rs := range s.RootModule().Resources {
if rs.Type == "ns1_apikey" {
apiKey = rs.Primary.Attributes["id"]
}
}
key, _, _ := client.APIKeys.Get(apiKey)
if key != nil {
return fmt.Errorf("apiKey still exists: %#v", key)
}
return nil
}
func testAccCheckAPIKeyIPWhitelists(k *account.APIKey, expected []string) resource.TestCheckFunc {
return func(s *terraform.State) error {
actualList := k.IPWhitelist
expectedList := expected
sort.Strings(actualList)
sort.Strings(expectedList)
if !reflect.DeepEqual(actualList, expectedList) {
return fmt.Errorf("IPWhitelist: got values: %v want: %v", k.IPWhitelist, expected)
}
return nil
}
}
// Simulate a manual deletion of an API key.
func testAccManualDeleteAPIKey(apiKey *account.APIKey) func() {
return func() {
client := testAccProvider.Meta().(*ns1.Client)
_, err := client.APIKeys.Delete(apiKey.ID)
// Not a big deal if this fails, it will get caught in the test conditions and fail the test.
if err != nil {
log.Printf("failed to delete api key: %v", err)
}
}
}
func testAccCheckAPIKeyNotEmpty(k *account.APIKey) resource.TestCheckFunc {
return func(s *terraform.State) error {
var key string
for _, rs := range s.RootModule().Resources {
if rs.Primary.ID == k.ID {
key = rs.Primary.Attributes["key"]
}
}
if key == "" {
return fmt.Errorf("key should not be empty string")
}
return nil
}
}
func testAccAPIKeyBasic(apiKeyName string) string {
return fmt.Sprintf(`resource "ns1_apikey" "it" {
name = "%s"
ip_whitelist = ["1.1.1.1","2.2.2.2"]
ip_whitelist_strict = true
}
`, apiKeyName)
}
func testAccAPIKeyUpdated(apiKeyName string) string {
return fmt.Sprintf(`resource "ns1_apikey" "it" {
name = "%s"
}
`, apiKeyName)
}
func testAccAPIKeyPermissionsOnTeam(rString string) string {
return fmt.Sprintf(`resource "ns1_team" "t" {
name = "terraform acc test team %s"
account_manage_account_settings = true
account_manage_ip_whitelist = true
}
resource "ns1_apikey" "it" {
name = "terraform acc test key %s"
teams = ["${ns1_team.t.id}"]
}
`, rString, rString)
}
func TestAccAPIKey_withExpiryDuration(t *testing.T) {
var apiKey account.APIKey
name := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyWithExpiryDuration(name, "30d"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
resource.TestCheckResourceAttr("ns1_apikey.it", "expiry_duration", "30d"),
testAccCheckAPIKeyHasSecrets(&apiKey),
),
},
{
ResourceName: "ns1_apikey.it",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"key", "secrets"}, // importing existing key won't have the key or secret values
},
},
})
}
func TestAccAPIKey_updateExpiryDuration(t *testing.T) {
var apiKey account.APIKey
var apiKeyRecreated account.APIKey
name := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyBasic(name),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
resource.TestCheckResourceAttr("ns1_apikey.it", "expiry_duration", ""),
),
},
{
Config: testAccAPIKeyWithExpiryDuration(name, "30d"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKeyRecreated),
testAccCheckAPIKeyName(&apiKeyRecreated, name),
resource.TestCheckResourceAttr("ns1_apikey.it", "expiry_duration", "30d"),
testAccCheckAPIKeyHasSecrets(&apiKeyRecreated),
// Verify the API key was recreated (different ID)
testAccCheckAPIKeyRecreated(&apiKey, &apiKeyRecreated),
),
},
},
})
}
func testAccCheckAPIKeyHasSecrets(k *account.APIKey) resource.TestCheckFunc {
return func(s *terraform.State) error {
if len(k.Secrets) == 0 {
return fmt.Errorf("API key should have at least one secret when expiry_duration is set")
}
// Verify the first secret has required fields
secret := k.Secrets[0]
if secret.ID == "" {
return fmt.Errorf("secret should have an ID")
}
if secret.ExpiresAt == "" {
return fmt.Errorf("secret should have an expiration date")
}
if secret.Enabled == nil {
return fmt.Errorf("secret should have an enabled status")
}
return nil
}
}
func testAccCheckAPIKeyRecreated(old, new *account.APIKey) resource.TestCheckFunc {
return func(s *terraform.State) error {
if old.ID == new.ID {
return fmt.Errorf("expected API key to be recreated with new ID, but got same ID: %s", old.ID)
}
return nil
}
}
func testAccAPIKeyWithExpiryDuration(apiKeyName, expiryDuration string) string {
return fmt.Sprintf(`resource "ns1_apikey" "it" {
name = "%s"
expiry_duration = "%s"
dns_view_zones = false
account_manage_users = false
}
`, apiKeyName, expiryDuration)
}
func TestAccAPIKey_invalidExpiryDuration(t *testing.T) {
name := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyWithExpiryDuration(name, "invalid"),
ExpectError: regexp.MustCompile(`must be a duration in format '<number>d'`),
},
{
Config: testAccAPIKeyWithExpiryDuration(name, "30"),
ExpectError: regexp.MustCompile(`must be a duration in format '<number>d'`),
},
{
Config: testAccAPIKeyWithExpiryDuration(name, "d30"),
ExpectError: regexp.MustCompile(`must be a duration in format '<number>d'`),
},
},
})
}
func TestAccAPIKey_allExpiryDurations(t *testing.T) {
durations := []string{"10d", "30d", "90d"}
for _, duration := range durations {
t.Run(duration, func(t *testing.T) {
var apiKey account.APIKey
name := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyWithExpiryDuration(name, duration),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
resource.TestCheckResourceAttr("ns1_apikey.it", "expiry_duration", duration),
testAccCheckAPIKeyHasSecrets(&apiKey),
),
},
},
})
})
}
}
func TestAccAPIKey_customExpiryDuration(t *testing.T) {
var apiKey account.APIKey
name := acctest.RandStringFromCharSet(15, acctest.CharSetAlphaNum)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAPIKeyDestroy,
Steps: []resource.TestStep{
{
Config: testAccAPIKeyWithExpiryDuration(name, "45d"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAPIKeyExists("ns1_apikey.it", &apiKey),
testAccCheckAPIKeyName(&apiKey, name),
resource.TestCheckResourceAttr("ns1_apikey.it", "expiry_duration", "45d"),
testAccCheckAPIKeyHasSecrets(&apiKey),
),
},
},
})
}
func testAccAPIKeyPermissionsNoTeam(rString string) string {
return fmt.Sprintf(`resource "ns1_team" "t" {
name = "terraform acc test team %s"
account_manage_account_settings = true
account_manage_ip_whitelist = true
}
resource "ns1_apikey" "it" {
name = "terraform acc test key %s"
}
`, rString, rString)
}