Skip to content

Commit

Permalink
Prevent ManagedIdentityCredential mutating GetToken arguments (#15331)
Browse files Browse the repository at this point in the history
  • Loading branch information
chlowell committed Aug 20, 2021
1 parent dc2d9f4 commit cf0793e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
1 change: 1 addition & 0 deletions sdk/azidentity/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
### Breaking Changes

### Bugs Fixed
* `ManagedIdentityCredential.GetToken` no longer mutates its `opts.Scopes`

### Other Changes

Expand Down
6 changes: 3 additions & 3 deletions sdk/azidentity/managed_identity_credential.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,9 @@ func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts azcore.To
addGetTokenFailureLogs("Managed Identity Credential", err, true)
return nil, err
}
// The following code will remove the /.default suffix from any scopes passed into the method since ManagedIdentityCredentials expect a resource string instead of a scope string
opts.Scopes[0] = strings.TrimSuffix(opts.Scopes[0], defaultSuffix)
tk, err := c.client.authenticate(ctx, c.id, opts.Scopes)
// 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("Managed Identity Credential", err, true)
return nil, err
Expand Down
25 changes: 25 additions & 0 deletions sdk/azidentity/managed_identity_credential_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,31 @@ func TestManagedIdentityCredential_GetTokenNilResource(t *testing.T) {
}
}

func TestManagedIdentityCredential_ScopesImmutable(t *testing.T) {
resetEnvironmentVarsForTest()
srv, close := mock.NewServer()
defer close()
srv.AppendResponse(mock.WithBody([]byte(expiresOnIntResp)))
_ = os.Setenv(msiEndpoint, srv.URL())
defer clearEnvVars(msiEndpoint)
options := ManagedIdentityCredentialOptions{
HTTPClient: srv,
}
cred, err := NewManagedIdentityCredential("", &options)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
scope := "https://localhost/.default"
scopes := []string{scope}
_, err = cred.GetToken(context.Background(), azcore.TokenRequestOptions{Scopes: scopes})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if scopes[0] != scope {
t.Fatalf("GetToken shouldn't mutate arguments")
}
}

func TestManagedIdentityCredential_GetTokenMultipleResources(t *testing.T) {
resetEnvironmentVarsForTest()
srv, close := mock.NewServer()
Expand Down

0 comments on commit cf0793e

Please sign in to comment.