/
clients_auth.go
429 lines (353 loc) · 15.3 KB
/
clients_auth.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
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
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Contains common helpers for TESTS ONLY
package testcommon
import (
"context"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/internal/recording"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/appendblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/container"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/sas"
"github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/service"
"github.com/stretchr/testify/require"
)
type TestAccountType string
const (
TestAccountDefault TestAccountType = ""
TestAccountSecondary TestAccountType = "SECONDARY_"
TestAccountPremium TestAccountType = "PREMIUM_"
TestAccountSoftDelete TestAccountType = "SOFT_DELETE_"
TestAccountDatalake TestAccountType = "DATALAKE_"
TestAccountImmutable TestAccountType = "IMMUTABLE_"
)
const (
DefaultEndpointSuffix = "core.windows.net/"
DefaultBlobEndpointSuffix = "blob.core.windows.net/"
AccountNameEnvVar = "AZURE_STORAGE_ACCOUNT_NAME"
AccountKeyEnvVar = "AZURE_STORAGE_ACCOUNT_KEY"
DefaultEndpointSuffixEnvVar = "AZURE_STORAGE_ENDPOINT_SUFFIX"
SubscriptionID = "SUBSCRIPTION_ID"
ResourceGroupName = "RESOURCE_GROUP_NAME"
)
const (
FakeStorageAccount = "fakestorage"
FakeStorageURL = "https://fakestorage.blob.core.windows.net"
FakeToken = "faketoken"
)
var (
BlobContentType = "my_type"
BlobContentDisposition = "my_disposition"
BlobCacheControl = "control"
BlobContentLanguage = "my_language"
BlobContentEncoding = "my_encoding"
)
var BasicHeaders = blob.HTTPHeaders{
BlobContentType: &BlobContentType,
BlobContentDisposition: &BlobContentDisposition,
BlobCacheControl: &BlobCacheControl,
BlobContentMD5: nil,
BlobContentLanguage: &BlobContentLanguage,
BlobContentEncoding: &BlobContentEncoding,
}
var BasicMetadata = map[string]*string{"Foo": to.Ptr("bar")}
var BasicBlobTagsMap = map[string]string{
"azure": "blob",
"blob": "sdk",
"sdk": "go",
}
var SpecialCharBlobTagsMap = map[string]string{
"+-./:=_ ": "firsttag",
"tag2": "+-./:=_",
"+-./:=_1": "+-./:=_",
"Microsoft Azure": "Azure Storage",
"Storage+SDK": "SDK/GO",
"GO ": ".Net",
}
func SetClientOptions(t *testing.T, opts *azcore.ClientOptions) {
opts.Logging.AllowedHeaders = append(opts.Logging.AllowedHeaders, "X-Request-Mismatch", "X-Request-Mismatch-Error")
transport, err := recording.NewRecordingHTTPClient(t, nil)
require.NoError(t, err)
opts.Transport = transport
}
func GetClient(t *testing.T, accountType TestAccountType, options *azblob.ClientOptions) (*azblob.Client, error) {
if options == nil {
options = &azblob.ClientOptions{}
}
SetClientOptions(t, &options.ClientOptions)
cred, err := GetGenericSharedKeyCredential(accountType)
if err != nil {
return nil, err
}
client, err := azblob.NewClientWithSharedKeyCredential("https://"+cred.AccountName()+".blob.core.windows.net/", cred, options)
return client, err
}
func GetServiceClient(t *testing.T, accountType TestAccountType, options *service.ClientOptions) (*service.Client, error) {
if options == nil {
options = &service.ClientOptions{}
}
SetClientOptions(t, &options.ClientOptions)
cred, err := GetGenericSharedKeyCredential(accountType)
if err != nil {
return nil, err
}
serviceClient, err := service.NewClientWithSharedKeyCredential("https://"+cred.AccountName()+".blob.core.windows.net/", cred, options)
return serviceClient, err
}
func GetServiceClientNoCredential(t *testing.T, sasUrl string, options *service.ClientOptions) (*service.Client, error) {
if options == nil {
options = &service.ClientOptions{}
}
SetClientOptions(t, &options.ClientOptions)
serviceClient, err := service.NewClientWithNoCredential(sasUrl, options)
return serviceClient, err
}
type FakeCredential struct {
}
func (c *FakeCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (azcore.AccessToken, error) {
return azcore.AccessToken{Token: FakeToken, ExpiresOn: time.Now().Add(time.Hour).UTC()}, nil
}
func GetGenericTokenCredential() (azcore.TokenCredential, error) {
if recording.GetRecordMode() == recording.PlaybackMode {
return &FakeCredential{}, nil
}
return azidentity.NewDefaultAzureCredential(nil)
}
func GetGenericAccountInfo(accountType TestAccountType) (string, string) {
if recording.GetRecordMode() == recording.PlaybackMode {
return FakeStorageAccount, "ZmFrZQ=="
}
accountNameEnvVar := string(accountType) + AccountNameEnvVar
accountKeyEnvVar := string(accountType) + AccountKeyEnvVar
accountName, _ := GetRequiredEnv(accountNameEnvVar)
accountKey, _ := GetRequiredEnv(accountKeyEnvVar)
return accountName, accountKey
}
func GetGenericSharedKeyCredential(accountType TestAccountType) (*azblob.SharedKeyCredential, error) {
accountName, accountKey := GetGenericAccountInfo(accountType)
if accountName == "" || accountKey == "" {
return nil, errors.New(string(accountType) + AccountNameEnvVar + " and/or " + string(accountType) + AccountKeyEnvVar + " environment variables not specified.")
}
return azblob.NewSharedKeyCredential(accountName, accountKey)
}
func GetGenericConnectionString(accountType TestAccountType) (*string, error) {
accountName, accountKey := GetGenericAccountInfo(accountType)
if accountName == "" || accountKey == "" {
return nil, errors.New(string(accountType) + AccountNameEnvVar + " and/or " + string(accountType) + AccountKeyEnvVar + " environment variables not specified.")
}
connectionString := fmt.Sprintf("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=core.windows.net/",
accountName, accountKey)
return &connectionString, nil
}
func GetServiceClientFromConnectionString(t *testing.T, accountType TestAccountType, options *service.ClientOptions) (*service.Client, error) {
if options == nil {
options = &service.ClientOptions{}
}
SetClientOptions(t, &options.ClientOptions)
transport, err := recording.NewRecordingHTTPClient(t, nil)
require.NoError(t, err)
options.Transport = transport
cred, err := GetGenericConnectionString(accountType)
if err != nil {
return nil, err
}
svcClient, err := service.NewClientFromConnectionString(*cred, options)
return svcClient, err
}
func GetContainerClient(containerName string, s *service.Client) *container.Client {
return s.NewContainerClient(containerName)
}
func CreateNewContainer(ctx context.Context, _require *require.Assertions, containerName string, serviceClient *service.Client) *container.Client {
containerClient := GetContainerClient(containerName, serviceClient)
_, err := containerClient.Create(ctx, nil)
_require.NoError(err)
return containerClient
}
func DeleteContainer(ctx context.Context, _require *require.Assertions, containerClient *container.Client) {
_, err := containerClient.Delete(ctx, nil)
_require.NoError(err)
}
func GetBlobClient(blockBlobName string, containerClient *container.Client) *blob.Client {
return containerClient.NewBlobClient(blockBlobName)
}
func CreateNewBlobs(ctx context.Context, _require *require.Assertions, blobNames []string, containerClient *container.Client) {
for _, blobName := range blobNames {
CreateNewBlockBlob(ctx, _require, blobName, containerClient)
}
}
func CreateNewBlobsListTier(ctx context.Context, _require *require.Assertions, blobNames []string, containerClient *container.Client, tier *blob.AccessTier) {
for _, blobName := range blobNames {
bbClient := CreateNewBlockBlob(ctx, _require, blobName, containerClient)
_, err := bbClient.SetTier(ctx, *tier, nil)
_require.NoError(err)
}
}
func GetBlockBlobClient(blockBlobName string, containerClient *container.Client) *blockblob.Client {
return containerClient.NewBlockBlobClient(blockBlobName)
}
func CreateNewBlockBlob(ctx context.Context, _require *require.Assertions, blockBlobName string, containerClient *container.Client) *blockblob.Client {
bbClient := GetBlockBlobClient(blockBlobName, containerClient)
_, err := bbClient.Upload(ctx, streaming.NopCloser(strings.NewReader(BlockBlobDefaultData)), nil)
_require.NoError(err)
return bbClient
}
func CreateNewBlockBlobWithCPK(ctx context.Context, _require *require.Assertions, blockBlobName string, containerClient *container.Client, cpkInfo *blob.CPKInfo, cpkScopeInfo *blob.CPKScopeInfo) (bbClient *blockblob.Client) {
bbClient = GetBlockBlobClient(blockBlobName, containerClient)
uploadBlockBlobOptions := blockblob.UploadOptions{
CPKInfo: cpkInfo,
CPKScopeInfo: cpkScopeInfo,
}
cResp, err := bbClient.Upload(ctx, streaming.NopCloser(strings.NewReader(BlockBlobDefaultData)), &uploadBlockBlobOptions)
_require.NoError(err)
// _require.Equal(cResp.RawResponse.StatusCode, 201)
_require.Equal(*cResp.IsServerEncrypted, true)
if cpkInfo != nil {
_require.EqualValues(cResp.EncryptionKeySHA256, cpkInfo.EncryptionKeySHA256)
}
if cpkScopeInfo != nil {
_require.EqualValues(cResp.EncryptionScope, cpkScopeInfo.EncryptionScope)
}
return
}
func GetAppendBlobClient(appendBlobName string, containerClient *container.Client) *appendblob.Client {
return containerClient.NewAppendBlobClient(appendBlobName)
}
func CreateNewAppendBlob(ctx context.Context, _require *require.Assertions, appendBlobName string, containerClient *container.Client) *appendblob.Client {
abClient := GetAppendBlobClient(appendBlobName, containerClient)
_, err := abClient.Create(ctx, nil)
_require.NoError(err)
return abClient
}
// Some tests require setting service properties. It can take up to 30 seconds for the new properties to be reflected across all FEs.
// We will enable the necessary property and try to run the test implementation. If it fails with an error that should be due to
// those changes not being reflected yet, we will wait 30 seconds and try the test again. If it fails this time for any reason,
// we fail the test. It is the responsibility of the testImplFunc to determine which error string indicates the test should be retried.
// There can only be one such string. All errors that cannot be due to this detail should be asserted and not returned as an error string.
func RunTestRequiringServiceProperties(ctx context.Context, _require *require.Assertions, svcClient *service.Client, code string,
enableServicePropertyFunc func(context.Context, *require.Assertions, *service.Client),
testImplFunc func(context.Context, *require.Assertions, *service.Client) error,
disableServicePropertyFunc func(context.Context, *require.Assertions, *service.Client)) {
enableServicePropertyFunc(ctx, _require, svcClient)
defer disableServicePropertyFunc(ctx, _require, svcClient)
err := testImplFunc(ctx, _require, svcClient)
// We cannot assume that the error indicative of slow update will necessarily be a StorageError. As in ListBlobs.
if err != nil && err.Error() == code {
time.Sleep(time.Second * 30)
err = testImplFunc(ctx, _require, svcClient)
_require.NoError(err)
}
}
func EnableSoftDelete(ctx context.Context, _require *require.Assertions, client *service.Client) {
days := int32(1)
_, err := client.SetProperties(ctx, &service.SetPropertiesOptions{
DeleteRetentionPolicy: &service.RetentionPolicy{Enabled: to.Ptr(true), Days: &days}})
_require.NoError(err)
}
func DisableSoftDelete(ctx context.Context, _require *require.Assertions, client *service.Client) {
_, err := client.SetProperties(ctx, &service.SetPropertiesOptions{DeleteRetentionPolicy: &service.RetentionPolicy{Enabled: to.Ptr(false)}})
_require.NoError(err)
}
func ListBlobsCount(ctx context.Context, _require *require.Assertions, listPager *runtime.Pager[container.ListBlobsFlatResponse], ctr int) {
found := make([]*container.BlobItem, 0)
for listPager.More() {
resp, err := listPager.NextPage(ctx)
_require.NoError(err)
if err != nil {
break
}
found = append(found, resp.Segment.BlobItems...)
}
_require.Len(found, ctr)
}
func GetServiceSAS(containerName string, permissions sas.BlobPermissions) (string, error) {
credential, err := GetGenericSharedKeyCredential(TestAccountDefault)
if err != nil {
return "", err
}
sasQueryParams, err := sas.BlobSignatureValues{
Protocol: sas.ProtocolHTTPS,
StartTime: time.Now().UTC(),
ExpiryTime: time.Now().UTC().Add(2 * time.Hour),
Permissions: permissions.String(),
ContainerName: containerName,
}.SignWithSharedKey(credential)
if err != nil {
return "", err
}
return sasQueryParams.Encode(), nil
}
func GetUserDelegationSAS(svcClient *service.Client, containerName string, permissions sas.BlobPermissions) (string, error) {
// Set current and past time and create key
now := time.Now().UTC().Add(-10 * time.Second)
expiry := now.Add(2 * time.Hour)
info := service.KeyInfo{
Start: to.Ptr(now.UTC().Format(sas.TimeFormat)),
Expiry: to.Ptr(expiry.UTC().Format(sas.TimeFormat)),
}
udc, err := svcClient.GetUserDelegationCredential(context.Background(), info, nil)
if err != nil {
return "", err
}
// Create Blob Signature Values with desired permissions and sign with user delegation credential
sasQueryParams, err := sas.BlobSignatureValues{
Protocol: sas.ProtocolHTTPS,
StartTime: time.Now().UTC().Add(time.Second * -10),
ExpiryTime: time.Now().UTC().Add(15 * time.Minute),
Permissions: permissions.String(),
ContainerName: containerName,
}.SignWithUserDelegation(udc)
if err != nil {
return "", err
}
return sasQueryParams.Encode(), nil
}
func GetAccountSAS(permissions sas.AccountPermissions, resourceTypes sas.AccountResourceTypes) (string, error) {
credential, err := GetGenericSharedKeyCredential(TestAccountDefault)
if err != nil {
return "", err
}
sasQueryParams, err := sas.AccountSignatureValues{
Protocol: sas.ProtocolHTTPS,
StartTime: time.Now().UTC(),
ExpiryTime: time.Now().UTC().Add(1 * time.Hour),
Permissions: permissions.String(),
ResourceTypes: resourceTypes.String(),
}.SignWithSharedKey(credential)
if err != nil {
return "", err
}
return sasQueryParams.Encode(), nil
}
func DeleteContainerUsingManagementClient(_require *require.Assertions, accountType TestAccountType, containerName string) {
if recording.GetRecordMode() == recording.PlaybackMode {
return
}
accountName, err := GetRequiredEnv(string(accountType) + AccountNameEnvVar)
_require.NoError(err)
subscriptionID, err := GetRequiredEnv(SubscriptionID)
_require.NoError(err)
resourceGroupName, err := GetRequiredEnv(ResourceGroupName)
_require.NoError(err)
cred, err := azidentity.NewDefaultAzureCredential(nil)
_require.NoError(err)
managementClient, err := armstorage.NewBlobContainersClient(subscriptionID, cred, nil)
_require.NoError(err)
_, err = managementClient.Delete(context.Background(), resourceGroupName, accountName, containerName, nil)
_require.NoError(err)
}