Repository navigation
Fix IMDSv2 SCHANNEL failures bypassing certificate re-mint retry - #6173
Conversation
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>
There was a problem hiding this comment.
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 asInnerException). - 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>
There was a problem hiding this comment.
π‘ 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>
β¦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>
|
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>
There was a problem hiding this comment.
π’ 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
Fixes #6172
What broke
#6070 (
3680c2fe2) moved the IMDSv2 mTLS-PoP token leg to the sharedTokenClientβOAuth2ClientβHttpManagerpath. The retry logic survived that move β it was re-implemented inManagedIdentityAuthRequest. What did not survive wasAbstractManagedIdentity.HandleException, which normalized raw transport failures intoMsalServiceException(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:
MsalServiceExceptionβHttpRequestExceptionβAuthenticationExceptionβ matchedHttpRequestExceptionβAuthenticationExceptionβWin32Exceptionβ type mismatchNet effect: a KeyGuard/CNG-bound cert Schannel can no longer use (
SEC_E_UNKNOWN_CREDENTIALS, 0x8009030D) surfaced as a bareHttpRequestExceptioninstead 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. WraptokenClient.SendTokenRequestAsyncand re-normalize failures MSAL doesn't already own intoMsalServiceException, mirroringHandleException. Scoped to the token call only β the mint step already throws MSAL-shaped exceptions, so wrapping it would double-wrap. The error-code mapping mirrorsHandleException:HttpRequestExceptionβmanaged_identity_unreachable_network,FormatExceptionβinvalid_managed_identity_endpoint(reachable because the token endpoint is built frombinding.Endpoint, an IMDS-supplied value), everything else βmanaged_identity_request_failed. Guard isex is not MsalException, stricter than the oldMsalServiceExceptioncheck, soMsalClientExceptionis preserved rather than masked.OperationCanceledExceptionpasses through untouched.ShouldRemintImdsV2Bindingβ defense in depth. Widen the catch fromcatch (MsalServiceException ex)tocatch (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 fromMsalServiceException.internal staticβ no public API surface change, noPublicAPI.Unshipped.txtentry. Detection logic byte-for-byte unchanged: it still keys onAuthenticationExceptionbroadly, which also catches server-cert validation failures. That over-trigger is bounded (one wasted re-mint, then the real error propagates) and narrowing it toSEC_E_UNKNOWN_CREDENTIALS/SEC_E_NO_CREDENTIALSis 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 asMsalServiceExceptionagain, with the original exception preserved asInnerException. That restores the documented managed identity contract, but anyone who added acatch (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 viaMockHttpManager.QueueSize, so "retries exactly once" is proven rather than inferred from a successful return.mTLSPop_TokenLeg_RawSchannelFailure_...mTLSPop_TokenLeg_RepeatedSchannelFailure_...mTLSPop_TokenLeg_UnrelatedNetworkFailure_...mTLSPop_TokenLeg_NonHttpFailure_...HttpRequestExceptionnormalized ontomanaged_identity_request_failedmTLSPop_TokenLeg_FormatFailure_...FormatExceptionkeepsinvalid_managed_identity_endpoint, not the generic codeBearerOverMtls_TokenLeg_SchannelFailure_...WithRequestOverMtlsas for PoPmTLSPop_Unattested_TokenLeg_SchannelFailure_...WithAttestationSupportmTLSPop_TokenLeg_Cancellation_...WithRequestOverMtlshad zero coverage inTest.Unitbefore 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 run20260901.8on the MI-enabled Azure VM pool (20/20 passed), which exercises real IMDSv2 with Credential Guard.HttpRequestExceptionfailures trigger one certificate re-mint and retrymTLSPop_TokenLeg_RawSchannelFailure_...(re-mints + retries) and..._RepeatedSchannelFailure_...(retries once, then propagates). Attempt counts asserted viaQueueSize; both fail against pre-fix codeBearerOverMtls_TokenLeg_SchannelFailure_...mirrors the PoP test β both paths shareSendDelegatedImdsV2TokenRequestAsync. E2E:AcquireToken_OnImdsV2_WithRequestOverMtls_ReturnsBearerpassed for SAMI + UAMIAcquireToken_OnImdsV2_MtlsPoP_WithAttestation_Succeeds(SAMI + UAMI-ClientId) andAcquireTokenAndCallAKV_.... Unattested:AcquireToken_OnImdsV2_MtlsPoP_GracefulDegradation_WhenCredentialGuardUnavailableManagedIdentityImdsV2FicTests.FicTwoLeg_MtlsPop_SAMI/_UAMI-ClientIdpassed E2E (plus bothFicTwoLeg_Bearer_*). This is the same code path Identity.Web'sManagedIdentityClientAssertiondrives. Identity.Web's own suite was not run against this branch β its test is[OnlyOnAzureDevopsFact]; static review found no risk (below)mTLSPop_TokenLeg_Cancellation_...(propagates un-wrapped, consumes no re-mint) and..._UnrelatedNetworkFailure_...(neither retried nor swallowed). Both assertQueueSizeBeing 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-webcheckout. No risk found:MsiFic_TwoLeg_FinalMtlsPop_SystemAssignedManagedIdentityAsyncexists (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.4.88.0(Directory.Build.props) β inside the affected range.Exception, logs, and rethrows unfiltered; it does not discriminate on exception type.ManagedIdentityClientAssertionalready documents that bind failures "surface as anMsalServiceExceptionfromExecuteAsync", which is the contract this PR restores.invalid_client+ specific AADSTS codes, somanaged_identity_*error codes cannot trigger a spurious retry.HttpRequestExceptionfilters inDownstreamApi.HttpMethods.csare on downstream API calls, not token acquisition.