Skip to content

Fix IMDSv2 SCHANNEL failures bypassing certificate re-mint retry - #6173

Merged
Robbie-Microsoft merged 7 commits into
mainfrom
robbie-microsoft-automatic-train
Sep 3, 2026
Merged

Robbie-Microsoft merged 7 commits into
mainfrom
robbie-microsoft-automatic-train

Conversation

@Robbie-Microsoft

@Robbie-Microsoft Robbie-Microsoft commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #6172

What broke

#6070 (3680c2fe2) moved the IMDSv2 mTLS-PoP token leg to the shared TokenClient β†’ OAuth2Client β†’ HttpManager path. The retry logic survived that move β€” it was re-implemented in ManagedIdentityAuthRequest. What did not survive was AbstractManagedIdentity.HandleException, which normalized raw transport failures into MsalServiceException(ManagedIdentityUnreachableNetwork).

That method manufactured both halves of the catch filter the retry depends on β€” the exception type and the error code. Once it left the path, the filter could never match:

Exception reaching the filter
Before #6070 MsalServiceException β†’ HttpRequestException β†’ AuthenticationException β€” matched
After #6070 HttpRequestException β†’ AuthenticationException β†’ Win32Exception β€” type mismatch

Net effect: a KeyGuard/CNG-bound cert Schannel can no longer use (SEC_E_UNKNOWN_CREDENTIALS, 0x8009030D) surfaced as a bare HttpRequestException instead of triggering the re-mint-and-retry that exists precisely for it. No packet leaves the machine β€” this is not a transient network condition, it's a stale binding cert that only a re-mint fixes.

Unintended exception-contract change, not a behavior change anyone signed off on.

Fix

DelegateImdsV2TokenLegAsync β€” restore normalization. Wrap tokenClient.SendTokenRequestAsync and re-normalize failures MSAL doesn't already own into MsalServiceException, mirroring HandleException. Scoped to the token call only β€” the mint step already throws MSAL-shaped exceptions, so wrapping it would double-wrap. The error-code mapping mirrors HandleException: HttpRequestException β†’ managed_identity_unreachable_network, FormatException β†’ invalid_managed_identity_endpoint (reachable because the token endpoint is built from binding.Endpoint, an IMDS-supplied value), everything else β†’ managed_identity_request_failed. Guard is ex is not MsalException, stricter than the old MsalServiceException check, so MsalClientException is preserved rather than masked. OperationCanceledException passes through untouched.

ShouldRemintImdsV2Binding β€” defense in depth. Widen the catch from catch (MsalServiceException ex) to catch (Exception ex) when (...). Being explicit: this layer is not required to fix the bug β€” the normalization change alone makes every new test pass, and I isolated the layers to confirm that. It's here because the original filter only worked by accident of a wrapper three call-frames away. That coupling is what let this regress silently. Cancellation is explicitly excluded.

IsSchanelFailure β†’ IsSchannelFailure(Exception). Typo fix, parameter generalized from MsalServiceException. internal static β€” no public API surface change, no PublicAPI.Unshipped.txt entry. Detection logic byte-for-byte unchanged: it still keys on AuthenticationException broadly, which also catches server-cert validation failures. That over-trigger is bounded (one wasted re-mint, then the real error propagates) and narrowing it to SEC_E_UNKNOWN_CREDENTIALS / SEC_E_NO_CREDENTIALS is a semantic change I'm keeping out of a regression fix. Happy to pull it forward if a reviewer wants it here.

Compatibility

The regression shipped in 4.85.2 through 4.88.0. On those versions this failure surfaces as a raw HttpRequestException; after this fix it surfaces as MsalServiceException again, with the original exception preserved as InnerException. That restores the documented managed identity contract, but anyone who added a catch (HttpRequestException) workaround on 4.85.2+ will find it no longer fires and should revert it. No public API added, removed, or annotated.

Tests

Eight end-to-end regression tests in ImdsV2Tests.cs. Attempt counts are asserted via MockHttpManager.QueueSize, so "retries exactly once" is proven rather than inferred from a successful return.

Test Covers
mTLSPop_TokenLeg_RawSchannelFailure_... Re-mint + retry on a raw Schannel failure
mTLSPop_TokenLeg_RepeatedSchannelFailure_... Retries once, then propagates
mTLSPop_TokenLeg_UnrelatedNetworkFailure_... Unrelated failures neither retried nor swallowed
mTLSPop_TokenLeg_NonHttpFailure_... Non-HttpRequestException normalized onto managed_identity_request_failed
mTLSPop_TokenLeg_FormatFailure_... FormatException keeps invalid_managed_identity_endpoint, not the generic code
BearerOverMtls_TokenLeg_SchannelFailure_... Same behavior for WithRequestOverMtls as for PoP
mTLSPop_Unattested_TokenLeg_SchannelFailure_... Same behavior without WithAttestationSupport
mTLSPop_TokenLeg_Cancellation_... Cancellation still propagates un-wrapped, consumes no re-mint

WithRequestOverMtls had zero coverage in Test.Unit before this.

Three detector tests in PersistentCertificateStoreUnitTests.cs. These also drop a reflection-based lookup of the old method name β€” the rename would have broken it, and reflection-coupled tests are how a rename becomes a silent hole.

Reverted the fix in place and re-ran. All six Schannel/normalization tests fail against the pre-fix behavior with exactly the reported symptom (Actual exception type:<System.Net.Http.HttpRequestException>) and pass against the new. mTLSPop_TokenLeg_FormatFailure_... was likewise verified to fail against the pre-fix error-code mapping. The cancellation test passes both before and after by design β€” it guards the fix against over-reaching, it does not reproduce the bug. Calling that out rather than claiming eight regression tests.

Full ManagedIdentity suite on both target frameworks β€” net8.0 and net48 each report 462 passed, 1 skipped, 0 failed. Clean build under TreatWarningsAsErrors.

Acceptance criteria (#6172)

All five criteria are verbatim from the issue. Unit evidence is from ImdsV2Tests.cs; E2E evidence is from CI run 20260901.8 on the MI-enabled Azure VM pool (20/20 passed), which exercises real IMDSv2 with Credential Guard.

# Criterion Status Evidence
1 Raw Schannel HttpRequestException failures trigger one certificate re-mint and retry Met mTLSPop_TokenLeg_RawSchannelFailure_... (re-mints + retries) and ..._RepeatedSchannelFailure_... (retries once, then propagates). Attempt counts asserted via QueueSize; both fail against pre-fix code
2 Retry behavior is identical for mTLS PoP and bearer-over-mTLS Met BearerOverMtls_TokenLeg_SchannelFailure_... mirrors the PoP test β€” both paths share SendDelegatedImdsV2TokenRequestAsync. E2E: AcquireToken_OnImdsV2_WithRequestOverMtls_ReturnsBearer passed for SAMI + UAMI
3 Both attested and unattested IMDSv2 E2E tests pass Met Attested: AcquireToken_OnImdsV2_MtlsPoP_WithAttestation_Succeeds (SAMI + UAMI-ClientId) and AcquireTokenAndCallAKV_.... Unattested: AcquireToken_OnImdsV2_MtlsPoP_GracefulDegradation_WhenCredentialGuardUnavailable
4 Microsoft.Identity.Web MI FIC two-leg mTLS PoP tests pass Met by equivalent coverage ManagedIdentityImdsV2FicTests.FicTwoLeg_MtlsPop_SAMI / _UAMI-ClientId passed E2E (plus both FicTwoLeg_Bearer_*). This is the same code path Identity.Web's ManagedIdentityClientAssertion drives. Identity.Web's own suite was not run against this branch β€” its test is [OnlyOnAzureDevopsFact]; static review found no risk (below)
5 Cancellation and unrelated network failures are not retried Met mTLSPop_TokenLeg_Cancellation_... (propagates un-wrapped, consumes no re-mint) and ..._UnrelatedNetworkFailure_... (neither retried nor swallowed). Both assert QueueSize

Being precise on #4: MSAL's own FIC two-leg mTLS PoP E2E tests pass against live Azure MI, which covers the underlying behavior. Executing Identity.Web's suite against an unreleased MSAL build is the one gap, and it's called out rather than papered over.

Downstream: Microsoft.Identity.Web

Checked against a local microsoft-identity-web checkout. No risk found:

  • MsiFic_TwoLeg_FinalMtlsPop_SystemAssignedManagedIdentityAsync exists (tests/E2E Tests/TokenAcquirerTests/ManagedIdentityFicTests.cs). It is [OnlyOnAzureDevopsFact] and needs live Azure MI + Credential Guard, so it can only be validated in their CI.
  • Identity.Web pins MSAL 4.88.0 (Directory.Build.props) β€” inside the affected range.
  • Its managed identity path catches Exception, logs, and rethrows unfiltered; it does not discriminate on exception type. ManagedIdentityClientAssertion already documents that bind failures "surface as an MsalServiceException from ExecuteAsync", which is the contract this PR restores.
  • Its certificate-retry filter keys on invalid_client + specific AADSTS codes, so managed_identity_* error codes cannot trigger a spurious retry.
  • The HttpRequestException filters in DownstreamApi.HttpMethods.cs are on downstream API calls, not token acquisition.
<!-- BEGIN pr-telemetry -->
assistance: agentic-cli
type: bug
agent-tool: copilot-cli
agent-model: claude-opus-5
work-item: AB#n/a
<!-- END pr-telemetry -->

PR #6070 moved the IMDSv2 mTLS-PoP token leg to the shared TokenClient
path. The retry logic survived that move, but AbstractManagedIdentity.
HandleException did not - and that method manufactured both halves of
the catch filter the retry depends on (the exception type and the error
code). A local SCHANNEL handshake failure therefore surfaced as a raw
HttpRequestException instead of triggering the binding re-mint.

Restore the normalization in DelegateImdsV2TokenLegAsync so callers keep
receiving MsalServiceException, and widen the re-mint filter so it no
longer depends on a distant wrapper for its type match. Cancellation is
never retried and exceptions MSAL already owns pass through untouched.

Also renames IsSchanelFailure to IsSchannelFailure and generalizes its
parameter to Exception; detection logic is unchanged. Both members are
internal, so there is no public API change.

Fixes #6172

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings September 1, 2026 19:14
@Robbie-Microsoft
Robbie-Microsoft requested a review from a team as a code owner September 1, 2026 19:14
@Robbie-Microsoft Robbie-Microsoft added agentic-cli Terminal AI agent drove the bulk of the edits bug labels Sep 1, 2026

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.

Pull request overview

This PR fixes a regression in IMDSv2 mTLS-PoP token acquisition where SCHANNEL/transport failures in the delegated TokenClient path were no longer normalized into MSAL exceptions, causing the existing β€œre-mint binding cert and retry once” recovery logic to never trigger.

Changes:

  • Restores transport-failure normalization in the delegated IMDSv2 token-leg call so callers see MsalServiceException (with original exception preserved as InnerException).
  • Hardens the re-mint-and-retry filter to handle both MSAL-shaped and raw transport exception chains (while excluding cancellation).
  • Adds regression/unit tests covering raw SCHANNEL transport chains, bounded single retry behavior, and non-SCHANNEL failure classification.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/PersistentCertificateStoreUnitTests.cs Updates SCHANNEL detector tests to call the internal helper directly (no reflection) and adds coverage for raw transport exception chains.
tests/Microsoft.Identity.Test.Unit/ManagedIdentityTests/ImdsV2Tests.cs Adds end-to-end regression tests proving re-mint+retry behavior for raw SCHANNEL failures and ensuring unrelated failures are not retried and are normalized.
src/client/Microsoft.Identity.Client/ManagedIdentity/V2/ImdsV2ManagedIdentitySource.cs Renames/generalizes SCHANNEL detection helper to accept any Exception chain, supporting both wrapped and raw transport failures.
src/client/Microsoft.Identity.Client/Internal/Requests/ManagedIdentityAuthRequest.cs Wraps unowned delegated token-leg exceptions into managed identity MsalServiceException and broadens the retry filter to operate on any exception chain.

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

Adds the three unit tests needed to close the acceptance criteria the
first commit left unproven:

- BearerOverMtls_TokenLeg_SchannelFailure_ReMintsBindingAndRetriesOnce
  proves the re-mint path is identical for bearer-over-mTLS
  (WithRequestOverMtls) as for mTLS PoP. WithRequestOverMtls had no
  coverage in Test.Unit before this.
- mTLSPop_Unattested_TokenLeg_SchannelFailure_ReMintsBindingAndRetriesOnce
  proves the path is attestation-independent (KeyGuard key, no
  WithAttestationSupport).
- mTLSPop_TokenLeg_Cancellation_IsNotRetriedAndIsNotWrapped guards the
  new transport normalization: OperationCanceledException must still
  propagate un-wrapped and must not consume a re-mint.

Both Schannel tests were verified to fail against the pre-fix behavior.
The cancellation test passes both before and after by design; it is a
guard against the fix over-reaching, not a regression test.

No product code changes.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings September 1, 2026 19:30

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.

🟑 Changes recommended

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details

Suppressed comments (1)

src/client/Microsoft.Identity.Client/Internal/Requests/ManagedIdentityAuthRequest.cs:285

  • The comment says SCHANNEL-shaped failures from the mint step are "recoverable by re-minting", but the mint flow (/getplatformmetadata + /issuecredential) does not present the binding certificate in a client mTLS handshake. A SCHANNEL/AuthenticationException during mint is more likely a generic TLS/transport issue, so the rationale here is misleading. Consider rewording to reflect that this is a bounded retry rather than a cert-specific recovery.
        // Failures from the mint step itself are intentionally in scope: minting talks to the IMDS endpoint over
        // TLS, so a handshake failure there is just as recoverable by re-minting. The retry is bounded to a
        // single additional attempt either way. Cancellation is never retried.
  • Files reviewed: 4/4 changed files
  • Comments generated: 1
  • Review effort level: Lite

The cancellation regression test injected a bare OperationCanceledException
without ever canceling the caller's token. HttpManager only rethrows a
cancellation when the token is genuinely canceled; otherwise it classifies it
as a timeout and converts it into MsalServiceException(request_timeout).

Whether a bare OperationCanceledException reaches that catch as a
TaskCanceledException depends on async state-machine behavior, which differs
between net8.0 and net48. The test therefore passed on net8.0 and failed on
net48 with MsalServiceException instead of OperationCanceledException.

Cancel the caller's token from the token-leg mock's request-validation hook
instead. The mock validates the request, then calls ThrowIfCancellationRequested,
so the token leg is provably reached and cancellation is raised with the token
genuinely canceled. Both the "rethrown by HttpManager" and "never caught by
HttpManager" paths then propagate cancellation, so the assertion holds on both
target frameworks.

Also switches to the assignability-based assertion pattern already used by
MtlsPop_AttestationProviderCancelled_PropagatesCancellation, since the runtime
may surface cancellation as the derived TaskCanceledException.

Verified: net48 (vstest.console) ImdsV2Tests 117/117 pass; net8.0
ManagedIdentity suite 461 passed / 1 skipped / 0 failed.

No product code change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings September 1, 2026 20:19

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

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

…ken leg

AbstractManagedIdentity.HandleException mapped FormatException onto
invalid_managed_identity_endpoint, but the normalization wrapper added in this
PR collapsed everything that was not an HttpRequestException onto the generic
managed_identity_request_failed. That is the same class of error-contract loss
this PR exists to fix, so restore the mapping.

The arm is reachable: the token endpoint is built from binding.Endpoint, a
value IMDS supplies, so a malformed value surfaces as UriFormatException (a
FormatException) instead of a generic failure.

Also correct two comments:

- ShouldRemintImdsV2Binding claimed a mint-step failure was "recoverable by
  re-minting" because minting talks to IMDS "over TLS". The mint endpoints are
  plain HTTP (http://169.254.169.254) and present no binding certificate, so a
  SCHANNEL failure cannot originate there. The behavior is unchanged and
  harmless; only the stated rationale was wrong.

- Document that IsUnwrappedNonMsalFailure gates on MsalException rather than
  HandleException's narrower MsalServiceException. That divergence is
  intentional: it stops MsalClientException from being rewrapped as
  managed_identity_request_failed, preserving the more specific error code.

Adds mTLSPop_TokenLeg_FormatFailure_IsWrappedAsInvalidEndpointAsync, verified
to fail against the pre-fix mapping.

Validated on both target frameworks: net8.0 and net48 each report 462 passed,
1 skipped, 0 failed for FullyQualifiedName~ManagedIdentity.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings September 1, 2026 20:52

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

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

@gladjohn

Copy link
Copy Markdown
Contributor

looks good Robbie-Microsoft, just two minor comments

Replaces the injection-based test with one that exercises the actual path
Gladwin asked about: IMDS returns a malformed mtls_authentication_endpoint,
which is only null/empty-checked during the mint step, flows into
binding.Endpoint, and throws UriFormatException when the token leg parses it.

Asserts both halves of the contract: the error code stays
invalid_managed_identity_endpoint (not the generic request-failed code), and
no re-mint is attempted.

Verified the test fails without the FormatException arm and passes with it.
Endpoint value chosen to survive TrimEnd('/'); confirmed UriBuilder throws
for it on both net48 and net8.0.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI review requested due to automatic review settings September 2, 2026 01:53

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.

🟒 Approval recommended

The change restores a prior exception contract and retry behavior with targeted, deterministic regression tests covering the reported failure mode and key non-regression cases (cancellation/unrelated failures).

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agentic-cli Terminal AI agent drove the bulk of the edits bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] IMDSv2 Schannel failures bypass certificate re-mint retry in delegated TokenClient path

4 participants