Azure auth: do not use CLI provider by default when running in a cloud service (#3338)

Signed-off-by: ItalyPaleAle <43508+ItalyPaleAle@users.noreply.github.com>
This commit is contained in:
Alessandro (Ale) Segala 2024-02-06 16:01:50 -08:00 committed by GitHub
parent 43d905db6b
commit 9acfcc16b8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 22 additions and 21 deletions

View File

@ -143,27 +143,8 @@ func (s EnvironmentSettings) addManagedIdentityProvider(timeout time.Duration, c
c := s.GetMSI()
msiCred, err := c.GetTokenCredential()
useTimeout := true
if _, ok := os.LookupEnv(identityEndpoint); ok {
// App Service, Functions, Service Fabric and Container Apps
useTimeout = false
} else {
if _, ok := os.LookupEnv(arcIMDSEndpoint); ok {
// Azure Arc
useTimeout = false
} else {
if _, ok := os.LookupEnv(msiEndpoint); ok {
// Cloud Shell
useTimeout = false
} else if isVirtualMachineWithManagedIdentity() {
// Azure VM with MSI enabled
useTimeout = false
}
}
}
// We need to use a timeout for MSI on environments where it is not available because the request for the default IMDS endpoint can hang for several minutes.
if useTimeout {
if !(isCloudServiceWithManagedIdentity() || isVirtualMachineWithManagedIdentity()) {
msiCred = &timeoutWrapper{cred: msiCred, authmethod: "managed identity", timeout: timeout}
}
@ -235,7 +216,10 @@ func (s EnvironmentSettings) GetTokenCredential() (azcore.TokenCredential, error
s.addManagedIdentityProvider(1*time.Second, &creds, &errs)
// 5. AzureCLICredential
s.addCLIProvider(30*time.Second, &creds, &errs)
// We omit this if running in a cloud environment
if !isCloudServiceWithManagedIdentity() {
s.addCLIProvider(30*time.Second, &creds, &errs)
}
} else {
authMethodIdentifiers := getAzureAuthMethods()
authMethods := strings.Split(strings.ToLower(strings.TrimSpace(authMethods)), ",")
@ -499,6 +483,23 @@ func (s EnvironmentSettings) GetEnvironment(key string) (val string, ok bool) {
return metadata.GetMetadataProperty(s.Metadata, MetadataKeys[key]...)
}
// Returns true if the application is running on a cloud service with Managed Identity, including: Azure App Service, Azure Functions, Azure Service Fabric, Azure Container Apps, Azure Arc, Azure Cloud Shell.
func isCloudServiceWithManagedIdentity() bool {
switch {
case os.Getenv(identityEndpoint) != "":
// Azure App Service, Azure Functions, Azure Service Fabric and Azure Container Apps
return true
case os.Getenv(arcIMDSEndpoint) != "":
// Azure Arc
return true
case os.Getenv(msiEndpoint) != "":
// Azure Cloud Shell
return true
default:
return false
}
}
// isVirtualMachineWithManagedIdentity returns true if the code is running on a virtual machine with managed identity enabled.
// This is indicated by the standard IMDS endpoint being reachable.
func isVirtualMachineWithManagedIdentity() bool {