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 9 commits into
base: dev6x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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 @@ -12,6 +12,7 @@
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens;
using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages;
using System.Security.Claims;
westin-m marked this conversation as resolved.
Show resolved Hide resolved

#if !NET45
using System.IO;
Expand Down Expand Up @@ -538,7 +539,6 @@ internal static JsonDocument GetJsonDocumentFromBase64UrlEncodedString(string ra
return Base64UrlEncoding.Decode<JsonDocument>(rawString, startIndex, length, ParseDocument);
}
#endif

}
}

67 changes: 63 additions & 4 deletions src/Microsoft.IdentityModel.Tokens/AppContextSwitches.cs
westin-m marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,73 @@ 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.
/// Enables a fallback to the previous behavior of using <see cref="ClaimsIdentity"/> instead of <see cref="CaseSensitiveClaimsIdentity"/> globally.
westin-m marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
internal const string UseCaseSensitiveClaimsIdentityTypeSwitch = "Microsoft.IdentityModel.Tokens.UseCaseSensitiveClaimsIdentityType";
internal const string UseClaimsIdentityTypeSwitch = "Microsoft.IdentityModel.Tokens.UseClaimsIdentityType";

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

internal static bool UseClaimsIdentityType => _useClaimsIdentityType ??= (AppContext.TryGetSwitch(UseClaimsIdentityTypeSwitch, out bool useClaimsIdentityType) && useClaimsIdentityType);

/// <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);

/// <summary>
/// When reading claims from the token, specifies whether to try to convert all string claims to DateTime.
/// Some claims are known not to be DateTime, so conversion is skipped.
/// </summary>
internal const string TryAllStringClaimsAsDateTimeSwitch = "Switch.Microsoft.IdentityModel.TryAllStringClaimsAsDateTime";
keegan-caruso marked this conversation as resolved.
Show resolved Hide resolved

private static bool? _tryAllStringClaimsAsDateTime;

internal static bool TryAllStringClaimsAsDateTime => _tryAllStringClaimsAsDateTime ??= (AppContext.TryGetSwitch(TryAllStringClaimsAsDateTimeSwitch, out bool tryAsDateTime) && tryAsDateTime);

/// <summary>
/// Controls whether to validate the length of the authentication tag when decrypting a token.
/// </summary>
internal const string SkipValidationOfAuthenticationTagLengthSwitch = "Switch.Microsoft.IdentityModel.SkipAuthenticationTagLengthValidation";

private static bool? _skipValidationOfAuthenticationTagLength;

internal static bool ShouldValidateAuthenticationTagLength => _skipValidationOfAuthenticationTagLength ??= !(AppContext.TryGetSwitch(SkipValidationOfAuthenticationTagLengthSwitch, out bool skipValidation) && skipValidation);

/// <summary>
/// Controls whether to use the short name for the RSA OAEP key wrap algorithm.
/// </summary>
internal const string UseShortNameForRsaOaepKeySwitch = "Switch.Microsoft.IdentityModel.UseShortNameForRsaOaepKey";

private static bool? _useShortNameForRsaOaepKey;

internal static bool ShouldUseShortNameForRsaOaepKey => _useShortNameForRsaOaepKey ??= AppContext.TryGetSwitch(UseShortNameForRsaOaepKeySwitch, out var useKeyWrap) && useKeyWrap;

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

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

_tryAllStringClaimsAsDateTime = null;
AppContext.SetSwitch(TryAllStringClaimsAsDateTimeSwitch, false);

_skipValidationOfAuthenticationTagLength = null;
AppContext.SetSwitch(SkipValidationOfAuthenticationTagLengthSwitch, false);

_useShortNameForRsaOaepKey = null;
AppContext.SetSwitch(UseShortNameForRsaOaepKeySwitch, false);
}
#else
// .NET 4.5 does not support AppContext switches. Always use ClaimsIdentity.
internal static bool UseCaseSensitiveClaimsIdentityType() => false;
Expand Down
37 changes: 22 additions & 15 deletions src/Microsoft.IdentityModel.Tokens/ClaimsIdentityFactory.cs
westin-m marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -6,36 +6,43 @@

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.UseClaimsIdentityType"/>.
/// </summary>
#endif

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

return new ClaimsIdentity(claims);
#if !NET45
if (AppContextSwitches.UseClaimsIdentityType)
return new ClaimsIdentity(claims);
#endif
return new CaseSensitiveClaimsIdentity(claims);
}

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

return new ClaimsIdentity(claims, authenticationType);
#if !NET45
if (AppContextSwitches.UseClaimsIdentityType)
return new ClaimsIdentity(claims, authenticationType);
#endif
return new CaseSensitiveClaimsIdentity(claims, authenticationType);
}

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

return new ClaimsIdentity(authenticationType: authenticationType, nameType: nameType, roleType: roleType);
if (AppContextSwitches.UseClaimsIdentityType)
return new ClaimsIdentity(authenticationType: authenticationType, nameType: nameType, roleType: roleType);
#endif
return new CaseSensitiveClaimsIdentity(authenticationType: authenticationType, nameType: nameType, roleType: roleType)
{
SecurityToken = securityToken,
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ public static void EnableAadSigningKeyIssuerValidation(this TokenValidationParam
}

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

private static bool DontFailOnMissingTid()
{
return (AppContext.TryGetSwitch(DontFailOnMissingTidSwitch, out bool dontFailOnMissingTid) && dontFailOnMissingTid);
return (AppContext.TryGetSwitch(DoNotFailOnMissingTidSwitch, out bool doNotFailOnMissingTid) && doNotFailOnMissingTid);
westin-m marked this conversation as resolved.
Show resolved Hide resolved
}
#endif

Expand Down Expand Up @@ -83,10 +83,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
westin-m marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,9 @@ namespace Microsoft.IdentityModel.JsonWebTokens.Tests
public class JsonWebTokenHandlerClaimsIdentityTests
{

#if NET46_OR_GREATER || NETCOREAPP || NETSTANDARD
[Fact]
public void CreateClaimsIdentity_ReturnsCaseSensitveClaimsIdentity_WithAppContextSwitch()
{
AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, true);

var handler = new DerivedJsonWebTokenHandler();
var jsonWebToken = new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor()));
var tokenValidationParameters = new TokenValidationParameters();
Expand All @@ -40,14 +37,17 @@ public void CreateClaimsIdentity_ReturnsCaseSensitveClaimsIdentity_WithAppContex
actualClaimsIdentity = handler.CreateClaimsIdentityInternal(jsonWebToken, tokenValidationParameters, Default.Issuer);
Assert.IsType<CaseSensitiveClaimsIdentity>(actualClaimsIdentity);
Assert.NotNull(((CaseSensitiveClaimsIdentity)actualClaimsIdentity).SecurityToken);

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

#if NET46_OR_GREATER || NETCOREAPP || NETSTANDARD
[Fact]
public void CreateClaimsIdentity_ReturnsClaimsIdentity_ByDefault()
{
AppContext.SetSwitch(AppContextSwitches.UseClaimsIdentityTypeSwitch, true);

var handler = new DerivedJsonWebTokenHandler();
var jsonWebToken = new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor()));
var tokenValidationParameters = new TokenValidationParameters();
Expand All @@ -58,7 +58,10 @@ public void CreateClaimsIdentity_ReturnsClaimsIdentity_ByDefault()
// This will also test mapped claims flow.
handler.MapInboundClaims = true;
Assert.IsType<ClaimsIdentity>(handler.CreateClaimsIdentityInternal(jsonWebToken, tokenValidationParameters, Default.Issuer));

AppContextSwitches.ResetAllSwitches();
}
#endif

private class DerivedJsonWebTokenHandler : JsonWebTokenHandler
{
Expand Down
westin-m marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,7 @@ public static TheoryData<JwtTheoryData> ParseTokenTheoryData
theoryData.Add(new JwtTheoryData(nameof(EncodedJwts.InvalidHeader))
{
Token = EncodedJwts.InvalidHeader,
#if NET452
#if NET45
ExpectedException = new ExpectedException(typeof(ArgumentException), "IDX14102:", typeof(JsonReaderException), false ),
#else
ExpectedException = new ExpectedException(typeof(ArgumentException), "IDX14102:", typeof(JsonReaderException), true),
Expand All @@ -606,7 +606,7 @@ public static TheoryData<JwtTheoryData> ParseTokenTheoryData
theoryData.Add(new JwtTheoryData(nameof(EncodedJwts.InvalidPayload))
{
Token = EncodedJwts.InvalidPayload,
#if NET452
#if NET45
ExpectedException = new ExpectedException(typeof(ArgumentException), "IDX14101:", typeof(JsonReaderException), false ),
#else
ExpectedException = new ExpectedException(typeof(ArgumentException), "IDX14101:", typeof(JsonReaderException), true),
Expand All @@ -616,7 +616,7 @@ public static TheoryData<JwtTheoryData> ParseTokenTheoryData
theoryData.Add(new JwtTheoryData(nameof(EncodedJwts.JWSEmptyHeader))
{
Token = EncodedJwts.JWSEmptyHeader,
#if NET452
#if NET45
ExpectedException = new ExpectedException(typeof(ArgumentException), "IDX14102:", typeof(JsonReaderException), false ),
#else
ExpectedException = new ExpectedException(typeof(ArgumentException), "IDX14102:", typeof(JsonReaderException), true),
Expand All @@ -626,7 +626,7 @@ public static TheoryData<JwtTheoryData> ParseTokenTheoryData
theoryData.Add(new JwtTheoryData(nameof(EncodedJwts.JWSEmptyPayload))
{
Token = EncodedJwts.JWSEmptyPayload,
#if NET452
#if NET45
ExpectedException = new ExpectedException(typeof(ArgumentException), "IDX14101:", typeof(JsonReaderException), false ),
#else
ExpectedException = new ExpectedException(typeof(ArgumentException), "IDX14101:", typeof(JsonReaderException), true),
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
westin-m marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -228,12 +228,12 @@ public class CaseSensitiveClaimsIdentityTheoryData(string testId) : TheoryDataBa

private static ClaimsIdentity CreateCaseSensitiveClaimsIdentity(JObject claims, TokenValidationParameters validationParameters = null)
{
AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, true);
AppContext.SetSwitch(AppContextSwitches.UseClaimsIdentityTypeSwitch, false);

var handler = new JsonWebTokenHandler();
var claimsIdentity = handler.CreateClaimsIdentityInternal(new JsonWebToken(CreateUnsignedToken(claims)), validationParameters ?? new TokenValidationParameters(), Default.Issuer);

AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, false);
AppContext.SetSwitch(AppContextSwitches.UseClaimsIdentityTypeSwitch, true);

return claimsIdentity;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class ClaimsIdentityFactoryTests
[InlineData(false)]
public void Create_FromTokenValidationParameters_ReturnsCorrectClaimsIdentity(bool useCaseSensitiveClaimsIdentity)
{
AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, useCaseSensitiveClaimsIdentity);
AppContext.SetSwitch(AppContextSwitches.UseClaimsIdentityTypeSwitch, useCaseSensitiveClaimsIdentity);

var jsonWebToken = new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor()));
var tokenValidationParameters = new TokenValidationParameters();
Expand All @@ -35,16 +35,16 @@ public void Create_FromTokenValidationParameters_ReturnsCorrectClaimsIdentity(bo

if (useCaseSensitiveClaimsIdentity)
{
Assert.IsType<CaseSensitiveClaimsIdentity>(actualClaimsIdentity);
Assert.NotNull(((CaseSensitiveClaimsIdentity)actualClaimsIdentity).SecurityToken);
Assert.Equal(jsonWebToken, ((CaseSensitiveClaimsIdentity)actualClaimsIdentity).SecurityToken);
Assert.IsType<ClaimsIdentity>(actualClaimsIdentity);
}
else
{
Assert.IsType<ClaimsIdentity>(actualClaimsIdentity);
Assert.IsType<CaseSensitiveClaimsIdentity>(actualClaimsIdentity);
Assert.NotNull(((CaseSensitiveClaimsIdentity)actualClaimsIdentity).SecurityToken);
Assert.Equal(jsonWebToken, ((CaseSensitiveClaimsIdentity)actualClaimsIdentity).SecurityToken);
}

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

[Theory]
Expand All @@ -53,7 +53,7 @@ public void Create_FromTokenValidationParameters_ReturnsCorrectClaimsIdentity(bo
[InlineData(false, false)]
public void Create_FromDerivedTokenValidationParameters_ReturnsCorrectClaimsIdentity(bool tvpReturnsCaseSensitiveClaimsIdentity, bool tvpReturnsCaseSensitiveClaimsIdentityWithToken)
{
AppContext.SetSwitch(AppContextSwitches.UseCaseSensitiveClaimsIdentityTypeSwitch, true);
AppContext.SetSwitch(AppContextSwitches.UseClaimsIdentityTypeSwitch, true);

var jsonWebToken = new JsonWebToken(Default.Jwt(Default.SecurityTokenDescriptor()));
var tokenValidationParameters = new DerivedTokenValidationParameters(tvpReturnsCaseSensitiveClaimsIdentity, tvpReturnsCaseSensitiveClaimsIdentityWithToken);
Expand Down Expand Up @@ -87,7 +87,7 @@ public void Create_FromDerivedTokenValidationParameters_ReturnsCorrectClaimsIden
Assert.Equal(tokenValidationParameters.NameClaimType, actualClaimsIdentity.NameClaimType);
Assert.Equal(tokenValidationParameters.RoleClaimType, actualClaimsIdentity.RoleClaimType);

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

Expand Down
Loading