-
Notifications
You must be signed in to change notification settings - Fork 9.7k
/
Copy pathhelpers_test.go
348 lines (292 loc) · 11.5 KB
/
helpers_test.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package azure
import (
"context"
"fmt"
"log"
"math/rand"
"os"
"strings"
"testing"
"time"
"github.com/hashicorp/go-azure-helpers/lang/pointer"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonids"
sasStorage "github.com/hashicorp/go-azure-helpers/storage"
"github.com/hashicorp/go-azure-sdk/resource-manager/resources/2024-03-01/resourcegroups"
"github.com/hashicorp/go-azure-sdk/resource-manager/storage/2023-01-01/storageaccounts"
"github.com/hashicorp/go-azure-sdk/sdk/auth"
"github.com/hashicorp/go-azure-sdk/sdk/environments"
"github.com/jackofallops/giovanni/storage/2023-11-03/blob/blobs"
"github.com/jackofallops/giovanni/storage/2023-11-03/blob/containers"
)
const (
// required for Azure Stack
sasSignedVersion = "2015-04-05"
)
// verify that we are doing ACC tests or the Azure tests specifically
func testAccAzureBackend(t *testing.T) {
skip := os.Getenv("TF_ACC") == "" && os.Getenv("TF_AZURE_TEST") == ""
if skip {
t.Log("azure backend tests require setting TF_ACC or TF_AZURE_TEST")
t.Skip()
}
}
// these kind of tests can only run when within Azure (e.g. MSI)
func testAccAzureBackendRunningInAzure(t *testing.T) {
testAccAzureBackend(t)
if os.Getenv("TF_RUNNING_IN_AZURE") == "" {
t.Skip("Skipping test since not running in Azure")
}
}
// these kind of tests can only run when within GitHub Actions (e.g. OIDC)
func testAccAzureBackendRunningInGitHubActions(t *testing.T) {
testAccAzureBackend(t)
if os.Getenv("TF_RUNNING_IN_GITHUB_ACTIONS") == "" {
t.Skip("Skipping test since not running in GitHub Actions")
}
}
// these kind of tests can only run when within ADO Pipelines (e.g. OIDC)
func testAccAzureBackendRunningInADOPipelines(t *testing.T) {
testAccAzureBackend(t)
if os.Getenv("TF_RUNNING_IN_ADO_PIPELINES") == "" {
t.Skip("Skipping test since not running in ADO Pipelines")
}
}
// clearARMEnv cleans up the azure related environment variables.
// This is to ensure the configuration only comes from HCL, which avoids
// env vars for test setup interfere the behavior.
//
// NOTE: Since `go test` runs all test cases in a single process, clearing
// environment has a whole process impact to other test cases. While this
// impact can be eliminated given all the tests are implemented in a similar
// pattern that those env vars will be consumed at the very begining. The test
// runner has to ensure to set a **big enough parallelism**.
func clearARMEnv() {
for _, evexp := range os.Environ() {
k, _, ok := strings.Cut(evexp, "=")
if !ok {
continue
}
if strings.HasPrefix(k, "ARM_") {
os.Unsetenv(k)
}
}
}
func buildSasToken(accountName, accessKey string) (*string, error) {
// grant full access to Objects in the Blob Storage Account
permissions := "rwdlacup" // full control
resourceTypes := "sco" // service, container, object
services := "b" // blob
// Details on how to do this are here:
// https://docs.microsoft.com/en-us/rest/api/storageservices/Constructing-an-Account-SAS
signedProtocol := "https,http"
signedIp := ""
signedVersion := sasSignedVersion
signedEncryptionScope := ""
utcNow := time.Now().UTC()
// account for servers being up to 5 minutes out
startDate := utcNow.Add(time.Minute * -5).Format(time.RFC3339)
endDate := utcNow.Add(time.Hour * 24).Format(time.RFC3339)
sasToken, err := sasStorage.ComputeAccountSASToken(accountName, accessKey, permissions, services, resourceTypes,
startDate, endDate, signedProtocol, signedIp, signedVersion, signedEncryptionScope)
if err != nil {
return nil, fmt.Errorf("Error computing SAS Token: %+v", err)
}
log.Printf("SAS Token should be %q", sasToken)
return &sasToken, nil
}
type resourceNames struct {
resourceGroup string
storageAccountName string
storageContainerName string
storageKeyName string
}
func testResourceNames(rString string, keyName string) resourceNames {
return resourceNames{
resourceGroup: fmt.Sprintf("acctestRG-backend-%s-%s", strings.Replace(time.Now().Local().Format("060102150405.00"), ".", "", 1), rString),
storageAccountName: fmt.Sprintf("acctestsa%s", rString),
storageContainerName: "acctestcont",
storageKeyName: keyName,
}
}
type TestMeta struct {
names resourceNames
clientId string
clientSecret string
tenantId string
subscriptionId string
location string
env environments.Environment
// This is populated during test resource deploying
storageAccessKey string
// This is populated during test resoruce deploying
blobBaseUri string
resourceGroupsClient *resourcegroups.ResourceGroupsClient
storageAccountsClient *storageaccounts.StorageAccountsClient
}
func BuildTestMeta(t *testing.T, ctx context.Context) *TestMeta {
names := testResourceNames(randString(10), "testState")
subscriptionID := os.Getenv("ARM_SUBSCRIPTION_ID")
if subscriptionID == "" {
t.Fatalf("Missing ARM_SUBSCRIPTION_ID")
}
tenantID := os.Getenv("ARM_TENANT_ID")
if tenantID == "" {
t.Fatalf("Missing ARM_TENANT_ID")
}
location := os.Getenv("ARM_LOCATION")
if location == "" {
t.Fatalf("Missing ARM_LOCATION")
}
clientID := os.Getenv("ARM_CLIENT_ID")
clientSecret := os.Getenv("ARM_CLIENT_SECRET")
environment := "public"
if v := os.Getenv("ARM_ENVIRONMENT"); v != "" {
environment = v
}
env, err := environments.FromName(environment)
if err != nil {
t.Fatalf("Failed to build environment for %s: %v", environment, err)
}
// For deploying test resources, we support the followings:
// - Client secret: For most of the tests
// - Client certificate: For client certificate related tests
// - MSI: For MSI related tests
// - OIDC: For OIDC related tests
authConfig := &auth.Credentials{
Environment: *env,
TenantID: tenantID,
ClientID: clientID,
ClientSecret: clientSecret,
ClientCertificatePath: os.Getenv("ARM_CLIENT_CERTIFICATE_PATH"),
ClientCertificatePassword: os.Getenv("ARM_CLIENT_CERTIFICATE_PASSWORD"),
OIDCTokenRequestURL: getEnvvars("ACTIONS_ID_TOKEN_REQUEST_URL", "SYSTEM_OIDCREQUESTURI"),
OIDCTokenRequestToken: getEnvvars("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "SYSTEM_ACCESSTOKEN"),
ADOPipelineServiceConnectionID: os.Getenv("ARM_ADO_PIPELINE_SERVICE_CONNECTION_ID"),
EnableAuthenticatingUsingClientSecret: true,
EnableAuthenticatingUsingClientCertificate: true,
EnableAuthenticatingUsingManagedIdentity: true,
EnableAuthenticationUsingGitHubOIDC: true,
EnableAuthenticationUsingADOPipelineOIDC: true,
}
resourceManagerAuth, err := auth.NewAuthorizerFromCredentials(ctx, *authConfig, env.ResourceManager)
if err != nil {
t.Fatalf("unable to build authorizer for Resource Manager API: %+v", err)
}
resourceGroupsClient, err := resourcegroups.NewResourceGroupsClientWithBaseURI(env.ResourceManager)
if err != nil {
t.Fatalf("building Resource Groups client: %+v", err)
}
resourceGroupsClient.Client.SetAuthorizer(resourceManagerAuth)
storageAccountsClient, err := storageaccounts.NewStorageAccountsClientWithBaseURI(env.ResourceManager)
if err != nil {
t.Fatalf("building Storage Accounts client: %+v", err)
}
storageAccountsClient.Client.SetAuthorizer(resourceManagerAuth)
return &TestMeta{
names: names,
clientId: clientID,
clientSecret: clientSecret,
tenantId: tenantID,
subscriptionId: subscriptionID,
location: location,
env: *env,
resourceGroupsClient: resourceGroupsClient,
storageAccountsClient: storageAccountsClient,
}
}
func (c *TestMeta) buildTestResources(ctx context.Context) error {
log.Printf("Creating Resource Group %q", c.names.resourceGroup)
rgid := commonids.NewResourceGroupID(c.subscriptionId, c.names.resourceGroup)
if _, err := c.resourceGroupsClient.CreateOrUpdate(ctx, rgid, resourcegroups.ResourceGroup{Location: c.location}); err != nil {
return fmt.Errorf("failed to create test resource group: %s", err)
}
log.Printf("Creating Storage Account %q in Resource Group %q", c.names.storageAccountName, c.names.resourceGroup)
storageProps := storageaccounts.StorageAccountCreateParameters{
Kind: storageaccounts.KindStorageVTwo,
Sku: storageaccounts.Sku{
Name: storageaccounts.SkuNameStandardLRS,
Tier: pointer.To(storageaccounts.SkuTierStandard),
},
Location: c.location,
}
said := commonids.NewStorageAccountID(c.subscriptionId, c.names.resourceGroup, c.names.storageAccountName)
if err := c.storageAccountsClient.CreateThenPoll(ctx, said, storageProps); err != nil {
return fmt.Errorf("failed to create test storage account: %s", err)
}
// Populate the storage account access key
resp, err := c.storageAccountsClient.GetProperties(ctx, said, storageaccounts.DefaultGetPropertiesOperationOptions())
if err != nil {
return fmt.Errorf("retrieving %s: %+v", said, err)
}
if resp.Model == nil {
return fmt.Errorf("unexpected null model of %s", said)
}
accountDetail, err := populateAccountDetails(said, *resp.Model)
if err != nil {
return fmt.Errorf("populating details for %s: %+v", said, err)
}
accountKey, err := accountDetail.AccountKey(ctx, c.storageAccountsClient)
if err != nil {
return fmt.Errorf("listing access key for %s: %+v", said, err)
}
c.storageAccessKey = *accountKey
blobBaseUri, err := accountDetail.DataPlaneEndpoint(EndpointTypeBlob)
if err != nil {
return err
}
c.blobBaseUri = *blobBaseUri
containersClient, err := containers.NewWithBaseUri(*blobBaseUri)
if err != nil {
return fmt.Errorf("failed to new container client: %v", err)
}
authorizer, err := auth.NewSharedKeyAuthorizer(c.names.storageAccountName, *accountKey, auth.SharedKey)
if err != nil {
return fmt.Errorf("new shared key authorizer: %v", err)
}
containersClient.Client.Authorizer = authorizer
log.Printf("Creating Container %q in Storage Account %q (Resource Group %q)", c.names.storageContainerName, c.names.storageAccountName, c.names.resourceGroup)
if _, err = containersClient.Create(ctx, c.names.storageContainerName, containers.CreateInput{}); err != nil {
return fmt.Errorf("failed to create storage container: %s", err)
}
return nil
}
func (c *TestMeta) destroyTestResources(ctx context.Context) error {
log.Printf("[DEBUG] Deleting Resource Group %q..", c.names.resourceGroup)
rgid := commonids.NewResourceGroupID(c.subscriptionId, c.names.resourceGroup)
if err := c.resourceGroupsClient.DeleteThenPoll(ctx, rgid, resourcegroups.DefaultDeleteOperationOptions()); err != nil {
return fmt.Errorf("Error deleting Resource Group: %+v", err)
}
return nil
}
func (c *TestMeta) getBlobClient(ctx context.Context) (bc *blobs.Client, err error) {
blobsClient, err := blobs.NewWithBaseUri(c.blobBaseUri)
if err != nil {
return nil, fmt.Errorf("new blob client: %v", err)
}
authorizer, err := auth.NewSharedKeyAuthorizer(c.names.storageAccountName, c.storageAccessKey, auth.SharedKey)
if err != nil {
return nil, fmt.Errorf("new shared key authorizer: %v", err)
}
blobsClient.Client.SetAuthorizer(authorizer)
return blobsClient, nil
}
// randString generates a random alphanumeric string of the length specified
func randString(strlen int) string {
const charSet = "abcdefghijklmnopqrstuvwxyz012346789"
result := make([]byte, strlen)
for i := 0; i < strlen; i++ {
result[i] = charSet[rand.Intn(len(charSet))]
}
return string(result)
}
// getEnvvars return the first non-empty env var specified. If none is found, it returns empty string.
func getEnvvars(envvars ...string) string {
for _, envvar := range envvars {
if v := os.Getenv(envvar); v != "" {
return v
}
}
return ""
}