From f5fdc3a62ce33663a884d84a4b9e9c0ba24ae5a8 Mon Sep 17 00:00:00 2001 From: Matthew Barnes Date: Mon, 25 Apr 2022 09:06:31 -0400 Subject: [PATCH] EXPERIMENTAL pkg/env/msiauthorizer.go --- pkg/env/msiauthorizer.go | 48 ++++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/pkg/env/msiauthorizer.go b/pkg/env/msiauthorizer.go index c21bdf7bc09..1432028a269 100644 --- a/pkg/env/msiauthorizer.go +++ b/pkg/env/msiauthorizer.go @@ -7,8 +7,10 @@ import ( "fmt" "os" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure/auth" + "github.com/jongio/azidext/go/azidext" ) type MSIContext string @@ -19,27 +21,35 @@ const ( ) func (c *core) NewMSIAuthorizer(msiContext MSIContext, resource string) (autorest.Authorizer, error) { - if !c.IsLocalDevelopmentMode() { - return auth.NewAuthorizerFromEnvironmentWithResource(resource) - } + var tokenCredential azcore.TokenCredential + var err error - for _, key := range []string{ - "AZURE_" + string(msiContext) + "_CLIENT_ID", - "AZURE_" + string(msiContext) + "_CLIENT_SECRET", - "AZURE_TENANT_ID", - } { - if _, found := os.LookupEnv(key); !found { - return nil, fmt.Errorf("environment variable %q unset (development mode)", key) + if !c.IsLocalDevelopmentMode() { + tokenCredential, err = azidentity.NewManagedIdentityCredential( + &azidentity.ManagedIdentityCredentialOptions{}) + } else { + for _, key := range []string{ + "AZURE_" + string(msiContext) + "_CLIENT_ID", + "AZURE_" + string(msiContext) + "_CLIENT_SECRET", + "AZURE_TENANT_ID", + } { + if _, found := os.LookupEnv(key); !found { + return nil, fmt.Errorf("environment variable %q unset (development mode)", key) + } } - } - config := &auth.ClientCredentialsConfig{ - ClientID: os.Getenv("AZURE_" + string(msiContext) + "_CLIENT_ID"), - ClientSecret: os.Getenv("AZURE_" + string(msiContext) + "_CLIENT_SECRET"), - TenantID: os.Getenv("AZURE_TENANT_ID"), - Resource: resource, - AADEndpoint: c.Environment().ActiveDirectoryEndpoint, + tokenCredential, err = azidentity.NewClientSecretCredential( + os.Getenv("AZURE_TENANT_ID"), + os.Getenv("AZURE_"+string(msiContext)+"_CLIENT_ID"), + os.Getenv("AZURE_"+string(msiContext)+"_CLIENT_SECRET"), + &azidentity.ClientSecretCredentialOptions{ + AuthorityHost: c.Environment().AuthorityHost, + }) + } + if err != nil { + return nil, err } - return config.Authorizer() + scopes := []string{resource + "/.default"} + return azidext.NewTokenCredentialAdapter(tokenCredential, scopes), nil }