Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revise azidentity logging #17039

Merged
merged 3 commits into from
Feb 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions sdk/azidentity/authorization_code_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ func (c *AuthorizationCodeCredential) GetToken(ctx context.Context, opts policy.
}
ar, err = c.cca.AcquireTokenByAuthCode(ctx, c.authCode, c.redirectURI, opts.Scopes)
if err != nil {
addGetTokenFailureLogs(credNameAuthCode, err, true)
return nil, newAuthenticationFailedErrorFromMSALError(credNameAuthCode, err)
}
logGetTokenSuccess(c, opts)
Expand All @@ -107,7 +106,6 @@ func (c *AuthorizationCodeCredential) GetToken(ctx context.Context, opts policy.
}
ar, err = c.pca.AcquireTokenByAuthCode(ctx, c.authCode, c.redirectURI, opts.Scopes)
if err != nil {
addGetTokenFailureLogs(credNameAuthCode, err, true)
return nil, newAuthenticationFailedErrorFromMSALError(credNameAuthCode, err)
}
logGetTokenSuccess(c, opts)
Expand Down
1 change: 0 additions & 1 deletion sdk/azidentity/azure_cli_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ func (c *AzureCLICredential) GetToken(ctx context.Context, opts policy.TokenRequ
scope := strings.TrimSuffix(opts.Scopes[0], defaultSuffix)
at, err := c.authenticate(ctx, scope)
if err != nil {
addGetTokenFailureLogs(credNameAzureCLI, err, true)
return nil, err
}
logGetTokenSuccess(c, opts)
Expand Down
6 changes: 2 additions & 4 deletions sdk/azidentity/chained_token_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts policy.Token
for _, cred := range c.sources {
token, err := cred.GetToken(ctx, opts)
if err == nil {
log.Writef(EventAuthentication, "Azure Identity => %s authenticated with %s", c.name, extractCredentialName(cred))
log.Writef(EventAuthentication, "%s authenticated with %s", c.name, extractCredentialName(cred))
c.successfulCredential = cred
return token, nil
}
Expand All @@ -78,9 +78,7 @@ func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts policy.Token
}
// if we get here, all credentials returned credentialUnavailableError
msg := createChainedErrorMessage(errs)
err := newCredentialUnavailableError(c.name, msg)
log.Write(EventAuthentication, "Azure Identity => ERROR: "+err.Error())
return nil, err
return nil, newCredentialUnavailableError(c.name, msg)
}

func createChainedErrorMessage(errs []error) string {
Expand Down
2 changes: 0 additions & 2 deletions sdk/azidentity/client_certificate_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ func NewClientCertificateCredential(tenantID string, clientID string, certs []*x
}
authorityHost, err := setAuthorityHost(options.AuthorityHost)
if err != nil {
logCredentialError(credNameCert, err)
return nil, err
}
cert, err := newCertContents(certs, pk, options.SendCertificateChain)
Expand Down Expand Up @@ -100,7 +99,6 @@ func (c *ClientCertificateCredential) GetToken(ctx context.Context, opts policy.

ar, err = c.client.AcquireTokenByCredential(ctx, opts.Scopes)
if err != nil {
addGetTokenFailureLogs(credNameCert, err, true)
return nil, newAuthenticationFailedErrorFromMSALError(credNameCert, err)
}
logGetTokenSuccess(c, opts)
Expand Down
1 change: 0 additions & 1 deletion sdk/azidentity/client_secret_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ func (c *ClientSecretCredential) GetToken(ctx context.Context, opts policy.Token

ar, err = c.client.AcquireTokenByCredential(ctx, opts.Scopes)
if err != nil {
addGetTokenFailureLogs(credNameSecret, err, true)
return nil, newAuthenticationFailedErrorFromMSALError(credNameSecret, err)
}
logGetTokenSuccess(c, opts)
Expand Down
6 changes: 2 additions & 4 deletions sdk/azidentity/default_azure_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,11 @@ func defaultAzureCredentialConstructorErrorHandler(numberOfSuccessfulCredentials
errorMessage := strings.Join(errorMessages, "\n\t")

if numberOfSuccessfulCredentials == 0 {
err := errors.New(errorMessage)
log.Writef(EventAuthentication, "Azure Identity => Failed to initialize the Default Azure Credential:\n\t%s", err.Error())
return err
return errors.New(errorMessage)
}

if len(errorMessages) != 0 {
log.Writef(EventAuthentication, "Azure Identity => Failed to initialize some credentials on the Default Azure Credential:\n\t%s", errorMessage)
log.Writef(EventAuthentication, "NewDefaultAzureCredential failed to initialize some credentials:\n\t%s", errorMessage)
}

return nil
Expand Down
41 changes: 8 additions & 33 deletions sdk/azidentity/default_azure_credential_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ package azidentity

import (
"context"
"os"
"testing"

"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
Expand All @@ -27,22 +26,13 @@ func TestDefaultAzureCredential_GetTokenSuccess(t *testing.T) {
}
}

func TestDefaultAzureCredential_defaultAzureCredentialConstructorErrorHandlerNoSuccessfulCredential(t *testing.T) {
err := os.Setenv("AZURE_SDK_GO_LOGGING", "all")
if err != nil {
t.Fatal("Unexpected error", err.Error())
}

logMessages := []string{}
log.SetListener(func(event log.Event, message string) {
logMessages = append(logMessages, message)
})

func TestDefaultAzureCredential_ConstructorErrorHandler(t *testing.T) {
setEnvironmentVariables(t, map[string]string{"AZURE_SDK_GO_LOGGING": "all"})
errorMessages := []string{
"<credential-name>: <error-message>",
"<credential-name>: <error-message>",
}
err = defaultAzureCredentialConstructorErrorHandler(0, errorMessages)
err := defaultAzureCredentialConstructorErrorHandler(0, errorMessages)
if err == nil {
t.Fatalf("Expected an error, but received none.")
}
Expand All @@ -52,37 +42,22 @@ func TestDefaultAzureCredential_defaultAzureCredentialConstructorErrorHandlerNoS
t.Fatalf("Did not create an appropriate error message.\n\nReceived:\n%s\n\nExpected:\n%s", err.Error(), expectedError)
}

expectedLogs := `Azure Identity => Failed to initialize the Default Azure Credential:
<credential-name>: <error-message>
<credential-name>: <error-message>`
if logMessages[0] != expectedLogs {
t.Fatalf("Did not receive the expected logs.\n\nReceived:\n%s\n\nExpected:\n%s", logMessages[0], expectedLogs)
}
}

func TestDefaultAzureCredential_defaultAzureCredentialConstructorErrorHandlerOneSuccessfulCredential(t *testing.T) {
err := os.Setenv("AZURE_SDK_GO_LOGGING", "all")
if err != nil {
t.Fatal("Unexpected error", err.Error())
}

logMessages := []string{}
log.SetListener(func(event log.Event, message string) {
logMessages = append(logMessages, message)
})

errorMessages := []string{
"<credential-name>: <error-message>",
"<credential-name>: <error-message>",
}
err = defaultAzureCredentialConstructorErrorHandler(1, errorMessages)
if err != nil {
t.Fatal("Unexpected error", err.Error())
t.Fatal(err)
}

expectedLogs := `Azure Identity => Failed to initialize some credentials on the Default Azure Credential:
expectedLogs := `NewDefaultAzureCredential failed to initialize some credentials:
chlowell marked this conversation as resolved.
Show resolved Hide resolved
<credential-name>: <error-message>
<credential-name>: <error-message>`
if len(logMessages) == 0 {
t.Fatal("error handler logged no messages")
}
if logMessages[0] != expectedLogs {
t.Fatalf("Did not receive the expected logs.\n\nReceived:\n%s\n\nExpected:\n%s", logMessages[0], expectedLogs)
}
Expand Down
2 changes: 0 additions & 2 deletions sdk/azidentity/device_code_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts policy.TokenRe
}
dc, err := c.client.AcquireTokenByDeviceCode(ctx, opts.Scopes)
if err != nil {
addGetTokenFailureLogs(credNameDeviceCode, err, true)
return nil, newAuthenticationFailedErrorFromMSALError(credNameDeviceCode, err)
}
err = c.userPrompt(ctx, DeviceCodeMessage{
Expand All @@ -121,7 +120,6 @@ func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts policy.TokenRe
}
ar, err = dc.AuthenticationResult(ctx)
if err != nil {
addGetTokenFailureLogs(credNameDeviceCode, err, true)
return nil, newAuthenticationFailedErrorFromMSALError(credNameDeviceCode, err)
}
c.account = ar.Account
Expand Down
6 changes: 3 additions & 3 deletions sdk/azidentity/environment_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*Environme
return nil, errors.New("missing environment variable AZURE_CLIENT_ID")
}
if clientSecret := os.Getenv("AZURE_CLIENT_SECRET"); clientSecret != "" {
log.Write(EventAuthentication, "Azure Identity => EnvironmentCredential will authenticate with ClientSecretCredential")
log.Write(EventAuthentication, "EnvironmentCredential will authenticate with ClientSecretCredential")
o := &ClientSecretCredentialOptions{AuthorityHost: options.AuthorityHost, ClientOptions: options.ClientOptions}
cred, err := NewClientSecretCredential(tenantID, clientID, clientSecret, o)
if err != nil {
Expand All @@ -74,7 +74,7 @@ func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*Environme
return &EnvironmentCredential{cred: cred}, nil
}
if certPath := os.Getenv("AZURE_CLIENT_CERTIFICATE_PATH"); certPath != "" {
log.Write(EventAuthentication, "Azure Identity => EnvironmentCredential will authenticate with ClientCertificateCredential")
log.Write(EventAuthentication, "EnvironmentCredential will authenticate with ClientCertificateCredential")
certData, err := os.ReadFile(certPath)
if err != nil {
return nil, fmt.Errorf(`failed to read certificate file "%s": %v`, certPath, err)
Expand All @@ -95,7 +95,7 @@ func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*Environme
}
if username := os.Getenv("AZURE_USERNAME"); username != "" {
if password := os.Getenv("AZURE_PASSWORD"); password != "" {
log.Write(EventAuthentication, "Azure Identity => EnvironmentCredential will authenticate with UsernamePasswordCredential")
log.Write(EventAuthentication, "EnvironmentCredential will authenticate with UsernamePasswordCredential")
o := &UsernamePasswordCredentialOptions{AuthorityHost: options.AuthorityHost, ClientOptions: options.ClientOptions}
cred, err := NewUsernamePasswordCredential(tenantID, clientID, username, password, o)
if err != nil {
Expand Down
1 change: 0 additions & 1 deletion sdk/azidentity/interactive_browser_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@ func (c *InteractiveBrowserCredential) GetToken(ctx context.Context, opts policy
}
ar, err = c.client.AcquireTokenInteractive(ctx, opts.Scopes, o...)
if err != nil {
addGetTokenFailureLogs(credNameBrowser, err, true)
return nil, newAuthenticationFailedErrorFromMSALError(credNameBrowser, err)
}
c.account = ar.Account
Expand Down
21 changes: 2 additions & 19 deletions sdk/azidentity/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (

"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/internal/diag"
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
)

Expand All @@ -22,23 +21,7 @@ func logGetTokenSuccess(cred azcore.TokenCredential, opts policy.TokenRequestOpt
if !log.Should(EventAuthentication) {
return
}
msg := fmt.Sprintf("Azure Identity => GetToken() result for %T: SUCCESS\n", cred)
msg += fmt.Sprintf("\tCredential Scopes: [%s]", strings.Join(opts.Scopes, ", "))
scope := strings.Join(opts.Scopes, ", ")
msg := fmt.Sprintf("%s.GetToken() acquired a token for scope %s\n", cred, scope)
log.Write(EventAuthentication, msg)
}

func logCredentialError(credName string, err error) {
log.Writef(EventAuthentication, "Azure Identity => ERROR in %s: %s", credName, err.Error())
}

func addGetTokenFailureLogs(credName string, err error, includeStack bool) {
if !log.Should(EventAuthentication) {
return
}
stack := ""
if includeStack {
// skip the stack trace frames and ourself
stack = "\n" + diag.StackTrace(3, 32)
}
log.Writef(EventAuthentication, "Azure Identity => ERROR in GetToken() call for %s: %s%s", credName, err.Error(), stack)
}
2 changes: 1 addition & 1 deletion sdk/azidentity/managed_identity_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) (*manag
c.pipeline = runtime.NewPipeline(component, version, runtime.PipelineOptions{}, &cp)

if log.Should(EventAuthentication) {
log.Writef(EventAuthentication, "Azure Identity => Managed Identity Credential will use %s managed identity", env)
log.Writef(EventAuthentication, "Managed Identity Credential will use %s managed identity", env)
}

return &c, nil
Expand Down
3 changes: 0 additions & 3 deletions sdk/azidentity/managed_identity_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*M
}
client, err := newManagedIdentityClient(options)
if err != nil {
logCredentialError(credNameManagedIdentity, err)
return nil, err
}
return &ManagedIdentityCredential{id: options.ID, client: client}, nil
Expand All @@ -91,14 +90,12 @@ func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*M
func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) {
if len(opts.Scopes) != 1 {
err := errors.New(credNameManagedIdentity + ": GetToken() requires exactly one scope")
addGetTokenFailureLogs(credNameManagedIdentity, err, true)
return nil, err
}
// managed identity endpoints require an AADv1 resource (i.e. token audience), not a v2 scope, so we remove "/.default" here
scopes := []string{strings.TrimSuffix(opts.Scopes[0], defaultSuffix)}
tk, err := c.client.authenticate(ctx, c.id, scopes)
if err != nil {
addGetTokenFailureLogs(credNameManagedIdentity, err, true)
return nil, err
}
logGetTokenSuccess(c, opts)
Expand Down
1 change: 0 additions & 1 deletion sdk/azidentity/username_password_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ func (c *UsernamePasswordCredential) GetToken(ctx context.Context, opts policy.T
}
ar, err = c.client.AcquireTokenByUsernamePassword(ctx, opts.Scopes, c.username, c.password)
if err != nil {
addGetTokenFailureLogs(credNameUserPassword, err, true)
return nil, newAuthenticationFailedErrorFromMSALError(credNameUserPassword, err)
}
c.account = ar.Account
Expand Down