Skip to content

Dynamically refresh Entra tokens in publishing HTTP clients - #17566

Merged
mmitche merged 3 commits into
dotnet:mainfrom
mmitche:mmitche-miniature-parakeet
Sep 16, 2026
Merged

mmitche merged 3 commits into
dotnet:mainfrom
mmitche:mmitche-miniature-parakeet

Conversation

@mmitche

@mmitche mmitche commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Summary of Changes

In long-running publishing jobs (such as Maestro Build Promotion downloading hundreds of assets across multiple manifests), \PublishArtifactsInManifestBase\ and \AzureDevOpsNugetFeedAssetPublisher\ previously acquired an Entra ID bearer token once during \HttpClient\ initialization. Because Entra access tokens have a lifetime of 30-60 minutes, downloads and feed queries occurring after token expiration failed with \401 Unauthorized. Retries within the task could not recover because the client's \DefaultRequestHeaders.Authorization\ was static.

Key Changes

  1. **\TokenCredentialAuthenticationHandler**: Added a delegating \HttpMessageHandler\ in \Microsoft.DotNet.ArcadeAzureIntegration\ that dynamically attaches a Bearer token via \TokenCredential.GetTokenAsync\ / \GetToken\ on every outgoing request that doesn't already have one. It doesn't cache tokens itself; it relies on the wrapped \TokenCredential\ (e.g. \DefaultIdentityTokenCredential's \TokenCredentialShortCache\ wrapping, or \ManagedIdentityCredential's own cache) to make that cheap and to refresh only when actually needed.
  2. **\PublishArtifactsInManifestBase.CreateAzdoClient**: Configured the Azure DevOps \HttpClient\ with \TokenCredentialAuthenticationHandler\ when authenticating via Entra ID credentials.
  3. **\AzureDevOpsNugetFeedAssetPublisher**: Configured feed query \HttpClient\ with \TokenCredentialAuthenticationHandler.
  4. Unit Tests: Added test coverage in \Microsoft.DotNet.Build.Tasks.Feed.Tests\ verifying dynamic per-request token generation and preservation of existing credentials.

Long-running publishing jobs (e.g. Maestro Build Promotion downloading hundreds of assets) previously acquired an Entra ID token once during HttpClient creation. Because Entra access tokens expire after ~30-60 minutes, subsequent asset downloads and feed queries would fail with 401 Unauthorized errors and retries could not recover.

- Implement TokenCredentialAuthenticationHandler to dynamically acquire and refresh Bearer tokens per HTTP request using TokenCredential
- Update PublishArtifactsInManifestBase and AzureDevOpsNugetFeedAssetPublisher to use the delegating handler
- Improve retry and error logging in asset download and manifest helper methods to surface root-cause inner exceptions
- Add unit tests for TokenCredentialAuthenticationHandler

Co-authored-by: Copilot App <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Preserve the captured retry exception as the failure’s inner exception.

Pull request overview

Updates publishing clients to refresh Entra bearer tokens per request, preventing failures in long-running jobs.

Changes:

  • Adds and integrates TokenCredentialAuthenticationHandler.
  • Enhances retry diagnostics.
  • Adds authentication handler tests and source-only build configuration.
File summaries
File Summary
src/Microsoft.DotNet.Build.Tasks.Feed/src/PublishArtifactsInManifestBase.cs Dynamic authentication and retry diagnostics
src/Microsoft.DotNet.Build.Tasks.Feed/src/AzureDevOpsNugetFeedAssetPublisher.cs Dynamic feed authentication
src/Microsoft.DotNet.Build.Tasks.Feed.Tests/TokenCredentialAuthenticationHandlerTests.cs Token handler behavior tests
src/Microsoft.DotNet.ArcadeAzureIntegration/TokenCredentialAuthenticationHandler.cs Per-request bearer-token attachment
src/Microsoft.DotNet.ArcadeAzureIntegration/Microsoft.DotNet.ArcadeAzureIntegration.csproj Source-only build exclusion
Review details

Suppressed comments (2)

src/Microsoft.DotNet.Build.Tasks.Feed/src/PublishArtifactsInManifestBase.cs:1176

  • mostRecentlyCaughtException is only set by the filtered exception handler above. If the callback returns false because the artifact is missing or its container data is invalid, this new message still appends Last error: with an empty value (or can report an earlier attempt's exception rather than the final failure). Either track those non-exception failures or omit the suffix unless an exception was captured.
            Log.LogError($"Failed to construct download URL helper for '{artifactName}' after {RetryHandler.MaxAttempts} attempts. Last error: {mostRecentlyCaughtException?.Message}");

src/Microsoft.DotNet.Build.Tasks.Feed/src/PublishArtifactsInManifestBase.cs:1179

  • The new diagnostics log the last exception, but this failure is still thrown without mostRecentlyCaughtException as the inner exception; it is only interpolated into the message. Callers therefore cannot inspect the original HttpRequestException, and the “See inner exception” text is inaccurate. Pass the saved exception as the second constructor argument, as DownloadFileAsync does above.
            Log.LogError($"Failed to construct download URL helper for '{artifactName}' after {RetryHandler.MaxAttempts} attempts. Last error: {mostRecentlyCaughtException?.Message}");
            if (mostRecentlyCaughtException != null)
            {
                Log.LogErrorFromException(mostRecentlyCaughtException, showStackTrace: false);
  • Files reviewed: 5/5 changed files
  • Comments generated: 0
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Copilot AI review requested due to automatic review settings September 15, 2026 20:04

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Preserve mostRecentlyCaughtException as the wrapper’s InnerException in PublishArtifactsInManifestBase.cs.

Review details

Suppressed comments (1)

Previously missed (1) — in code that hasn't changed since the last review.

src/Microsoft.DotNet.Build.Tasks.Feed/src/PublishArtifactsInManifestBase.cs:1182

  • Although the new logging prints the last exception, the wrapper thrown below still does not pass mostRecentlyCaughtException as its InnerException; it only interpolates the exception into the message. This makes the existing “See inner exception” guidance false and prevents callers from inspecting the root failure programmatically. Preserve the exception as the inner exception, as DownloadFileAsync does.
  • Files reviewed: 5/5 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

Revert the extra Log.LogMessage/Log.LogError/LogErrorFromException calls in DownloadFileAsync and CreateArtifactUrlHelper. This PR is scoped to the dynamic token refresh fix only.

Co-authored-by: Copilot App <[email protected]>
Copilot AI review requested due to automatic review settings September 15, 2026 21:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Authentication and build-integration changes warrant final human review.

Review details
  • Files reviewed: 5/5 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@mmitche
mmitche marked this pull request as ready for review September 15, 2026 21:58
if (request.Headers.Authorization == null)
{
var tokenRequestContext = new TokenRequestContext(_scopes);
var token = await _credential.GetTokenAsync(tokenRequestContext, cancellationToken).ConfigureAwait(false);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Depending on the type of backing TokenCredential , this can shell procs and be slow on windows. Can we cache tokens on scopes and only request one if it's soon to expire?

@mmitche
mmitche merged commit 6d42f78 into dotnet:main Sep 16, 2026
12 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Sep 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants