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

[BUG] Azure.Identity.ManagedIdentitySource throws ArgumentNullException #47844

Open
pampua84 opened this issue Jan 15, 2025 · 8 comments · May be fixed by #47866
Open

[BUG] Azure.Identity.ManagedIdentitySource throws ArgumentNullException #47844

pampua84 opened this issue Jan 15, 2025 · 8 comments · May be fixed by #47866
Assignees
Labels
Azure.Identity Client This issue points to a problem in the data-plane of the library. customer-reported Issues that are reported by GitHub users external to the Azure organization. needs-team-attention Workflow: This issue needs attention from Azure service team or SDK team question The issue doesn't require a change to the product in order to be resolved. Most issues start as that

Comments

@pampua84
Copy link

Library name and version

Azure.Identity 1.13.2

Describe the bug

In my application, I'm trying to get a certificate from Azure Key Vault using this simple code:

var client = new CertificateClient(new Uri("uri"), new DefaultAzureCredential());
var response = client.GetCertificate("name");

However, I receive a 401 Unauthorized error without content in the Azure HTTP response, which raises the following exception:

Azure.Identity.AuthenticationFailedException: ManagedIdentityCredential authentication failed: Value cannot be null. (Parameter 'bytes')
See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot
---> System.ArgumentNullException: Value cannot be null. (Parameter 'bytes')
at System.ArgumentNullException.Throw(String paramName)
at System.ArgumentNullException.ThrowIfNull(Void* argument, String paramName)
at System.Text.Encoding.GetString(Byte* bytes, Int32 byteCount)
at System.BinaryData.ToString()
at Azure.Identity.ManagedIdentitySource.HandleResponseAsync(Boolean async, TokenRequestContext context, HttpMessage message, CancellationToken cancellationToken)
at Azure.Identity.ImdsManagedIdentityProbeSource.HandleResponseAsync(Boolean async, TokenRequestContext context, HttpMessage message, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentitySource.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ImdsManagedIdentityProbeSource.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityClient.AuthenticateCoreAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityClient.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)

It seems that the ToString() method is being called on a null Content object inside the library.

Image

Expected behavior

In the case of 401 I expect a speaking message or at least only the value Unauthorized

Actual behavior

Currently the following message is returned:

ManagedIdentityCredential authentication failed: Value cannot be null. (Parameter 'bytes')

Reproduction Steps

Create simple unauthorided client to get certificate from Key Vault

var client = new CertificateClient(new Uri("uri"), new DefaultAzureCredential());
var response = client.GetCertificate("name");

Environment

.NET SDK:
Version: 9.0.101
Commit: eedb237549
Workload version: 9.0.100-manifests.4a280210
MSBuild version: 17.12.12+1cce77968

Runtime Environment:
OS Name: Windows
OS Version: 10.0.22621
OS Platform: Windows
RID: win-x64
Base Path: C:\Program Files\dotnet\sdk\9.0.101\

@pampua84 pampua84 changed the title [BUG] Azure.Identity.ManagedIdentitySource ManagedIdentityCredential throws ArgumentNullException [BUG] Azure.Identity.ManagedIdentitySource throws ArgumentNullException Jan 15, 2025
@github-actions github-actions bot added Azure.Identity Client This issue points to a problem in the data-plane of the library. customer-reported Issues that are reported by GitHub users external to the Azure organization. needs-team-attention Workflow: This issue needs attention from Azure service team or SDK team question The issue doesn't require a change to the product in order to be resolved. Most issues start as that labels Jan 15, 2025
Copy link

Thank you for your feedback. Tagging and routing to the team member best able to assist.

@christothes
Copy link
Member

Hi @pampua84 - Sorry you have hit this issue. Is this occurring locally in your development environment or when deployed?

Would you mind enabling logging to show what the 401 response body looks like as well as the request that generated it?

For console output, you would just need to add the following line to your program.

using AzureEventSourceListener listener = AzureEventSourceListener.CreateTraceLogger(EventLevel.Verbose);

If you need to log the output somewhere other than the console, this can be done as described in these docs.

For example:

using AzureEventSourceListener listener = new AzureEventSourceListener(
    (args, message) => myLogger.Log("[{0:HH:mm:ss:fff}][{1}] {2}", DateTimeOffset.Now, args.Level, message),
    level: EventLevel.Verbose);

@christothes christothes added the needs-author-feedback Workflow: More information is needed from author to address the issue. label Jan 15, 2025
@github-actions github-actions bot removed the needs-team-attention Workflow: This issue needs attention from Azure service team or SDK team label Jan 15, 2025
Copy link

Hi @pampua84. Thank you for opening this issue and giving us the opportunity to assist. To help our team better understand your issue and the details of your scenario please provide a response to the question asked above or the information requested above. This will help us more accurately address your issue.

@pampua84
Copy link
Author

H @christothes i, the issue occurred locally because when using the DefaultAzureCredential, the system tries to use the ManagedIdentity and I get a 401 error.
The problem, however, is due to receiving an unclear exception unless the AzureEventSourceListener is enabled as you specified. Could this be intentional?

@github-actions github-actions bot added needs-team-attention Workflow: This issue needs attention from Azure service team or SDK team and removed needs-author-feedback Workflow: More information is needed from author to address the issue. labels Jan 15, 2025
@christothes
Copy link
Member

Could you provide the logging output from your repro? This will help to ensure we are able to diagnose and fix this issue properly.

@christothes christothes added the needs-author-feedback Workflow: More information is needed from author to address the issue. label Jan 15, 2025
@github-actions github-actions bot removed the needs-team-attention Workflow: This issue needs attention from Azure service team or SDK team label Jan 15, 2025
Copy link

Hi @pampua84. Thank you for opening this issue and giving us the opportunity to assist. To help our team better understand your issue and the details of your scenario please provide a response to the question asked above or the information requested above. This will help us more accurately address your issue.

@pampua84
Copy link
Author

Hi @christothes, here is the logger output as you indicated:

[09:12:22:334][Informational] Request [d71febc5-ee92-4b89-8135-dfc3303bf29f] GET https://tsid-keyvault.vault.azure.net/certificates/SPID?api-version=7.5
Content-Type:application/json
Accept:application/json
x-ms-client-request-id:d71febc5-ee92-4b89-8135-dfc3303bf29f
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Security.KeyVault.Certificates/4.7.0 (.NET 8.0.11; Microsoft Windows 10.0.22621)
client assembly: Azure.Security.KeyVault.Certificates
[09:12:22:714][Warning] Error response [d71febc5-ee92-4b89-8135-dfc3303bf29f] 401 Unauthorized (00.4s)
Cache-Control:no-cache
Pragma:no-cache
x-ms-keyvault-region:italynorth
x-ms-client-request-id:d71febc5-ee92-4b89-8135-dfc3303bf29f
x-ms-request-id:3be77992-da98-457b-a2e3-7bfc98b74dcb
x-ms-keyvault-service-version:1.9.1988.1
x-ms-keyvault-network-info:conn_type=Ipv4;addr=155.190.43.5;act_addr_fam=InterNetwork;
X-Content-Type-Options:REDACTED
Strict-Transport-Security:REDACTED
WWW-Authenticate:Bearer authorization="https://login.microsoftonline.com/bb364f09-07cf-4eca-9b92-1f26a92d5f3f", resource="https://vault.azure.net"
Date:Thu, 16 Jan 2025 08:12:21 GMT
Content-Type:application/json; charset=utf-8
Expires:-1
Content-Length:97

[09:12:22:737][Informational] DefaultAzureCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: d71febc5-ee92-4b89-8135-dfc3303bf29f
[09:12:22:747][Informational] EnvironmentCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: d71febc5-ee92-4b89-8135-dfc3303bf29f
[09:12:22:751][Informational] EnvironmentCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: d71febc5-ee92-4b89-8135-dfc3303bf29f Exception: Azure.Identi
ty.CredentialUnavailableException (0x80131500): EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot
[09:12:22:760][Informational] WorkloadIdentityCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: d71febc5-ee92-4b89-8135-dfc3303bf29f
[09:12:22:761][Informational] WorkloadIdentityCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: d71febc5-ee92-4b89-8135-dfc3303bf29f Exception: Azure.I
dentity.CredentialUnavailableException (0x80131500): WorkloadIdentityCredential authentication unavailable. The workload options are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/workloadidentitycredential/troubleshoot
[09:12:22:764][Informational] ManagedIdentityCredential.GetToken invoked. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: d71febc5-ee92-4b89-8135-dfc3303bf29f
[09:12:22:774][Informational] ManagedIdentitySource TokenExchangeManagedIdentitySource was attempted. IsSelected=False.
[09:12:24:430][Informational] Request [d0ff2cf3-0902-4875-b2c0-bc821c7b572d] GET http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=REDACTED
x-ms-client-request-id:d0ff2cf3-0902-4875-b2c0-bc821c7b572d
x-ms-return-client-request-id:true
User-Agent:azsdk-net-Identity/1.13.2 (.NET 8.0.11; Microsoft Windows 10.0.22621)
client assembly: Azure.Identity
[09:12:24:521][Warning] Error response [d0ff2cf3-0902-4875-b2c0-bc821c7b572d] 403 Forbidden (00.1s)
Date:Thu, 16 Jan 2025 08:12:24 GMT
Connection:keep-alive
Via:REDACTED
Content-Length:0

[09:12:26:531][Informational] ManagedIdentityCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: d71febc5-ee92-4b89-8135-dfc3303bf29f Exception: Azure.Identity.AuthenticationFailedException (0x80131500): ManagedIdentityCredential authentication failed: Value cannot be null. (Parameter 'bytes')
See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot
---> System.ArgumentNullException (0x80004003): Value cannot be null. (Parameter 'bytes')
[09:12:26:568][Informational] DefaultAzureCredential.GetToken was unable to retrieve an access token. Scopes: [ https://vault.azure.net/.default ] ParentRequestId: d71febc5-ee92-4b89-8135-dfc3303bf29f Exception: Azure.Identity.AuthenticationFailedException (0x80131500): ManagedIdentityCredential authentication failed: Value cannot be null. (Parameter 'bytes')
See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot
---> System.ArgumentNullException (0x80004003): Value cannot be null. (Parameter 'bytes')
[09:12:30 ERR] An unhandled exception has occurred while executing the request. s1:Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware 0HN9M0LTTN34E:00000003
Azure.Identity.AuthenticationFailedException: ManagedIdentityCredential authentication failed: Value cannot be null. (Parameter 'bytes')
See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot
---> System.ArgumentNullException: Value cannot be null. (Parameter 'bytes')
at System.ArgumentNullException.Throw(String paramName)
at System.ArgumentNullException.ThrowIfNull(Void* argument, String paramName)
at System.Text.Encoding.GetString(Byte* bytes, Int32 byteCount)
at System.BinaryData.ToString()
at Azure.Identity.ManagedIdentitySource.HandleResponseAsync(Boolean async, TokenRequestContext context, HttpMessage message, CancellationToken cancellationToken)
at Azure.Identity.ImdsManagedIdentityProbeSource.HandleResponseAsync(Boolean async, TokenRequestContext context, HttpMessage message, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentitySource.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ImdsManagedIdentityProbeSource.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityClient.AuthenticateCoreAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityClient.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable)
at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask1 task) at Azure.Identity.ManagedIdentityCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) at Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(TokenCredential[] sources, TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken) at Azure.Identity.DefaultAzureCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken) at Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage, Boolean isCredentialUnavailable) at Azure.Identity.DefaultAzureCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken) at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask1 task)
at Azure.Identity.DefaultAzureCredential.GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken)
at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.SetResultOnTcsFromCredentialAsync(TokenRequestContext context, TaskCompletionSource1 targetTcs, Boolean async, CancellationToken cancellationToken) at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.GetAuthHeaderValueAsync(HttpMessage message, TokenRequestContext context, Boolean async) at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](Task1 task)
at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.TokenRequestState.GetCurrentHeaderValue(Boolean async, Boolean checkForCompletion, CancellationToken cancellationToken)
at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AccessTokenCache.GetAuthHeaderValueAsync(HttpMessage message, TokenRequestContext context, Boolean async)
at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask1 task) at Azure.Core.Pipeline.BearerTokenAuthenticationPolicy.AuthenticateAndAuthorizeRequest(HttpMessage message, TokenRequestContext context) at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.AuthorizeRequestOnChallengeAsyncInternal(HttpMessage message, Boolean async) at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted[T](ValueTask1 task)
at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.AuthorizeRequestOnChallenge(HttpMessage message)
at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.ProcessAsyncInternal(HttpMessage message, ReadOnlyMemory1 pipeline, Boolean async) at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task) at Azure.Security.KeyVault.ChallengeBasedAuthenticationPolicy.Process(HttpMessage message, ReadOnlyMemory1 pipeline)
at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory1 pipeline) at Azure.Core.Pipeline.RedirectPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory1 pipeline, Boolean async)
at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task)
at Azure.Core.Pipeline.RedirectPolicy.Process(HttpMessage message, ReadOnlyMemory1 pipeline) at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory1 pipeline)
at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory1 pipeline, Boolean async) at Azure.Core.Pipeline.RetryPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory1 pipeline, Boolean async)
at Azure.Core.Pipeline.TaskExtensions.EnsureCompleted(ValueTask task)
at Azure.Core.Pipeline.RetryPolicy.Process(HttpMessage message, ReadOnlyMemory1 pipeline) at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory1 pipeline)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory1 pipeline) at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory1 pipeline)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory1 pipeline) at Azure.Core.Pipeline.HttpPipelinePolicy.ProcessNext(HttpMessage message, ReadOnlyMemory1 pipeline)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.Process(HttpMessage message, ReadOnlyMemory1 pipeline) at Azure.Core.Pipeline.HttpPipeline.Send(HttpMessage message, CancellationToken cancellationToken) at Azure.Core.Pipeline.HttpPipeline.SendRequest(Request request, CancellationToken cancellationToken) at Azure.Security.KeyVault.KeyVaultPipeline.SendRequest(Request request, CancellationToken cancellationToken) at Azure.Security.KeyVault.KeyVaultPipeline.SendRequest[TResult](RequestMethod method, Func1 resultFactory, CancellationToken cancellationToken, String[] path)
at Azure.Security.KeyVault.Certificates.CertificateClient.GetCertificate(String certificateName, CancellationToken cancellationToken)
at Helpers.AzureCertificateHelper.FindByName(String name) in Helpers\AzureCertificateHelper.cs:line 28
at Factories.ServiceProviderFactory.GetServiceProvider(IConfiguration configuration) in Factories\ServiceProviderFactory.cs:line 18
at Startup.<>c__DisplayClass4_0.b__18(SpidOptions options) in Startup.cs:line 230
at Microsoft.Extensions.Options.OptionsFactory1.Create(String name) at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy1.CreateValue()
at Microsoft.Extensions.Options.OptionsCache1.GetOrAdd[TArg](String name, Func3 createOptions, TArg factoryArgument)
at Microsoft.Extensions.Options.OptionsMonitor1.Get(String name) at Microsoft.AspNetCore.Authentication.AuthenticationHandler1.InitializeAsync(AuthenticationScheme scheme, HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, String authenticationScheme)e 51
at Middlewares.NotFoundMiddleware.InvokeAsync(HttpContext context) in Middlewares\NotFoundMiddleware.cs:line 14
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddlewareImpl.g__Awaited|10_0(ExceptionHandlerMiddlewareImpl middleware, HttpContext context, Task task)

@github-actions github-actions bot added needs-team-attention Workflow: This issue needs attention from Azure service team or SDK team and removed needs-author-feedback Workflow: More information is needed from author to address the issue. labels Jan 16, 2025
@pampua84
Copy link
Author

The class where i get the error is:

ManagedIdentitySource

at row 92 content = response.Content.ToString();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Azure.Identity Client This issue points to a problem in the data-plane of the library. customer-reported Issues that are reported by GitHub users external to the Azure organization. needs-team-attention Workflow: This issue needs attention from Azure service team or SDK team question The issue doesn't require a change to the product in order to be resolved. Most issues start as that
Projects
Status: Untriaged
2 participants