forked from integrations/terraform-provider-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource_github_actions_secret_test.go
More file actions
559 lines (486 loc) · 18.2 KB
/
resource_github_actions_secret_test.go
File metadata and controls
559 lines (486 loc) · 18.2 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
package github
import (
"encoding/base64"
"fmt"
"strings"
"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/helper/schema"
)
func TestAccGithubActionsSecret(t *testing.T) {
t.Run("reads a repository public key without error", func(t *testing.T) {
randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)
repoName := fmt.Sprintf("%srepo-act-secret-%s", testResourcePrefix, randomID)
config := fmt.Sprintf(`
resource "github_repository" "test" {
name = "%s"
}
data "github_actions_public_key" "test_pk" {
repository = github_repository.test.name
}
`, repoName)
check := resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet(
"data.github_actions_public_key.test_pk", "key_id",
),
resource.TestCheckResourceAttrSet(
"data.github_actions_public_key.test_pk", "key",
),
)
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnauthenticated(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: config,
Check: check,
},
},
})
})
t.Run("creates and updates secrets without error", func(t *testing.T) {
randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)
repoName := fmt.Sprintf("%srepo-act-secret-%s", testResourcePrefix, randomID)
secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value"))
updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value"))
config := fmt.Sprintf(`
resource "github_repository" "test" {
name = "%s"
}
resource "github_actions_secret" "plaintext_secret" {
repository = github_repository.test.name
secret_name = "test_plaintext_secret"
plaintext_value = "%s"
}
resource "github_actions_secret" "encrypted_secret" {
repository = github_repository.test.name
secret_name = "test_encrypted_secret"
encrypted_value = "%s"
}
`, repoName, secretValue, secretValue)
checks := map[string]resource.TestCheckFunc{
"before": resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"github_actions_secret.plaintext_secret", "plaintext_value",
secretValue,
),
resource.TestCheckResourceAttr(
"github_actions_secret.encrypted_secret", "encrypted_value",
secretValue,
),
resource.TestCheckResourceAttrSet(
"github_actions_secret.plaintext_secret", "created_at",
),
resource.TestCheckResourceAttrSet(
"github_actions_secret.plaintext_secret", "updated_at",
),
),
"after": resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"github_actions_secret.plaintext_secret", "plaintext_value",
updatedSecretValue,
),
resource.TestCheckResourceAttr(
"github_actions_secret.encrypted_secret", "encrypted_value",
updatedSecretValue,
),
resource.TestCheckResourceAttrSet(
"github_actions_secret.plaintext_secret", "created_at",
),
resource.TestCheckResourceAttrSet(
"github_actions_secret.plaintext_secret", "updated_at",
),
),
}
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnauthenticated(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: config,
Check: checks["before"],
},
{
Config: strings.Replace(config,
secretValue,
updatedSecretValue, 2),
Check: checks["after"],
},
},
})
})
t.Run("creates and updates repository name without error", func(t *testing.T) {
randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)
repoName := fmt.Sprintf("%srepo-act-secret-%s", testResourcePrefix, randomID)
updatedRepoName := fmt.Sprintf("%srepo-act-secret-%s-upd", testResourcePrefix, randomID)
secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value"))
config := fmt.Sprintf(`
resource "github_repository" "test" {
name = "%s"
}
resource "github_actions_secret" "plaintext_secret" {
repository = github_repository.test.name
secret_name = "test_plaintext_secret"
plaintext_value = "%s"
}
resource "github_actions_secret" "encrypted_secret" {
repository = github_repository.test.name
secret_name = "test_encrypted_secret"
encrypted_value = "%s"
}
`, repoName, secretValue, secretValue)
checks := map[string]resource.TestCheckFunc{
"before": resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"github_actions_secret.plaintext_secret", "repository",
repoName,
),
resource.TestCheckResourceAttr(
"github_actions_secret.plaintext_secret", "plaintext_value",
secretValue,
),
resource.TestCheckResourceAttr(
"github_actions_secret.encrypted_secret", "encrypted_value",
secretValue,
),
resource.TestCheckResourceAttrSet(
"github_actions_secret.plaintext_secret", "created_at",
),
resource.TestCheckResourceAttrSet(
"github_actions_secret.plaintext_secret", "updated_at",
),
),
"after": resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"github_actions_secret.plaintext_secret", "repository",
updatedRepoName,
),
resource.TestCheckResourceAttr(
"github_actions_secret.plaintext_secret", "plaintext_value",
secretValue,
),
resource.TestCheckResourceAttr(
"github_actions_secret.encrypted_secret", "encrypted_value",
secretValue,
),
resource.TestCheckResourceAttrSet(
"github_actions_secret.plaintext_secret", "created_at",
),
resource.TestCheckResourceAttrSet(
"github_actions_secret.plaintext_secret", "updated_at",
),
),
}
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnauthenticated(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: config,
Check: checks["before"],
},
{
Config: strings.Replace(config,
repoName,
updatedRepoName, 2),
Check: checks["after"],
},
},
})
})
t.Run("deletes secrets without error", func(t *testing.T) {
randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)
repoName := fmt.Sprintf("%srepo-act-secret-%s", testResourcePrefix, randomID)
config := fmt.Sprintf(`
resource "github_repository" "test" {
name = "%s"
}
resource "github_actions_secret" "plaintext_secret" {
repository = github_repository.test.name
secret_name = "test_plaintext_secret"
}
resource "github_actions_secret" "encrypted_secret" {
repository = github_repository.test.name
secret_name = "test_encrypted_secret"
}
`, repoName)
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnauthenticated(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: config,
Destroy: true,
},
},
})
})
t.Run("respects destroy_on_drift setting", func(t *testing.T) {
randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)
repoName := fmt.Sprintf("%srepo-act-secret-%s", testResourcePrefix, randomID)
config := fmt.Sprintf(`
resource "github_repository" "test" {
name = "%s"
}
resource "github_actions_secret" "with_drift_true" {
repository = github_repository.test.name
secret_name = "test_drift_true"
plaintext_value = "initial_value"
destroy_on_drift = true
}
resource "github_actions_secret" "with_drift_false" {
repository = github_repository.test.name
secret_name = "test_drift_false"
plaintext_value = "initial_value"
destroy_on_drift = false
}
resource "github_actions_secret" "default_behavior" {
repository = github_repository.test.name
secret_name = "test_default"
plaintext_value = "initial_value"
# destroy_on_drift defaults to true
}
`, repoName)
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnauthenticated(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: config,
Check: resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"github_actions_secret.with_drift_true", "destroy_on_drift", "true"),
resource.TestCheckResourceAttr(
"github_actions_secret.with_drift_false", "destroy_on_drift", "false"),
resource.TestCheckResourceAttr(
"github_actions_secret.default_behavior", "destroy_on_drift", "true"),
resource.TestCheckResourceAttr(
"github_actions_secret.with_drift_true", "plaintext_value", "initial_value"),
resource.TestCheckResourceAttr(
"github_actions_secret.with_drift_false", "plaintext_value", "initial_value"),
resource.TestCheckResourceAttr(
"github_actions_secret.default_behavior", "plaintext_value", "initial_value"),
),
},
},
})
})
}
// Unit tests for drift detection behavior.
func TestGithubActionsSecretDriftDetection(t *testing.T) {
t.Run("destroyOnDrift true causes recreation on timestamp mismatch", func(t *testing.T) {
originalTimestamp := "2023-01-01T00:00:00Z"
newTimestamp := "2023-01-02T00:00:00Z"
d := schema.TestResourceDataRaw(t, resourceGithubActionsSecret().Schema, map[string]any{
"repository": "test-repo",
"secret_name": "test-secret",
"plaintext_value": "test-value",
"destroy_on_drift": true,
"updated_at": originalTimestamp,
})
d.SetId("test-secret")
// Test the drift detection logic - simulate what happens in the read function
destroyOnDrift := d.Get("destroy_on_drift").(bool)
if updatedAt, ok := d.GetOk("updated_at"); ok && destroyOnDrift && updatedAt != newTimestamp {
d.SetId("") // This simulates the drift detection
}
// Should have cleared the ID (marking for recreation)
if d.Id() != "" {
t.Error("Expected ID to be cleared due to drift detection, but it wasn't")
}
})
t.Run("destroyOnDrift false clears sensitive values instead of recreating", func(t *testing.T) {
originalTimestamp := "2023-01-01T00:00:00Z"
newTimestamp := "2023-01-02T00:00:00Z"
d := schema.TestResourceDataRaw(t, resourceGithubActionsSecret().Schema, map[string]any{
"repository": "test-repo",
"secret_name": "test-secret",
"plaintext_value": "original-value",
"encrypted_value": "original-encrypted",
"destroy_on_drift": false,
"updated_at": originalTimestamp,
})
d.SetId("test-secret")
// Simulate drift detection logic when destroy_on_drift is false
destroyOnDrift := d.Get("destroy_on_drift").(bool)
storedUpdatedAt, hasStoredUpdatedAt := d.GetOk("updated_at")
if hasStoredUpdatedAt && storedUpdatedAt != newTimestamp {
if destroyOnDrift {
// Would clear ID for recreation
d.SetId("")
} else {
// Should clear sensitive values to trigger update
_ = d.Set("encrypted_value", "")
_ = d.Set("plaintext_value", "")
}
_ = d.Set("updated_at", newTimestamp)
}
// Should NOT have cleared the ID when destroy_on_drift=false
if d.Id() == "" {
t.Error("Expected ID to be preserved when destroy_on_drift=false, but it was cleared")
}
// Should have cleared sensitive values to trigger update plan
if plaintextValue := d.Get("plaintext_value").(string); plaintextValue != "" {
t.Errorf("Expected plaintext_value to be cleared for update plan, got %s", plaintextValue)
}
if encryptedValue := d.Get("encrypted_value").(string); encryptedValue != "" {
t.Errorf("Expected encrypted_value to be cleared for update plan, got %s", encryptedValue)
}
// Should have updated the timestamp
if updatedAt := d.Get("updated_at").(string); updatedAt != newTimestamp {
t.Errorf("Expected timestamp to be updated to %s, got %s", newTimestamp, updatedAt)
}
})
t.Run("destroyOnDrift true still recreates resource on drift", func(t *testing.T) {
originalTimestamp := "2023-01-01T00:00:00Z"
newTimestamp := "2023-01-02T00:00:00Z"
d := schema.TestResourceDataRaw(t, resourceGithubActionsSecret().Schema, map[string]any{
"repository": "test-repo",
"secret_name": "test-secret",
"plaintext_value": "original-value",
"destroy_on_drift": true, // Explicitly set to true
"updated_at": originalTimestamp,
})
d.SetId("test-secret")
// Simulate drift detection logic when destroy_on_drift is true
destroyOnDrift := d.Get("destroy_on_drift").(bool)
storedUpdatedAt, hasStoredUpdatedAt := d.GetOk("updated_at")
if hasStoredUpdatedAt && storedUpdatedAt != newTimestamp {
if destroyOnDrift {
// Should clear ID for recreation (original behavior)
d.SetId("")
return // Exit early like the real function would
}
}
// Should have cleared the ID for recreation when destroy_on_drift=true
if d.Id() != "" {
t.Error("Expected ID to be cleared for recreation when destroy_on_drift=true, but it was preserved")
}
})
t.Run("destroyOnDrift true still recreates resource on drift", func(t *testing.T) {
originalTimestamp := "2023-01-01T00:00:00Z"
newTimestamp := "2023-01-02T00:00:00Z"
d := schema.TestResourceDataRaw(t, resourceGithubActionsSecret().Schema, map[string]any{
"repository": "test-repo",
"secret_name": "test-secret",
"plaintext_value": "original-value",
"destroy_on_drift": true, // Explicitly set to true
"updated_at": originalTimestamp,
})
d.SetId("test-secret")
// Simulate drift detection logic when destroy_on_drift is true
destroyOnDrift := d.Get("destroy_on_drift").(bool)
storedUpdatedAt, hasStoredUpdatedAt := d.GetOk("updated_at")
if hasStoredUpdatedAt && storedUpdatedAt != newTimestamp {
if destroyOnDrift {
// Should clear ID for recreation (original behavior)
d.SetId("")
return // Exit early like the real function would
}
}
// Should have cleared the ID for recreation when destroy_on_drift=true
if d.Id() != "" {
t.Error("Expected ID to be cleared for recreation when destroy_on_drift=true, but it was preserved")
}
})
t.Run("default destroy_on_drift is true", func(t *testing.T) {
d := schema.TestResourceDataRaw(t, resourceGithubActionsSecret().Schema, map[string]any{
"repository": "test-repo",
"secret_name": "test-secret",
"plaintext_value": "test-value",
// destroy_on_drift not set, should default to true
})
destroyOnDrift := d.Get("destroy_on_drift").(bool)
if !destroyOnDrift {
t.Error("Expected destroy_on_drift to default to true")
}
})
t.Run("no drift when timestamps match", func(t *testing.T) {
timestamp := "2023-01-01T00:00:00Z"
d := schema.TestResourceDataRaw(t, resourceGithubActionsSecret().Schema, map[string]any{
"repository": "test-repo",
"secret_name": "test-secret",
"plaintext_value": "test-value",
"destroy_on_drift": true,
"updated_at": timestamp,
})
d.SetId("test-secret")
// Simulate same timestamp (no external change)
destroyOnDrift := d.Get("destroy_on_drift").(bool)
if updatedAt, ok := d.GetOk("updated_at"); ok && destroyOnDrift && updatedAt != timestamp {
d.SetId("") // This should NOT happen
}
// Should NOT have cleared the ID
if d.Id() == "" {
t.Error("Expected ID to be preserved when no drift detected, but it was cleared")
}
})
t.Run("destroy_on_drift field defaults", func(t *testing.T) {
// Test that destroy_on_drift defaults to true for backward compatibility
schema := resourceGithubActionsSecret().Schema["destroy_on_drift"]
if schema.Default != true {
t.Error("destroy_on_drift should default to true for backward compatibility")
}
})
t.Run("destroy_on_drift field properties", func(t *testing.T) {
resource := resourceGithubActionsSecret()
driftField := resource.Schema["destroy_on_drift"]
// Should be optional
if driftField.Required {
t.Error("Expected destroy_on_drift to be optional, but it's required")
}
if !driftField.Optional {
t.Error("Expected destroy_on_drift to be optional")
}
// Should be boolean type
if driftField.Type.String() != "TypeBool" {
t.Errorf("Expected destroy_on_drift to be TypeBool, got %s", driftField.Type.String())
}
// Should have default value of true
if driftField.Default != true {
t.Errorf("Expected destroy_on_drift default to be true, got %v", driftField.Default)
}
// Should have description
if driftField.Description == "" {
t.Error("Expected destroy_on_drift to have a description")
}
})
}
// Test demonstrating the solution to GitHub issue #964.
func TestGithubActionsSecretIssue964Solution(t *testing.T) {
t.Run("solve issue 964 - prevent recreation when GUI changes secret", func(t *testing.T) {
// This test demonstrates the fix for:
// https://github.com/integrations/terraform-provider-github/issues/964
// Scenario: User creates secret with Terraform, then updates value via GitHub GUI
// Expected: With destroy_on_drift=false, Terraform should not recreate the secret
d := schema.TestResourceDataRaw(t, resourceGithubActionsSecret().Schema, map[string]any{
"repository": "my-repo",
"secret_name": "WORKFLOW_PAT",
"plaintext_value": "CHANGE_ME", // Initial placeholder value
"destroy_on_drift": false, // KEY FIX: Prevents recreation
})
d.SetId("WORKFLOW_PAT")
// Set initial timestamp
originalTime := "2023-01-01T00:00:00Z"
_ = d.Set("updated_at", originalTime)
// Simulate: User changes secret value via GitHub GUI
// This changes the updated_at timestamp
newTime := "2023-01-01T12:00:00Z" // Later timestamp = external change
// Test the read function behavior - this is what happens during terraform plan/apply
destroyOnDrift := d.Get("destroy_on_drift").(bool) // false
if updatedAt, ok := d.GetOk("updated_at"); ok && !destroyOnDrift && updatedAt != newTime {
// With destroy_on_drift=false, we update timestamp but don't clear ID
_ = d.Set("updated_at", newTime)
}
// RESULT: Secret should NOT be marked for recreation
if d.Id() == "" {
t.Error("ISSUE #964 NOT FIXED: Secret was marked for recreation despite destroy_on_drift=false")
}
// RESULT: Timestamp should be updated to acknowledge the change
if d.Get("updated_at").(string) != newTime {
t.Error("Expected timestamp to be updated to acknowledge external change")
}
t.Logf("SUCCESS: Issue #964 solved - secret with destroy_on_drift=false does not get recreated on external changes")
})
}