Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions docs/mtlspop_managed_identity.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,30 @@ When attestation is configured:
- The MAA JWT is embedded in the `/issuecredential` request body as `attestation_token`
- The token cache partitions attested vs non-attested tokens (`att=1` vs `att=0`) — they are not interchangeable

## Bounding capability discovery

Credential chains can bound uncached managed identity capability discovery by supplying
`ManagedIdentityCapabilitiesOptions.ImdsProbeTimeout`:

```csharp
var options = new ManagedIdentityCapabilitiesOptions
{
ImdsProbeTimeout = TimeSpan.FromSeconds(2)
};

ManagedIdentityCapabilities capabilities =
await managedIdentityApplication.GetManagedIdentityCapabilitiesAsync(
options,
CancellationToken.None);
```

The timeout is a total discovery budget covering lock contention, IMDSv2 probing and
retries, IMDSv1 fallback, compute metadata retrieval, and binding-strength detection.
Omitting the timeout preserves the existing unlimited behavior. Caller cancellation
continues to surface as cancellation, while expiration of the discovery budget throws
`MsalServiceException` with error code `request_timeout`. A timed-out discovery result
is not cached, so a later call can retry.

---

## Constraints
Expand Down
8 changes: 7 additions & 1 deletion src/client/Microsoft.Identity.Client/Http/HttpManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,13 @@ public async Task<HttpResponse> SendRequestAsync(
timeoutException = exception;
}

while (!_disableInternalRetries && await retryPolicy.PauseForRetryAsync(response, timeoutException, retryCount, logger).ConfigureAwait(false))
while (!_disableInternalRetries &&
await retryPolicy.PauseForRetryAsync(
response,
timeoutException,
retryCount,
logger,
cancellationToken).ConfigureAwait(false))
{
retryCount++;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Core;

Expand Down Expand Up @@ -40,12 +41,17 @@ public DefaultRetryPolicy(RequestType requestType)
}
}

internal virtual Task DelayAsync(int milliseconds)
internal virtual Task DelayAsync(int milliseconds, CancellationToken cancellationToken)
{
return Task.Delay(milliseconds);
return Task.Delay(milliseconds, cancellationToken);
}

public async Task<bool> PauseForRetryAsync(HttpResponse response, Exception exception, int retryCount, ILoggerAdapter logger)
public async Task<bool> PauseForRetryAsync(
HttpResponse response,
Exception exception,
int retryCount,
ILoggerAdapter logger,
CancellationToken cancellationToken)
{
// Check if the status code is retriable and if the current retry count is less than max retries
if (_retryCondition(response, exception) &&
Expand All @@ -63,7 +69,7 @@ public async Task<bool> PauseForRetryAsync(HttpResponse response, Exception exce
logger.Warning($"Retrying request in {retryAfterDelay}ms (retry attempt: {retryCount + 1})");

// Pause execution for the calculated delay
await DelayAsync(retryAfterDelay).ConfigureAwait(false);
await DelayAsync(retryAfterDelay, cancellationToken).ConfigureAwait(false);
Comment thread
Robbie-Microsoft marked this conversation as resolved.
Resolved

return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static bool ImdsProbe(HttpResponse response, Exception exception)
}

// If Imds would retry but the status code is 404, don't retry
return (int)response.StatusCode is not 404;
return response is not null && (int)response.StatusCode is not 404;
}

/// <summary>
Expand Down Expand Up @@ -74,7 +74,7 @@ public static bool RegionDiscovery(HttpResponse response, Exception exception)
}

// If Imds would retry but the status code is 404 or 408, don't retry
return (int)response.StatusCode is not (404 or 408);
return response is not null && (int)response.StatusCode is not (404 or 408);
}

/// <summary>
Expand Down
13 changes: 10 additions & 3 deletions src/client/Microsoft.Identity.Client/Http/Retry/IRetryPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Core;

Expand All @@ -15,11 +16,17 @@ internal interface IRetryPolicy
/// Determines whether a retry should be attempted for a given HTTP response or exception,
/// and performs any necessary pause or delay logic before the next retry attempt.
/// </summary>
/// <param name="response">The HTTP response received from the request.</param>
/// <param name="exception">The exception encountered during the request.</param>
/// <param name="response">The HTTP response received from the request, or null when no response was received.</param>
/// <param name="exception">The exception encountered during the request, or null when a response was received.</param>
/// <param name="retryCount">The current retry attempt count.</param>
/// <param name="logger">The logger used for diagnostic and informational messages.</param>
/// <param name="cancellationToken">The cancellation token to observe while waiting to retry.</param>
/// <returns>A task that returns true if a retry should be performed; otherwise, false.</returns>
Task<bool> PauseForRetryAsync(HttpResponse response, Exception exception, int retryCount, ILoggerAdapter logger);
Task<bool> PauseForRetryAsync(
HttpResponse response,
Exception exception,
int retryCount,
ILoggerAdapter logger,
CancellationToken cancellationToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Core;

Expand All @@ -28,40 +29,56 @@ internal class ImdsRetryPolicy : IRetryPolicy
ImdsRetryPolicy.ExponentialDeltaBackoffMs
);

internal virtual Task DelayAsync(int milliseconds)
internal virtual Task DelayAsync(int milliseconds, CancellationToken cancellationToken)
{
return Task.Delay(milliseconds);
return Task.Delay(milliseconds, cancellationToken);
}

protected virtual bool ShouldRetry(HttpResponse response, Exception exception)
{
return HttpRetryConditions.Imds(response, exception);
}

public async Task<bool> PauseForRetryAsync(HttpResponse response, Exception exception, int retryCount, ILoggerAdapter logger)
public async Task<bool> PauseForRetryAsync(
HttpResponse response,
Exception exception,
int retryCount,
ILoggerAdapter logger,
CancellationToken cancellationToken)
{
int httpStatusCode = (int)response.StatusCode;
if (!ShouldRetry(response, exception))
{
return false;
}

// A transport timeout already consumed the HTTP client's request timeout.
// Preserve the existing single-attempt behavior when no response was received.
if (response is null)
Comment thread
Robbie-Microsoft marked this conversation as resolved.
Resolved
{
return false;
}

bool isGone = response.StatusCode == HttpStatusCode.Gone;

if (retryCount == 0)
{
// Calculate the maxRetries based on the status code, once per request
_maxRetries = httpStatusCode == (int)HttpStatusCode.Gone
_maxRetries = isGone
? LinearStrategyNumRetries
: ExponentialStrategyNumRetries;
}

// Check if the status code is retriable and if the current retry count is less than max retries
if (ShouldRetry(response, exception) &&
retryCount < _maxRetries)
if (retryCount < _maxRetries)
{
int retryAfterDelay = httpStatusCode == (int)HttpStatusCode.Gone
int retryAfterDelay = isGone
? HttpStatusGoneRetryAfterMs
: _exponentialRetryStrategy.CalculateDelay(retryCount);

logger.Warning($"Retrying request in {retryAfterDelay}ms (retry attempt: {retryCount + 1})");

// Pause execution for the calculated delay
await DelayAsync(retryAfterDelay).ConfigureAwait(false);
await DelayAsync(retryAfterDelay, cancellationToken).ConfigureAwait(false);

return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Core;

Expand All @@ -22,12 +23,17 @@ internal class RegionDiscoveryRetryPolicy : IRetryPolicy
ExponentialDeltaBackoffMs
);

internal virtual Task DelayAsync(int milliseconds)
internal virtual Task DelayAsync(int milliseconds, CancellationToken cancellationToken)
{
return Task.Delay(milliseconds);
return Task.Delay(milliseconds, cancellationToken);
}

public async Task<bool> PauseForRetryAsync(HttpResponse response, Exception exception, int retryCount, ILoggerAdapter logger)
public async Task<bool> PauseForRetryAsync(
HttpResponse response,
Exception exception,
int retryCount,
ILoggerAdapter logger,
CancellationToken cancellationToken)
{
// Check if the status code is retriable and if the current retry count is less than max retries
if (HttpRetryConditions.RegionDiscovery(response, exception) &&
Expand All @@ -38,7 +44,7 @@ public async Task<bool> PauseForRetryAsync(HttpResponse response, Exception exce
logger.Warning($"Retrying request in {retryAfterDelay}ms (retry attempt: {retryCount + 1})");

// Pause execution for the calculated delay
await DelayAsync(retryAfterDelay).ConfigureAwait(false);
await DelayAsync(retryAfterDelay, cancellationToken).ConfigureAwait(false);
Comment thread
Robbie-Microsoft marked this conversation as resolved.
Resolved

return true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,12 @@ private static string GetTenant(Uri uri)

private sealed class InstanceDiscoveryRetryPolicy : IRetryPolicy
{
public Task<bool> PauseForRetryAsync(HttpResponse response, Exception exception, int retryCount, ILoggerAdapter logger)
public Task<bool> PauseForRetryAsync(
HttpResponse response,
Exception exception,
int retryCount,
ILoggerAdapter logger,
CancellationToken cancellationToken)
{
return Task.FromResult(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ namespace Microsoft.Identity.Client.ManagedIdentity
/// detected source and the strength with which tokens can be bound to a key.
/// </summary>
/// <remarks>
/// This type is returned by <see cref="ManagedIdentityApplication.GetManagedIdentityCapabilitiesAsync"/>.
/// This type is returned by
/// <see cref="ManagedIdentityApplication.GetManagedIdentityCapabilitiesAsync(System.Threading.CancellationToken)"/>.
/// It is useful for credential chains such as <c>DefaultAzureCredential</c> to decide whether
Comment thread
Robbie-Microsoft marked this conversation as resolved.
Resolved
/// managed identity is available and what binding strength the host supports.
/// </remarks>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;

namespace Microsoft.Identity.Client.ManagedIdentity
{
/// <summary>
/// Configures managed identity capability discovery.
/// </summary>
public sealed class ManagedIdentityCapabilitiesOptions
{
/// <summary>
/// Gets or sets the total time allowed for uncached IMDS capability discovery.
/// </summary>
/// <remarks>
/// The timeout covers discovery lock contention, IMDS probes and retries, fallback,
/// compute metadata retrieval, and binding-strength detection. A <c>null</c> value
/// preserves the default behavior of waiting without a discovery timeout. Cancellation
/// is cooperative, so non-interruptible platform work may finish before the timeout is
/// observed.
/// </remarks>
public TimeSpan? ImdsProbeTimeout { get; set; }
Comment thread
Robbie-Microsoft marked this conversation as resolved.
Resolved
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,11 @@ private Task<AbstractManagedIdentity> GetOrSelectManagedIdentitySourceAsync(
}
}

private static ManagedIdentityDiscoveryResult CacheDiscoveryResult(ManagedIdentityDiscoveryResult result)
private static ManagedIdentityDiscoveryResult CacheDiscoveryResult(
ManagedIdentityDiscoveryResult result,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
s_cachedSourceResult = result;
return result;
}
Expand All @@ -236,11 +239,12 @@ internal async Task<ManagedIdentityDiscoveryResult> GetManagedIdentityCapabiliti
return s_cachedSourceResult;
}

cancellationToken.ThrowIfCancellationRequested();
Comment thread
Robbie-Microsoft marked this conversation as resolved.
Resolved

// Single-flight: ensure only one caller probes IMDS / provisions a binding key at a
// time. Concurrent callers at process startup wait here and then observe the cached
// result instead of issuing redundant probes. Try a non-blocking acquire first so an
// uncontended caller keeps the existing cancellation point (the HTTP probe); only a
// contended caller waits, and that wait is cancelable.
// result instead of issuing redundant probes. Try a non-blocking acquire first to avoid
// an asynchronous wait when uncontended; both paths check cancellation after acquiring.
bool lockTaken = s_discoveryLock.Wait(0);
if (!lockTaken)
{
Expand All @@ -250,6 +254,8 @@ internal async Task<ManagedIdentityDiscoveryResult> GetManagedIdentityCapabiliti

try
{
cancellationToken.ThrowIfCancellationRequested();

// Re-check under the lock in case another caller completed discovery while we waited.
if (s_cachedSourceResult != null)
{
Expand All @@ -261,7 +267,7 @@ internal async Task<ManagedIdentityDiscoveryResult> GetManagedIdentityCapabiliti

if (source != ManagedIdentitySource.None)
{
return CacheDiscoveryResult(new ManagedIdentityDiscoveryResult(source));
return CacheDiscoveryResult(new ManagedIdentityDiscoveryResult(source), cancellationToken);
}

string imdsV1FailureReason = null;
Expand Down Expand Up @@ -299,7 +305,8 @@ internal async Task<ManagedIdentityDiscoveryResult> GetManagedIdentityCapabiliti
return CacheDiscoveryResult(new ManagedIdentityDiscoveryResult(
ManagedIdentitySource.Imds,
ImdsVersion.V2,
v2Strength));
v2Strength),
cancellationToken);
}
imdsV2FailureReason = imdsV2Failure;
}
Expand All @@ -323,15 +330,17 @@ internal async Task<ManagedIdentityDiscoveryResult> GetManagedIdentityCapabiliti
return CacheDiscoveryResult(new ManagedIdentityDiscoveryResult(
ManagedIdentitySource.Imds,
ImdsVersion.V1,
strength));
strength),
cancellationToken);
}
imdsV1FailureReason = imdsV1Failure;

requestContext.Logger.Info($"[Managed Identity] {MsalErrorMessage.ManagedIdentityAllSourcesUnavailable}");
return CacheDiscoveryResult(new ManagedIdentityDiscoveryResult(
ManagedIdentitySource.None,
imdsV1FailureReason: imdsV1FailureReason,
imdsV2FailureReason: imdsV2FailureReason));
imdsV2FailureReason: imdsV2FailureReason),
cancellationToken);
}
finally
{
Expand Down
Loading
Loading