Skip to content
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

Cherry-pick Cache context switches (#2724) #2775

Open
wants to merge 10 commits into
base: dev6x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -538,7 +538,6 @@ internal static JsonDocument GetJsonDocumentFromBase64UrlEncodedString(string ra
return Base64UrlEncoding.Decode<JsonDocument>(rawString, startIndex, length, ParseDocument);
}
#endif

}
}

36 changes: 34 additions & 2 deletions src/Microsoft.IdentityModel.Tokens/AppContextSwitches.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,46 @@ namespace Microsoft.IdentityModel.Tokens
/// </summary>
internal static class AppContextSwitches
{
#if NET461_OR_GREATER || NETCOREAPP || NETSTANDARD
/// <summary>
/// Enables a new behavior of using <see cref="CaseSensitiveClaimsIdentity"/> instead of <see cref="ClaimsIdentity"/> globally.
/// </summary>
internal const string UseCaseSensitiveClaimsIdentityTypeSwitch = "Microsoft.IdentityModel.Tokens.UseCaseSensitiveClaimsIdentityType";

#if NET46_OR_GREATER || NETCOREAPP || NETSTANDARD
internal static bool UseCaseSensitiveClaimsIdentityType() => AppContext.TryGetSwitch(UseCaseSensitiveClaimsIdentityTypeSwitch, out bool useCaseSensitiveClaimsIdentityType) && useCaseSensitiveClaimsIdentityType;
private static bool? _useCaseSensitiveClaimsIdentityType;

internal static bool UseCaseSensitiveClaimsIdentityType => _useCaseSensitiveClaimsIdentityType ??= (AppContext.TryGetSwitch(UseCaseSensitiveClaimsIdentityTypeSwitch, out bool useCaseSensitiveClaimsIdentityType) && useCaseSensitiveClaimsIdentityType);

/// <summary>
/// When validating the issuer signing key, specifies whether to fail if the 'tid' claim is missing.
/// </summary>
internal const string DoNotFailOnMissingTidSwitch = "Switch.Microsoft.IdentityModel.DontFailOnMissingTidValidateIssuerSigning";

private static bool? _doNotFailOnMissingTid;

internal static bool DoNotFailOnMissingTid => _doNotFailOnMissingTid ??= (AppContext.TryGetSwitch(DoNotFailOnMissingTidSwitch, out bool doNotFailOnMissingTid) && doNotFailOnMissingTid);


internal const string SkipValidationOfHmacKey = "Switch.Microsoft.IdentityModel.UnsafeRelaxHmacKeySizeValidation";

private static bool? _skipValidationOfHmacKeySizes;

internal static bool SkipValidationOfHmacKeySizes => _skipValidationOfHmacKeySizes ??= (AppContext.TryGetSwitch(SkipValidationOfHmacKey, out bool skipValidationOfHmacKeySizes) && skipValidationOfHmacKeySizes);

/// <summary>
/// Used for testing to reset all switches to its default value.
/// </summary>
internal static void ResetAllSwitches()
{
_useCaseSensitiveClaimsIdentityType = null;
AppContext.SetSwitch(UseCaseSensitiveClaimsIdentityTypeSwitch, false);

_doNotFailOnMissingTid = null;
AppContext.SetSwitch(DoNotFailOnMissingTidSwitch, false);

_skipValidationOfHmacKeySizes = null;
AppContext.SetSwitch(SkipValidationOfHmacKey, false);
}
#else
// .NET 4.5 does not support AppContext switches. Always use ClaimsIdentity.
internal static bool UseCaseSensitiveClaimsIdentityType() => false;
Expand Down
18 changes: 16 additions & 2 deletions src/Microsoft.IdentityModel.Tokens/ClaimsIdentityFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,49 @@

namespace Microsoft.IdentityModel.Tokens
{
#if !NET45
/// <summary>
/// Facilitates the creation of <see cref="ClaimsIdentity"/> and <see cref="CaseSensitiveClaimsIdentity"/> instances based on the <see cref="AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch"/>.
/// Facilitates the creation of <see cref="ClaimsIdentity"/> and <see cref="CaseSensitiveClaimsIdentity"/> instances based on the <see cref="AppContextSwitches.UseCaseSensitiveClaimsIdentityType"/>.
/// </summary>
#endif

internal static class ClaimsIdentityFactory
{
internal static ClaimsIdentity Create(IEnumerable<Claim> claims)
{
#if NET45
if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType())
#else
if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType)
#endif
return new CaseSensitiveClaimsIdentity(claims);

return new ClaimsIdentity(claims);
}

internal static ClaimsIdentity Create(IEnumerable<Claim> claims, string authenticationType)
{
#if NET45
if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType())
#else
if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType)
#endif
return new CaseSensitiveClaimsIdentity(claims, authenticationType);

return new ClaimsIdentity(claims, authenticationType);
}

internal static ClaimsIdentity Create(string authenticationType, string nameType, string roleType, SecurityToken securityToken)
{
#if NET45
if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType())
#else
if (AppContextSwitches.UseCaseSensitiveClaimsIdentityType)
#endif
return new CaseSensitiveClaimsIdentity(authenticationType: authenticationType, nameType: nameType, roleType: roleType)
{
SecurityToken = securityToken,
};

return new ClaimsIdentity(authenticationType: authenticationType, nameType: nameType, roleType: roleType);
}
}
Expand Down
6 changes: 2 additions & 4 deletions src/Microsoft.IdentityModel.Tokens/CryptoProviderFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ public class CryptoProviderFactory
private static object _cacheLock = new object();
private static int _defaultSignatureProviderObjectPoolCacheSize = Environment.ProcessorCount * 4;
private int _signatureProviderObjectPoolCacheSize = _defaultSignatureProviderObjectPoolCacheSize;
#if !NET45
internal const string _skipValidationOfHmacKeySizes = "Switch.Microsoft.IdentityModel.UnsafeRelaxHmacKeySizeValidation";
#endif

/// <summary>
/// Returns the default <see cref="CryptoProviderFactory"/> instance.
/// </summary>
Expand Down Expand Up @@ -492,7 +490,7 @@ public virtual KeyedHashAlgorithm CreateKeyedHashAlgorithm(byte[] keyBytes, stri
private static void ValidateKeySize(byte[] keyBytes, string algorithm, int expectedNumberOfBytes)
{
#if !NET45
if (AppContext.TryGetSwitch(_skipValidationOfHmacKeySizes, out bool skipValidationOfHmacKeySize) && skipValidationOfHmacKeySize)
if (AppContextSwitches.SkipValidationOfHmacKeySizes)
return;
#endif
if (keyBytes.Length < expectedNumberOfBytes)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,6 @@ public static void EnableAadSigningKeyIssuerValidation(this TokenValidationParam
};
}

#if !NET45
internal const string DontFailOnMissingTidSwitch = "Switch.Microsoft.IdentityModel.DontFailOnMissingTidValidateIssuerSigning";

private static bool DontFailOnMissingTid()
{
return (AppContext.TryGetSwitch(DontFailOnMissingTidSwitch, out bool dontFailOnMissingTid) && dontFailOnMissingTid);
}
#endif

/// <summary>
/// Validates the issuer signing key.
/// </summary>
Expand Down Expand Up @@ -83,10 +74,9 @@ internal static bool ValidateIssuerSigningKey(SecurityKey securityKey, SecurityT
if (string.IsNullOrEmpty(tenantIdFromToken))
{
#if !NET45
if (DontFailOnMissingTid())
if (AppContextSwitches.DoNotFailOnMissingTid)
return true;
#endif

throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidIssuerException(LogMessages.IDX40009));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
Expand Down Expand Up @@ -41,7 +41,7 @@ public void CreateClaimsIdentity_ReturnsCaseSensitveClaimsIdentity_WithAppContex
Assert.IsType<CaseSensitiveClaimsIdentity>(actualClaimsIdentity);
Assert.NotNull(((CaseSensitiveClaimsIdentity)actualClaimsIdentity).SecurityToken);

AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, false);
AppContextSwitches.ResetAllSwitches();
}
#endif

Expand All @@ -58,6 +58,9 @@ public void CreateClaimsIdentity_ReturnsClaimsIdentity_ByDefault()
// This will also test mapped claims flow.
handler.MapInboundClaims = true;
Assert.IsType<ClaimsIdentity>(handler.CreateClaimsIdentityInternal(jsonWebToken, tokenValidationParameters, Default.Issuer));
#if !NET452
AppContextSwitches.ResetAllSwitches();
#endif
}

private class DerivedJsonWebTokenHandler : JsonWebTokenHandler
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ public void OidcCreateAuthenticationRequestUrl(string testId, OpenIdConnectMessa
TestUtilities.WriteHeader(testId, "OidcCreateAuthenticationRequestUrl", true);
var context = new CompareContext();
// there is no net452 target, we bind to net45
#if NET452
#if NET45
if(!message.SkuTelemetryValue.Equals("ID_NET45"))
context.Diffs.Add($"{message.SkuTelemetryValue} != ID_NET45");
#elif NET461
Expand Down Expand Up @@ -494,7 +494,7 @@ public void OidcCreateLogoutRequestUrl(string testId, OpenIdConnectMessage messa

var context = new CompareContext();
// there is no net452 target, we bind to net45
#if NET452
#if NET45
if (!message.SkuTelemetryValue.Equals("ID_NET45"))
context.Diffs.Add($"{message.SkuTelemetryValue} != ID_NET45");
#elif NET461
Expand All @@ -505,7 +505,7 @@ public void OidcCreateLogoutRequestUrl(string testId, OpenIdConnectMessage messa
context.Diffs.Add($"{message.SkuTelemetryValue} != ID_NET472");
#elif NET6_0
if (!message.SkuTelemetryValue.Equals("ID_NET6_0"))
context.Diffs.Add($"{message.SkuTelemetryValue} != ID_NETCOREAPP3_1");
context.Diffs.Add($"{message.SkuTelemetryValue} != ID_NET6_0");
#elif NET_CORE
if (!message.SkuTelemetryValue.Equals("ID_NETSTANDARD2_0"))
context.Diffs.Add($"{message.SkuTelemetryValue} != ID_NETSTANDARD2_0");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public void Create_FromTokenValidationParameters_ReturnsCorrectClaimsIdentity(bo
Assert.IsType<ClaimsIdentity>(actualClaimsIdentity);
}

AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, false);
AppContextSwitches.ResetAllSwitches();
}

[Theory]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -745,7 +745,7 @@ public void SymmetricSecurityKeySizesSign(SymmetricSignatureProviderTheoryData t
[Theory, MemberData(nameof(SymmetricSecurityKeySizesVerifyOFFTheoryData))]
public void SymmetricSecurityKeySizesVerifyOFF(SymmetricSignatureProviderTheoryData theoryData)
{
AppContext.SetSwitch(CryptoProviderFactory._skipValidationOfHmacKeySizes, true);
AppContext.SetSwitch(AppContextSwitches.SkipValidationOfHmacKey, true);
var context = TestUtilities.WriteHeader($"{this}.SymmetricSecurityKeySizes", theoryData);
try
{
Expand All @@ -759,7 +759,7 @@ public void SymmetricSecurityKeySizesVerifyOFF(SymmetricSignatureProviderTheoryD
theoryData.ExpectedException.ProcessException(ex, context);
}

AppContext.SetSwitch(CryptoProviderFactory._skipValidationOfHmacKeySizes, false);
AppContextSwitches.ResetAllSwitches();
TestUtilities.AssertFailIfErrors(context);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,11 @@ public void ValidateIssuerSigningKeyTests(AadSigningKeyIssuerTheoryData theoryDa
}
finally
{
#if !NET452
AppContextSwitches.ResetAllSwitches();
#else
theoryData.TearDownAction?.Invoke();
#endif
}

TestUtilities.AssertFailIfErrors(context);
Expand Down Expand Up @@ -346,8 +350,8 @@ public static TheoryData<AadSigningKeyIssuerTheoryData> ValidateIssuerSigningKey
SecurityKey = KeyingMaterial.JsonWebKeyP256,
SecurityToken = new JwtSecurityToken(),
OpenIdConnectConfiguration = mockConfiguration,
SetupAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, true),
TearDownAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, false)
SetupAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, true),
TearDownAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, false)
});

theoryData.Add(new AadSigningKeyIssuerTheoryData
Expand All @@ -357,8 +361,8 @@ public static TheoryData<AadSigningKeyIssuerTheoryData> ValidateIssuerSigningKey
SecurityToken = new JwtSecurityToken(),
OpenIdConnectConfiguration = mockConfiguration,
ExpectedException = ExpectedException.SecurityTokenInvalidIssuerException("IDX40009"),
SetupAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, false),
TearDownAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, isEnabled: false)
SetupAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, false),
TearDownAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, isEnabled: false)
});

theoryData.Add(new AadSigningKeyIssuerTheoryData
Expand All @@ -367,8 +371,8 @@ public static TheoryData<AadSigningKeyIssuerTheoryData> ValidateIssuerSigningKey
SecurityKey = KeyingMaterial.JsonWebKeyP256,
SecurityToken = new JwtSecurityToken(),
OpenIdConnectConfiguration = mockConfiguration,
SetupAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, true),
TearDownAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, false)
SetupAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, true),
TearDownAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, false)
});

theoryData.Add(new AadSigningKeyIssuerTheoryData
Expand All @@ -378,8 +382,8 @@ public static TheoryData<AadSigningKeyIssuerTheoryData> ValidateIssuerSigningKey
SecurityToken = new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor(Default.SymmetricSigningCredentials, [issClaim]))),
OpenIdConnectConfiguration = mockConfiguration,
ExpectedException = ExpectedException.SecurityTokenInvalidIssuerException("IDX40009"),
SetupAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, false),
TearDownAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, isEnabled: false)
SetupAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, false),
TearDownAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, isEnabled: false)
});

theoryData.Add(new AadSigningKeyIssuerTheoryData
Expand All @@ -388,8 +392,8 @@ public static TheoryData<AadSigningKeyIssuerTheoryData> ValidateIssuerSigningKey
SecurityKey = KeyingMaterial.JsonWebKeyP256,
SecurityToken = new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor(Default.SymmetricSigningCredentials, [issClaim]))),
OpenIdConnectConfiguration = mockConfiguration,
SetupAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, true),
TearDownAction = () => AppContext.SetSwitch(AadTokenValidationParametersExtension.DontFailOnMissingTidSwitch, false)
SetupAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, true),
TearDownAction = () => AppContext.SetSwitch(AppContextSwitches.DoNotFailOnMissingTidSwitch, false)
});
#endif

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -615,8 +615,8 @@ public static TheoryData<JwtTheoryData> RoundTripTokensTheoryData()
ValidationParameters = Default.SymmetricEncryptSignTokenValidationParameters
});

#if NET461 || NET462 || NET_CORE
// RsaPss is not supported on .NET < 4.6
#if NET462 || NET_CORE
// RsaPss is not supported on .NET < 4.6.2
var rsaPssSigningCredentials = new SigningCredentials(Default.AsymmetricSigningKey, SecurityAlgorithms.RsaSsaPssSha256);
theoryData.Add(new JwtTheoryData
{
Expand Down