Skip to content
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: 2 additions & 0 deletions sdk/identity/Azure.Identity/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@

### Bugs Fixed

- ManagedIdentityCredential will no longer attempt to parse invalid json payloads on responses from the managed identity endpoint.

### Other Changes

## 1.10.0-beta.1 (2023-07-17)
Expand Down
17 changes: 12 additions & 5 deletions sdk/identity/Azure.Identity/src/ManagedIdentitySource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,19 @@ internal static async Task<string> GetMessageFromResponse(Response response, boo
{
return null;
}
response.ContentStream.Position = 0;
using JsonDocument json = async
? await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false)
: JsonDocument.Parse(response.ContentStream);
try
{
response.ContentStream.Position = 0;
using JsonDocument json = async
? await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false)
: JsonDocument.Parse(response.ContentStream);

return GetMessageFromResponse(json.RootElement);
return GetMessageFromResponse(json.RootElement);
}
catch // parsing failed
{
return "Response was not in a valid json format.";
}
}

protected static string GetMessageFromResponse(in JsonElement root)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,24 @@ public void VerifyImdsRequestFailurePopulatesExceptionMessage()
Assert.That(ex.Message, Does.Contain(expectedMessage));
}

[NonParallelizable]
[Test]
public void VerifyImdsRequestFailureWithInvalidJsonPopulatesExceptionMessage()
{
using var environment = new TestEnvVar(new() { { "MSI_ENDPOINT", null }, { "MSI_SECRET", null }, { "IDENTITY_ENDPOINT", null }, { "IDENTITY_HEADER", null }, { "AZURE_POD_IDENTITY_AUTHORITY_HOST", null } });

var expectedMessage = "Response was not in a valid json format.";
var response = CreateInvalidJsonResponse(502);
var mockTransport = new MockTransport(response);
var options = new TokenCredentialOptions() { Transport = mockTransport };
var pipeline = CredentialPipeline.GetInstance(options);

ManagedIdentityCredential credential = InstrumentClient(new ManagedIdentityCredential("mock-client-id", pipeline));

var ex = Assert.ThrowsAsync<CredentialUnavailableException>(async () => await credential.GetTokenAsync(new TokenRequestContext(MockScopes.Default)));
Assert.That(ex.Message, Does.Contain(expectedMessage));
}

[NonParallelizable]
[Test]
[TestCase(400, ImdsManagedIdentitySource.IdentityUnavailableError)]
Expand Down