Skip to content

Commit 6e69b23

Browse files
authored
Include response body in IMDS 400 error message (#21351)
1 parent 4b91f97 commit 6e69b23

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

sdk/azidentity/managed_identity_client.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,11 @@ func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKi
179179
if id != nil {
180180
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "the requested identity isn't assigned to this resource", resp, nil)
181181
}
182-
return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, "no default identity is assigned to this resource")
182+
msg := "failed to authenticate a system assigned identity"
183+
if body, err := runtime.Payload(resp); err == nil && len(body) > 0 {
184+
msg += fmt.Sprintf(". The endpoint responded with %s", body)
185+
}
186+
return azcore.AccessToken{}, newCredentialUnavailableError(credNameManagedIdentity, msg)
183187
}
184188

185189
return azcore.AccessToken{}, newAuthenticationFailedError(credNameManagedIdentity, "authentication failed", resp, nil)

sdk/azidentity/managed_identity_client_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
1717
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
1818
"github.com/Azure/azure-sdk-for-go/sdk/internal/log"
19+
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
1920
)
2021

2122
type userAgentValidatingPolicy struct {
@@ -75,6 +76,26 @@ func TestManagedIdentityClient_ApplicationID(t *testing.T) {
7576
}
7677
}
7778

79+
func TestManagedIdentityClient_IMDS400(t *testing.T) {
80+
srv, close := mock.NewServer(mock.WithTransformAllRequestsToTestServerUrl())
81+
defer close()
82+
body := `{"error":"invalid_request","error_description":"Identity not found"}`
83+
srv.SetResponse(mock.WithBody([]byte(body)), mock.WithStatusCode(http.StatusBadRequest))
84+
client, err := newManagedIdentityClient(&ManagedIdentityCredentialOptions{
85+
ClientOptions: azcore.ClientOptions{Transport: srv},
86+
})
87+
if err != nil {
88+
t.Fatal(err)
89+
}
90+
_, err = client.authenticate(context.Background(), nil, testTRO.Scopes)
91+
if err == nil {
92+
t.Fatal("expected an error")
93+
}
94+
if actual := err.Error(); !strings.Contains(actual, body) {
95+
t.Fatalf("expected response body in error, got %q", actual)
96+
}
97+
}
98+
7899
func TestManagedIdentityClient_UserAssignedIDWarning(t *testing.T) {
79100
for _, test := range []struct {
80101
name string

0 commit comments

Comments
 (0)