From 7ca18ac911218af0841e3e411836d46209900abd Mon Sep 17 00:00:00 2001 From: Scott Murray Date: Sat, 23 Apr 2022 10:28:36 +1200 Subject: [PATCH] only check availability for IMDS --- autorest/adal/token.go | 13 +++++++++++++ autorest/adal/token_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/autorest/adal/token.go b/autorest/adal/token.go index 310be07ec..14554324a 100644 --- a/autorest/adal/token.go +++ b/autorest/adal/token.go @@ -1317,12 +1317,25 @@ func NewMultiTenantServicePrincipalTokenFromCertificate(multiTenantCfg MultiTena // MSIAvailable returns true if the MSI endpoint is available for authentication. func MSIAvailable(ctx context.Context, s Sender) bool { + msiType, _, err := getMSIType() + + if err != nil { + return false + } + + if msiType != msiTypeIMDS { + return true + } + if s == nil { s = sender() } + resp, err := getMSIEndpoint(ctx, s) + if err == nil { resp.Body.Close() } + return err == nil } diff --git a/autorest/adal/token_test.go b/autorest/adal/token_test.go index 891706afc..4f34929d9 100644 --- a/autorest/adal/token_test.go +++ b/autorest/adal/token_test.go @@ -1343,6 +1343,32 @@ func TestMSIAvailableSuccess(t *testing.T) { } } +func TestMSIAvailableAppService(t *testing.T) { + os.Setenv("MSI_ENDPOINT", "http://localhost") + os.Setenv("MSI_SECRET", "super") + defer func() { + os.Unsetenv("MSI_ENDPOINT") + os.Unsetenv("MSI_SECRET") + }() + c := mocks.NewSender() + c.AppendResponse(mocks.NewResponse()) + available := MSIAvailable(context.Background(), c) + + if !available { + t.Fatal("expected MSI to be available") + } +} + +func TestMSIAvailableIMDS(t *testing.T) { + c := mocks.NewSender() + c.AppendResponse(mocks.NewResponse()) + available := MSIAvailable(context.Background(), c) + + if !available { + t.Fatal("expected MSI to be available") + } +} + func TestMSIAvailableSlow(t *testing.T) { c := mocks.NewSender() // introduce a long response delay to simulate the endpoint not being available