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

Added sample tests for the new validation path #2801

Closed
wants to merge 2 commits into from
Closed
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 @@ -4,3 +4,4 @@
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.IdentityModel.Validators, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.IdentityModel.JsonWebTokens.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.IdentityModel.TestUtils, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.IdentityModel.SampleTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ internal static Result<SecurityToken, ExceptionDetail> ReadToken(
{
StackFrame malformedTokenStackFrame = StackFrames.ReadTokenMalformed ?? new StackFrame(true);
return new ExceptionDetail(
new MessageDetail(LogMessages.IDX14107),
new MessageDetail(LogMessages.IDX14100),
ValidationFailureType.TokenReadingFailed,
ExceptionType.SecurityTokenMalformed,
malformedTokenStackFrame,
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.IdentityModel.Tokens/InternalsVisibleTo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.IdentityModel.S2S.Tokens.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.IdentityModel.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.IdentityModel.Tokens.Saml.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Microsoft.IdentityModel.SampleTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,11 @@ public static TheoryData<TokenReadingTheoryData> JsonWebTokenHandlerReadTokenTes
TestId = "Invalid_MalformedToken",
Token = "malformed-token",
ExpectedException = ExpectedException.SecurityTokenMalformedTokenException(
"IDX14107:",
"IDX14100:",
typeof(SecurityTokenMalformedException)),
Result = new ExceptionDetail(
new MessageDetail(
LogMessages.IDX14107,
LogMessages.IDX14100,
LogHelper.MarkAsNonPII("token")),
ValidationFailureType.TokenReadingFailed,
ExceptionType.SecurityTokenMalformed,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Threading;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need a new assembly?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CancellationToken requires it.

using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.TestUtils;
using Microsoft.IdentityModel.Tokens;
Expand Down Expand Up @@ -33,13 +34,19 @@ public SampleTokenValidationClass()
ValidIssuer = "http://Default.Issuer.com",
IssuerSigningKey = KeyingMaterial.JsonWebKeyRsa256SigningCredentials.Key
};
ValidationParameters = new ValidationParameters();
ValidationParameters.ValidAudiences.Add("http://Default.Audience.com");
ValidationParameters.ValidIssuers.Add("http://Default.Issuer.com");
ValidationParameters.IssuerSigningKeys.Add(KeyingMaterial.JsonWebKeyRsa256SigningCredentials.Key);
}

/// <summary>
/// Gets or sets the <see cref="TokenValidationParameters"/> used for the validation operations.
/// </summary>
public TokenValidationParameters TokenValidationParameters { get; set; }

public ValidationParameters ValidationParameters { get; set; }

/// <summary>
/// Gets or sets the <see cref="JsonWebTokenHandler"/> instance used for the validation operations.
/// </summary>
Expand All @@ -59,6 +66,11 @@ public void ValidateTokenShim(string token)
ValidateTokenShim(token, TokenValidationParameters);
}

public Result<ValidationResult, ExceptionDetail> ValidateTokenShimWithNewPath(string token)
{
return ValidateTokenShimWithNewPath(token, ValidationParameters);
}

/// <summary>
/// Validates the passed token using the instance of the deprecated <see cref="JwtSecurityTokenHandler"/>.
/// </summary>
Expand All @@ -75,14 +87,20 @@ public void ValidateTokenShimWithDeprecatedModel(string token)
/// <param name="tokenValidationParameters">
/// The <see cref="TokenValidationParameters"/> to use instead of the instance's value.
/// </param>
public void ValidateTokenShim(string token, TokenValidationParameters tokenValidationParameters)
public TokenValidationResult ValidateTokenShim(string token, TokenValidationParameters tokenValidationParameters)
{
var result = JsonWebTokenHandler.ValidateTokenAsync(token, tokenValidationParameters).Result;

if (!result.IsValid)
{
throw new SampleTestTokenValidationException("Validation Issue Encountered", result.Exception);
}

return result;
}

internal Result<ValidationResult, ExceptionDetail> ValidateTokenShimWithNewPath(string token, ValidationParameters validationParameters)
{
CallContext callContext = new CallContext();
return JsonWebTokenHandler.ValidateTokenAsync(token, validationParameters, callContext, CancellationToken.None).Result;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Threading.Tasks;
using Microsoft.IdentityModel.TestExtensions;
using Microsoft.IdentityModel.TestUtils;
using Microsoft.IdentityModel.Tokens;
Expand Down Expand Up @@ -221,6 +222,218 @@ public void TokenWithMissingSecurityCredentials()
}
#endregion

#region New Model Token Validation Tests
/// <summary>
/// Tests how the class under test handles a valid token.
/// </summary>
[Fact]
public void ValidToken_NewPath()
{
SampleTokenValidationClass classUnderTest = new SampleTokenValidationClass();
classUnderTest.ValidateTokenShimWithNewPath(testTokenCreator.CreateDefaultValidToken());
}

/// <summary>
/// Tests how the class under test handles a bogus token; one that in no way conforms to the expected JWS format.
/// </summary>
[Fact]
public void BogusToken_NewPath()
{
TestWithGeneratedToken_NewPath(
() => "InvalidToken",
typeof(SecurityTokenMalformedException),
"IDX14100");
}

/// <summary>
/// Tests how the class under test handles a token with a missing signature.
/// </summary>
[Fact]
public void TokenWithoutSignature_NewPath()
{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateTokenWithNoSignature,
typeof(SecurityTokenInvalidSignatureException),
"IDX10504:");
}

/// <summary>
/// Tests how the class under test handles a token with a malformed signature.
/// </summary>
[Fact]
public void TokenWithBadSignature_NewPath()
{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateTokenWithInvalidSignature,
typeof(SecurityTokenInvalidSignatureException),
"IDX10500:"); // 10500 indicates no signature key was found. Current path returns 10511 which indicates a bad signature and provides the list of keys attempted
}

/// <summary>
/// Tests how the class under test handles a token which is expired.
/// </summary>
[Fact]
public void ExpiredToken_NewPath()
{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateExpiredToken,
typeof(SecurityTokenExpiredException),
"IDX10223");
}

/// <summary>
/// Tests how the class under test handles a token which is not yet valid
/// </summary>
[Fact]
public void NetYetValidToken_NewPath()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is too fractured.
We need sets of tests using TheoryData for Lifetime, Audience, etc.
Why not part of JsonWebTokenHandler.ValidateLifetimeTests

{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateNotYetValidToken,
typeof(SecurityTokenNotYetValidException),
"IDX10222");
}

/// <summary>
/// Tests how the class under test handles a token with an issuer that doesn't match expectations.
/// </summary>
[Fact]
public void TokenWithWrongIssuer_NewPath()
{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateTokenWithBadIssuer,
typeof(SecurityTokenInvalidIssuerException),
"IDX10212");
// Current path returns IDX10205 which contains Issuer, ValidIssuer, and ValidIssuers.
// This is a new error code that drops ValidIssuer as it is no longer used.
}

/// <summary>
/// Tests how the class under test handles a token with an audience that doesn't match expectations.
/// </summary>
[Fact]
public void TokenWithWrongAudience_NewPath()
{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateTokenWithBadAudience,
typeof(SecurityTokenInvalidAudienceException),
"IDX10215");
// Current path returns IDX10214 which contains Audience, ValidAudience, and ValidAudiences.
// This is a new error code that drops ValidAudience as it is no longer used.
}

/// <summary>
/// Tests how the class under test handles a token signed with a key different than the one expected.
/// </summary>
[Fact]
public void TokenWithBadSignatureKey_NewPath()
{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateTokenWithBadSignatureKey,
typeof(SecurityTokenSignatureKeyNotFoundException),
"IDX10500"); // By default, the new path defaults to not trying all signing keys.
}

/// <summary>
/// Tests how the class under test handles a token signed with a key different than the one expected.
/// </summary>
[Fact]
public void TokenWithBadSignatureKey_NewPath_TryAllKeys()
{
Action<ValidationParameters> updateParameters = (validationParameters) =>
validationParameters.TryAllIssuerSigningKeys = true;

TestWithGeneratedToken_NewPath(
testTokenCreator.CreateTokenWithBadSignatureKey,
typeof(SecurityTokenSignatureKeyNotFoundException),
"IDX10503",
updateParameters);
}

/// <summary>
/// Tests how the class under test handles a token missing the iss claim.
/// </summary>
[Fact]
public void TokenWithMissingIssuer_NewPath()
{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateTokenWithMissingIssuer,
typeof(SecurityTokenInvalidIssuerException),
"IDX10211");
}

/// <summary>
/// Tests how the class under test handles a token missing the aud claim.
/// </summary>
[Fact]
public void TokenWithMissingAudience_NewPath()
{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateTokenWithMissingAudience,
typeof(SecurityTokenInvalidAudienceException),
"IDX10206");
}

/// <summary>
/// Tests how the class under test handles a token with a iat claim indicating it has not yet been issued.
/// </summary>
[Fact]
public void TokenWithFutureIssuedAt_NewPath()
{
// NOTE: This is not currently validated and there's no way to enforce its presence.
// It may be enforceable in the future, in which case this will be updated with proper checks.
SampleTokenValidationClass classUnderTest = new SampleTokenValidationClass();
classUnderTest.ValidateTokenShimWithNewPath(testTokenCreator.CreateTokenWithFutureIssuedAt());
}

/// <summary>
/// Tests how the class under test handles a token missing the iat claim.
/// </summary>
[Fact]
public void TokenWithMissingIssuedAt_NewPath()
{
// NOTE: This is not currently validated and there's no way to enforce its presence.
// It may be enforceable in the future, in which case this will be updated with proper checks.
SampleTokenValidationClass classUnderTest = new SampleTokenValidationClass();
classUnderTest.ValidateTokenShimWithNewPath(testTokenCreator.CreateTokenWithMissingIssuedAt());
}

/// <summary>
/// Tests how the class under test handles a token missing the nbf claim.
/// </summary>
[Fact]
public void TokenWithMissingNotBefore_NewPath()
{
// NOTE: This is not currently validated and there's no way to enforce its presence.
// It may be enforceable in the future, in which case this will be updated with proper checks.
SampleTokenValidationClass classUnderTest = new SampleTokenValidationClass();
classUnderTest.ValidateTokenShimWithNewPath(testTokenCreator.CreateTokenWithMissingNotBefore());
}

/// <summary>
/// Tests how the class under test handles a token missing the exp claim.
/// </summary>
[Fact]
public void TokenWithMissingExpires_NewPath()
{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateTokenWithMissingExpires,
typeof(SecurityTokenNoExpirationException),
"IDX10225");
}

/// <summary>
/// Test how the class under test handles a token without a signing key (i.e. alg=none, no signature).
/// </summary>
[Fact]
public void TokenWithMissingSecurityCredentials_NewPath()
{
TestWithGeneratedToken_NewPath(
testTokenCreator.CreateTokenWithMissingKey,
typeof(SecurityTokenInvalidSignatureException),
"IDX10504");
}
#endregion

#region Deprecated Model Token Validation Tests
/// <summary>
/// Tests how a class under test using JwtSecurityTokenHandler handles a valid token.
Expand Down Expand Up @@ -451,6 +664,32 @@ internal void TestWithGeneratedToken(Func<string> generateTokenToTest, Type expe
expectedInnerExceptionMessagePart);
}

internal void TestWithGeneratedToken_NewPath(
Func<string> generateTokenToTest,
Type expectedInnerExceptionType,
string expectedInnerExceptionMessagePart,
Action<ValidationParameters> modifyValidationParameters = null)
{
SampleTokenValidationClass classUnderTest = new SampleTokenValidationClass();
if (modifyValidationParameters != null)
modifyValidationParameters(classUnderTest.ValidationParameters);

string token = generateTokenToTest();
Result<ValidationResult, ExceptionDetail> result = classUnderTest.ValidateTokenShimWithNewPath(token);

if (!result.IsSuccess)
AssertException(expectedInnerExceptionType, expectedInnerExceptionMessagePart, result.UnwrapError().GetException());
else
{
if (expectedInnerExceptionType != null || !string.IsNullOrEmpty(expectedInnerExceptionMessagePart))
throw new TestException(
string.Format(
"Expected an exception of type '{0}' containing '{1}' in the message.",
expectedInnerExceptionType,
expectedInnerExceptionMessagePart));
}
}

/// <summary>
/// Calls a passed <paramref name="validate"/> action with a generated token and validates the outcome.
/// </summary>
Expand Down Expand Up @@ -494,13 +733,16 @@ internal void AssertValidationException(Action action, Type innerExceptionType,
catch (Exception e)
{
Assert.Equal(typeof(SampleTestTokenValidationException), e.GetType());
Assert.Equal(innerExceptionType, e.InnerException.GetType());

if (!string.IsNullOrEmpty(innerExceptionMessagePart))
{
Assert.Contains(innerExceptionMessagePart, e.InnerException.Message);
}
AssertException(innerExceptionType, innerExceptionMessagePart, e.InnerException);
}
}

private static void AssertException(Type exceptionType, string exceptionMessagePart, Exception exception)
{
Assert.Equal(exceptionType, exception.GetType());

if (!string.IsNullOrEmpty(exceptionMessagePart))
Assert.Contains(exceptionMessagePart, exception.Message);
}
}
}
Loading