1 // Copyright (C) The Azure-Samples Authors. All rights reserved.
3 // SPDX-License-Identifier: MIT
5 // Largely borrowed from
6 // https://github.com/Azure-Samples/azure-sdk-for-go-samples/blob/master/internal/iam/authorizers.go
14 "github.com/arvados/arvados-dev/compute-image-cleaner/config"
16 "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2017-06-01/storage"
18 "github.com/Azure/go-autorest/autorest"
19 "github.com/Azure/go-autorest/autorest/adal"
20 "github.com/Azure/go-autorest/autorest/azure/auth"
23 // OAuthGrantType specifies which grant type to use.
24 type OAuthGrantType int
27 // OAuthGrantTypeServicePrincipal for client credentials flow
28 OAuthGrantTypeServicePrincipal OAuthGrantType = iota
29 // OAuthGrantTypeDeviceFlow for device flow
30 OAuthGrantTypeDeviceFlow
34 armAuthorizer autorest.Authorizer
37 // GrantType returns what grant type has been configured.
38 func grantType() OAuthGrantType {
39 if config.UseDeviceFlow() {
40 return OAuthGrantTypeDeviceFlow
42 return OAuthGrantTypeServicePrincipal
45 func getAuthorizerForResource(grantType OAuthGrantType, resource string) (autorest.Authorizer, error) {
46 var a autorest.Authorizer
51 case OAuthGrantTypeServicePrincipal:
52 oauthConfig, err := adal.NewOAuthConfig(
53 config.Environment().ActiveDirectoryEndpoint, config.TenantID())
58 token, err := adal.NewServicePrincipalToken(
59 *oauthConfig, config.ClientID(), config.ClientSecret(), resource)
63 a = autorest.NewBearerAuthorizer(token)
65 case OAuthGrantTypeDeviceFlow:
66 deviceconfig := auth.NewDeviceFlowConfig(config.ClientID(), config.TenantID())
67 deviceconfig.Resource = resource
68 a, err = deviceconfig.Authorizer()
74 return a, fmt.Errorf("invalid grant type specified")
80 // GetResourceManagementAuthorizer gets an OAuthTokenAuthorizer for Azure Resource Manager
81 func GetResourceManagementAuthorizer() (autorest.Authorizer, error) {
82 if armAuthorizer != nil {
83 return armAuthorizer, nil
86 var a autorest.Authorizer
89 a, err = getAuthorizerForResource(
90 grantType(), config.Environment().ResourceManagerEndpoint)
99 return armAuthorizer, err
102 func getStorageAccountsClient() storage.AccountsClient {
103 storageAccountsClient := storage.NewAccountsClient(config.SubscriptionID())
104 auth, err := GetResourceManagementAuthorizer()
108 storageAccountsClient.Authorizer = auth
109 err = storageAccountsClient.AddToUserAgent("compute-image-cleaner")
113 return storageAccountsClient