-
Notifications
You must be signed in to change notification settings - Fork 255
Fix certificate reload logic to only trigger on certificate-specific errors #3653
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
Merged
Merged
Changes from 9 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
1392f17
Initial plan
Copilot 8bbf090
Fix certificate reload logic to only trigger on certificate-related e…
Copilot 312757e
Update CertificatesObserverTests to use certificate-specific error code
Copilot 4a52eff
Merge branch 'master' into copilot/fix-certificate-reload-logic
jmprieur 741b4a6
Merge branch 'master' into copilot/fix-certificate-reload-logic
jmprieur ef13e42
Refactor certificate error code checks to use centralized HashSet (Ce…
jmprieur 36ef6f9
Revert commit ef13e42e249c1ab32e3279c9ca72815269d61600.
jmprieur 1a34dbb
Revert "Refactor certificate error code checks to use centralized Has…
jmprieur 4257b69
Revert "Revert commit ef13e42e249c1ab32e3279c9ca72815269d61600."
jmprieur c28868e
Update Constants.cs with certificate-related error codes
jmprieur 19f9c2a
Used the dict that is already created for the certificate related iss…
4gust fb77f3b
added the constant to unshipped
4gust ceaff42
Merge branch 'master' into copilot/fix-certificate-reload-logic
4gust 47e101f
Use IndexOf for case-insensitive string comparison on .NET Framework
Copilot 560638e
Rename CertificateNotWithinValidityPeriod to ClientAssertionContainsI…
Copilot a5fe25d
Removed new api from shipped to unshipped
4gust File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
218 changes: 218 additions & 0 deletions
218
tests/Microsoft.Identity.Web.Test/CertificateReloadLogicTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,218 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Reflection; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Identity.Abstractions; | ||
| using Microsoft.Identity.Client; | ||
| using Microsoft.Identity.Web.Test.Common; | ||
| using Microsoft.Identity.Web.TestOnly; | ||
| using Xunit; | ||
|
|
||
| namespace Microsoft.Identity.Web.Test | ||
| { | ||
| /// <summary> | ||
| /// Tests for the certificate reload logic to ensure it only triggers on certificate-related errors. | ||
| /// This addresses the regression from PR #3430 where reload was triggered on all invalid_client errors. | ||
| /// </summary> | ||
| [Collection(nameof(TokenAcquirerFactorySingletonProtection))] | ||
| public class CertificateReloadLogicTests | ||
| { | ||
| private const string InvalidClientErrorCode = "invalid_client"; | ||
|
|
||
| [Theory] | ||
| [InlineData("AADSTS700027", true)] // InvalidKeyError | ||
| [InlineData("AADSTS700024", true)] // SignedAssertionInvalidTimeRange | ||
| [InlineData("AADSTS7000214", true)] // CertificateHasBeenRevoked | ||
| [InlineData("AADSTS1000502", true)] // CertificateIsOutsideValidityWindow | ||
| [InlineData("AADSTS7000274", true)] // CertificateNotWithinValidityPeriod | ||
| [InlineData("AADSTS7000277", true)] // CertificateWasRevoked | ||
| [InlineData("AADSTS7000215", false)] // Invalid client secret - should NOT trigger reload | ||
| [InlineData("AADSTS700016", false)] // Application not found - should NOT trigger reload | ||
| [InlineData("AADSTS7000222", false)] // Invalid client secret (expired) - should NOT trigger reload | ||
| [InlineData("AADSTS50011", false)] // Invalid reply address - should NOT trigger reload | ||
| [InlineData("AADSTS50012", false)] // Invalid client credentials - should NOT trigger reload | ||
| public void IsInvalidClientCertificateOrSignedAssertionError_ReturnsTrueOnlyForCertificateErrors( | ||
| string errorCode, | ||
| bool shouldTriggerReload) | ||
| { | ||
| // Arrange | ||
| var tokenAcquisition = CreateTokenAcquisition(); | ||
| var responseBody = $"{{\"error\":\"invalid_client\",\"error_description\":\"Error {errorCode}: Test error\"}}"; | ||
| var exception = CreateMsalServiceException(InvalidClientErrorCode, responseBody); | ||
|
|
||
| // Act | ||
| bool result = InvokeIsInvalidClientCertificateOrSignedAssertionError(tokenAcquisition, exception); | ||
|
|
||
| // Assert | ||
| Assert.Equal(shouldTriggerReload, result); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void IsInvalidClientCertificateOrSignedAssertionError_ReturnsFalseWhenErrorCodeIsNotInvalidClient() | ||
| { | ||
| // Arrange | ||
| var tokenAcquisition = CreateTokenAcquisition(); | ||
| var responseBody = "{\"error\":\"unauthorized_client\",\"error_description\":\"Test error\"}"; | ||
| var exception = CreateMsalServiceException("unauthorized_client", responseBody); | ||
|
|
||
| // Act | ||
| bool result = InvokeIsInvalidClientCertificateOrSignedAssertionError(tokenAcquisition, exception); | ||
|
|
||
| // Assert | ||
| Assert.False(result, "Should not trigger reload for non-invalid_client errors"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void IsInvalidClientCertificateOrSignedAssertionError_ReturnsFalseWhenRetryAlreadyInProgress() | ||
| { | ||
| // Arrange | ||
| var tokenAcquisition = CreateTokenAcquisition(); | ||
|
|
||
| // Set _retryClientCertificate to true to simulate retry in progress | ||
| var retryField = typeof(TokenAcquisition).GetField("_retryClientCertificate", | ||
| BindingFlags.NonPublic | BindingFlags.Instance); | ||
| retryField!.SetValue(tokenAcquisition, true); | ||
|
|
||
| var responseBody = $"{{\"error\":\"invalid_client\",\"error_description\":\"Error {Constants.InvalidKeyError}: Test error\"}}"; | ||
| var exception = CreateMsalServiceException(InvalidClientErrorCode, responseBody); | ||
|
|
||
| // Act | ||
| bool result = InvokeIsInvalidClientCertificateOrSignedAssertionError(tokenAcquisition, exception); | ||
|
|
||
| // Assert | ||
| Assert.False(result, "Should not trigger reload when retry is already in progress"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void IsInvalidClientCertificateOrSignedAssertionError_ReturnsFalseForEmptyResponseBody() | ||
| { | ||
| // Arrange | ||
| var tokenAcquisition = CreateTokenAcquisition(); | ||
| var exception = CreateMsalServiceException(InvalidClientErrorCode, string.Empty); | ||
|
|
||
| // Act | ||
| bool result = InvokeIsInvalidClientCertificateOrSignedAssertionError(tokenAcquisition, exception); | ||
|
|
||
| // Assert | ||
| Assert.False(result, "Should not trigger reload when response body is empty"); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("AADSTS700027")] // Case sensitive check - should still work | ||
| [InlineData("aadsts700027")] // Lowercase | ||
| [InlineData("AaDsTs700027")] // Mixed case | ||
| public void IsInvalidClientCertificateOrSignedAssertionError_IsCaseInsensitive(string errorCodeCase) | ||
| { | ||
| // Arrange | ||
| var tokenAcquisition = CreateTokenAcquisition(); | ||
| var responseBody = $"{{\"error\":\"invalid_client\",\"error_description\":\"Error {errorCodeCase}: Test error\"}}"; | ||
| var exception = CreateMsalServiceException(InvalidClientErrorCode, responseBody); | ||
|
|
||
| // Act | ||
| bool result = InvokeIsInvalidClientCertificateOrSignedAssertionError(tokenAcquisition, exception); | ||
|
|
||
| // Assert | ||
| Assert.True(result, $"Should trigger reload regardless of case: {errorCodeCase}"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void IsInvalidClientCertificateOrSignedAssertionError_WorksWithMultipleErrorCodesInResponse() | ||
| { | ||
| // Arrange | ||
| var tokenAcquisition = CreateTokenAcquisition(); | ||
| // Response might contain multiple error codes or descriptions | ||
| var responseBody = $"{{\"error\":\"invalid_client\",\"error_description\":\"Error {Constants.CertificateHasBeenRevoked}: Certificate has been revoked. Also note AADSTS7000215 in logs.\"}}"; | ||
| var exception = CreateMsalServiceException(InvalidClientErrorCode, responseBody); | ||
|
|
||
| // Act | ||
| bool result = InvokeIsInvalidClientCertificateOrSignedAssertionError(tokenAcquisition, exception); | ||
|
|
||
| // Assert | ||
| Assert.True(result, "Should trigger reload when certificate error code is present, even if other codes are also mentioned"); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Creates a TokenAcquisition instance for testing. | ||
| /// </summary> | ||
| private TokenAcquisition CreateTokenAcquisition() | ||
| { | ||
| TokenAcquirerFactoryTesting.ResetTokenAcquirerFactoryInTest(); | ||
| var tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance(); | ||
| tokenAcquirerFactory.Services.Configure<MicrosoftIdentityApplicationOptions>(options => | ||
| { | ||
| options.Instance = "https://login.microsoftonline.com/"; | ||
| options.TenantId = "f645ad92-e38d-4d1a-b510-d1b09a74a8ca"; | ||
| options.ClientId = "idu773ld-e38d-jud3-45lk-d1b09a74a8ca"; | ||
| options.ClientCredentials = [new CredentialDescription() | ||
| { | ||
| SourceType = CredentialSource.ClientSecret, | ||
| ClientSecret = "someSecret" | ||
| }]; | ||
| }); | ||
|
|
||
| var serviceProvider = tokenAcquirerFactory.Build(); | ||
|
|
||
| // Get the TokenAcquisition instance from the service provider | ||
| var tokenAcquisition = serviceProvider.GetService(typeof(ITokenAcquisitionInternal)) as TokenAcquisition; | ||
|
|
||
| if (tokenAcquisition == null) | ||
| { | ||
| throw new InvalidOperationException("Failed to create TokenAcquisition instance for testing"); | ||
| } | ||
|
|
||
| return tokenAcquisition; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Creates a MsalServiceException for testing. | ||
| /// </summary> | ||
| private MsalServiceException CreateMsalServiceException(string errorCode, string responseBody) | ||
| { | ||
| // Use the MsalServiceException constructor with errorCode and errorMessage | ||
| // The ResponseBody property is internal but can be accessed via reflection | ||
| var exception = new MsalServiceException(errorCode, $"Test exception: {errorCode}"); | ||
|
|
||
| // Set the ResponseBody property using reflection | ||
| var responseBodyField = typeof(MsalServiceException).GetProperty("ResponseBody"); | ||
| if (responseBodyField != null && responseBodyField.CanWrite) | ||
| { | ||
| responseBodyField.SetValue(exception, responseBody); | ||
| } | ||
| else | ||
| { | ||
| // Try the backing field instead | ||
| var backingField = typeof(MsalServiceException).GetField("<ResponseBody>k__BackingField", | ||
| BindingFlags.NonPublic | BindingFlags.Instance); | ||
| if (backingField != null) | ||
| { | ||
| backingField.SetValue(exception, responseBody); | ||
| } | ||
| } | ||
|
|
||
| return exception; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Invokes the private IsInvalidClientCertificateOrSignedAssertionError method using reflection. | ||
| /// </summary> | ||
| private bool InvokeIsInvalidClientCertificateOrSignedAssertionError( | ||
| TokenAcquisition tokenAcquisition, | ||
| MsalServiceException exception) | ||
| { | ||
| var method = typeof(TokenAcquisition).GetMethod( | ||
| "IsInvalidClientCertificateOrSignedAssertionError", | ||
| BindingFlags.NonPublic | BindingFlags.Instance); | ||
|
|
||
| if (method == null) | ||
| { | ||
| throw new InvalidOperationException("Could not find IsInvalidClientCertificateOrSignedAssertionError method"); | ||
| } | ||
|
|
||
| var result = method.Invoke(tokenAcquisition, new object[] { exception }); | ||
| return (bool)result!; | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.