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_organization_secret_test.go
More file actions
342 lines (304 loc) · 10.8 KB
/
resource_github_actions_organization_secret_test.go
File metadata and controls
342 lines (304 loc) · 10.8 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
package github
import (
"encoding/base64"
"fmt"
"strings"
"testing"
"github.com/google/go-github/v81/github"
"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"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)
func TestAccGithubActionsOrganizationSecret(t *testing.T) {
t.Run("creates and updates secrets without error", func(t *testing.T) {
secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value"))
updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value"))
config := fmt.Sprintf(`
resource "github_actions_organization_secret" "plaintext_secret" {
secret_name = "test_plaintext_secret"
plaintext_value = "%s"
visibility = "private"
}
resource "github_actions_organization_secret" "encrypted_secret" {
secret_name = "test_encrypted_secret"
encrypted_value = "%s"
visibility = "private"
destroy_on_drift = false
}
`, secretValue, secretValue)
checks := map[string]resource.TestCheckFunc{
"before": resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"github_actions_organization_secret.plaintext_secret", "plaintext_value",
secretValue,
),
resource.TestCheckResourceAttr(
"github_actions_organization_secret.encrypted_secret", "encrypted_value",
secretValue,
),
resource.TestCheckResourceAttrSet(
"github_actions_organization_secret.plaintext_secret", "created_at",
),
resource.TestCheckResourceAttrSet(
"github_actions_organization_secret.plaintext_secret", "updated_at",
),
),
"after": resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"github_actions_organization_secret.plaintext_secret", "plaintext_value",
updatedSecretValue,
),
resource.TestCheckResourceAttr(
"github_actions_organization_secret.encrypted_secret", "encrypted_value",
updatedSecretValue,
),
resource.TestCheckResourceAttrSet(
"github_actions_organization_secret.plaintext_secret", "created_at",
),
resource.TestCheckResourceAttrSet(
"github_actions_organization_secret.plaintext_secret", "updated_at",
),
),
}
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnlessHasOrgs(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: config,
Check: checks["before"],
},
{
Config: strings.Replace(config,
secretValue,
updatedSecretValue, 2),
Check: checks["after"],
},
},
})
})
t.Run("deletes secrets without error", func(t *testing.T) {
config := `
resource "github_actions_organization_secret" "plaintext_secret" {
secret_name = "test_plaintext_secret"
visibility = "private"
}
resource "github_actions_organization_secret" "encrypted_secret" {
secret_name = "test_encrypted_secret"
visibility = "private"
}
`
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnlessHasOrgs(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: config,
Destroy: true,
},
},
})
})
t.Run("imports secrets without error", func(t *testing.T) {
secretValue := "super_secret_value"
config := fmt.Sprintf(`
resource "github_actions_organization_secret" "test_secret" {
secret_name = "test_plaintext_secret"
plaintext_value = "%s"
visibility = "private"
}
`, secretValue)
check := resource.ComposeTestCheckFunc(
resource.TestCheckResourceAttr(
"github_actions_organization_secret.test_secret", "plaintext_value",
secretValue,
),
)
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnlessHasOrgs(t) },
ProviderFactories: providerFactories,
Steps: []resource.TestStep{
{
Config: config,
Check: check,
},
{
ResourceName: "github_actions_organization_secret.test_secret",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"plaintext_value"},
},
},
})
})
}
func TestAccGithubActionsOrganizationSecret_DestroyOnDrift(t *testing.T) {
t.Run("destroyOnDrift false", func(t *testing.T) {
destroyOnDrift := false
t.Run("should ignore drift when ignore_changes lifecycle is configured", func(t *testing.T) {
// Verify https://github.com/integrations/terraform-provider-github/issues/2614
randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)
config := fmt.Sprintf(`
resource "github_actions_organization_secret" "test_secret" {
secret_name = "test_secret_%s"
plaintext_value = "test_value"
visibility = "private"
destroy_on_drift = %t
lifecycle {
ignore_changes = [plaintext_value]
}
}
`, randomID, destroyOnDrift)
resource.Test(t, resource.TestCase{
PreCheck: func() { skipUnlessHasOrgs(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: config,
},
{
Config: config,
Check: resource.ComposeTestCheckFunc(
func(s *terraform.State) error {
rs, ok := s.RootModule().Resources["github_actions_organization_secret.test_secret"]
if !ok {
t.Errorf("not found: github_actions_organization_secret.test_secret")
}
// Now that the secret is created, update it to trigger a drift.
client := testAccProvider.Meta().(*Owner).v3client
owner := testAccProvider.Meta().(*Owner).name
ctx := t.Context()
keyId, publicKey, err := getOrganizationPublicKeyDetails(owner, testAccProvider.Meta().(*Owner))
if err != nil {
t.Errorf("Failed to get organization public key details: %v", err)
}
encryptedSecret, err := createEncryptedSecret(rs.Primary, "foo", keyId, publicKey)
if err != nil {
t.Errorf("Failed to create encrypted secret: %v", err)
}
_, err = client.Actions.CreateOrUpdateOrgSecret(ctx, owner, encryptedSecret)
if err != nil {
t.Errorf("Failed to create or update organization secret: %v", err)
}
return err
},
),
},
{
Config: config,
PlanOnly: true,
ExpectNonEmptyPlan: false,
},
},
})
})
})
// t.Run("destroyOnDrift true", func(t *testing.T) {
// destroyOnDrift := true
// })
}
func TestGithubActionsOrganizationSecret_DestroyOnDrift(t *testing.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, resourceGithubActionsOrganizationSecret().Schema, map[string]any{
"secret_name": "test-secret",
"plaintext_value": "original-value",
"encrypted_value": "original-encrypted",
"visibility": "private",
"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, resourceGithubActionsOrganizationSecret().Schema, map[string]any{
"secret_name": "test-secret",
"plaintext_value": "original-value",
"visibility": "private",
"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("destroy_on_drift field defaults", func(t *testing.T) {
// Test that destroy_on_drift defaults to true for backward compatibility
schema := resourceGithubActionsOrganizationSecret().Schema["destroy_on_drift"]
if schema.Default != true {
t.Error("destroy_on_drift should default to true for backward compatibility")
}
})
t.Run("default destroy_on_drift is true", func(t *testing.T) {
d := schema.TestResourceDataRaw(t, resourceGithubActionsOrganizationSecret().Schema, map[string]any{
"secret_name": "test-secret",
"plaintext_value": "test-value",
"visibility": "private",
// 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")
}
})
}
func createEncryptedSecret(is *terraform.InstanceState, plaintextValue, keyId, publicKey string) (*github.EncryptedSecret, error) {
secretName := is.Attributes["secret_name"]
visibility := is.Attributes["visibility"]
encryptedBytes, err := encryptPlaintext(plaintextValue, publicKey)
if err != nil {
return nil, err
}
encryptedValue := base64.StdEncoding.EncodeToString(encryptedBytes)
return &github.EncryptedSecret{
Name: secretName,
KeyID: keyId,
Visibility: visibility,
EncryptedValue: encryptedValue,
}, nil
}