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

Extensibility tests: Lifetime - JWT, SAML and SAML2 #3028

Merged
merged 15 commits into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
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 @@ -255,13 +255,28 @@ private async ValueTask<ValidationResult<ValidatedToken>> ValidateJWSAsync(
DateTime? expires = jsonWebToken.HasPayloadClaim(JwtRegisteredClaimNames.Exp) ? jsonWebToken.ValidTo : null;
DateTime? notBefore = jsonWebToken.HasPayloadClaim(JwtRegisteredClaimNames.Nbf) ? jsonWebToken.ValidFrom : null;

ValidationResult<ValidatedLifetime> lifetimeValidationResult = validationParameters.LifetimeValidator(
notBefore, expires, jsonWebToken, validationParameters, callContext);
ValidationResult<ValidatedLifetime> lifetimeValidationResult;
iNinja marked this conversation as resolved.
Show resolved Hide resolved

if (!lifetimeValidationResult.IsValid)
try
{
lifetimeValidationResult = validationParameters.LifetimeValidator(
notBefore, expires, jsonWebToken, validationParameters, callContext);

if (!lifetimeValidationResult.IsValid)
return lifetimeValidationResult.UnwrapError().AddCurrentStackFrame();
iNinja marked this conversation as resolved.
Show resolved Hide resolved
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
StackFrame lifetimeValidationFailureStackFrame = StackFrames.LifetimeValidationFailed ??= new StackFrame(true);
return lifetimeValidationResult.UnwrapError().AddStackFrame(lifetimeValidationFailureStackFrame);
return new LifetimeValidationError(
new MessageDetail(TokenLogMessages.IDX10271),
ValidationFailureType.LifetimeValidatorThrew,
typeof(SecurityTokenInvalidLifetimeException),
ValidationError.GetCurrentStackFrame(),
notBefore,
expires,
ex);
}

if (jsonWebToken.Audiences is not IList<string> tokenAudiences)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -192,17 +192,32 @@ internal virtual ValidationResult<ValidatedConditions> ValidateConditions(
StackFrames.AssertionConditionsNull);
}

var lifetimeValidationResult = validationParameters.LifetimeValidator(
samlToken.Assertion.Conditions.NotBefore,
samlToken.Assertion.Conditions.NotOnOrAfter,
samlToken,
validationParameters,
callContext);

if (!lifetimeValidationResult.IsValid)
ValidationResult<ValidatedLifetime> lifetimeValidationResult;
iNinja marked this conversation as resolved.
Show resolved Hide resolved

try
{
StackFrames.LifetimeValidationFailed ??= new StackFrame(true);
return lifetimeValidationResult.UnwrapError().AddStackFrame(StackFrames.LifetimeValidationFailed);
lifetimeValidationResult = validationParameters.LifetimeValidator(
samlToken.Assertion.Conditions.NotBefore,
samlToken.Assertion.Conditions.NotOnOrAfter,
samlToken,
validationParameters,
callContext);

if (!lifetimeValidationResult.IsValid)
return lifetimeValidationResult.UnwrapError().AddCurrentStackFrame();
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
return new LifetimeValidationError(
new MessageDetail(Tokens.LogMessages.IDX10271),
ValidationFailureType.LifetimeValidatorThrew,
typeof(SecurityTokenInvalidLifetimeException),
ValidationError.GetCurrentStackFrame(),
samlToken.Assertion.Conditions.NotBefore,
samlToken.Assertion.Conditions.NotOnOrAfter,
ex);
}

string? validatedAudience = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,17 +195,32 @@ internal virtual ValidationResult<ValidatedConditions> ValidateConditions(
StackFrames.AssertionConditionsNull);
}

var lifetimeValidationResult = validationParameters.LifetimeValidator(
samlToken.Assertion.Conditions.NotBefore,
samlToken.Assertion.Conditions.NotOnOrAfter,
samlToken,
validationParameters,
callContext);
ValidationResult<ValidatedLifetime> lifetimeValidationResult;
iNinja marked this conversation as resolved.
Show resolved Hide resolved

if (!lifetimeValidationResult.IsValid)
try
{
StackFrames.LifetimeValidationFailed ??= new StackFrame(true);
return lifetimeValidationResult.UnwrapError().AddStackFrame(StackFrames.LifetimeValidationFailed);
lifetimeValidationResult = validationParameters.LifetimeValidator(
samlToken.Assertion.Conditions.NotBefore,
samlToken.Assertion.Conditions.NotOnOrAfter,
samlToken,
validationParameters,
callContext);

if (!lifetimeValidationResult.IsValid)
return lifetimeValidationResult.UnwrapError().AddCurrentStackFrame();
}
#pragma warning disable CA1031 // Do not catch general exception types
catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
{
return new LifetimeValidationError(
new MessageDetail(Tokens.LogMessages.IDX10271),
ValidationFailureType.LifetimeValidatorThrew,
typeof(SecurityTokenInvalidLifetimeException),
ValidationError.GetCurrentStackFrame(),
samlToken.Assertion.Conditions.NotBefore,
samlToken.Assertion.Conditions.NotOnOrAfter,
ex);
}

if (samlToken.Assertion.Conditions.OneTimeUse)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const Microsoft.IdentityModel.Tokens.LogMessages.IDX10002 = "IDX10002: Unknown exception type returned. Type: '{0}'. Message: '{1}'." -> string
const Microsoft.IdentityModel.Tokens.LogMessages.IDX10268 = "IDX10268: Unable to validate audience, validationParameters.ValidAudiences.Count == 0." -> string
const Microsoft.IdentityModel.Tokens.LogMessages.IDX10269 = "IDX10269: IssuerValidationDelegate threw an exception, see inner exception." -> string
const Microsoft.IdentityModel.Tokens.LogMessages.IDX10271 = "IDX10271: LifetimeValidationDelegate threw an exception, see inner exception." -> string
const Microsoft.IdentityModel.Tokens.LogMessages.IDX10272 = "IDX10272: SignatureValidationDelegate threw an exception, see inner exception." -> string
const Microsoft.IdentityModel.Tokens.LogMessages.IDX10273 = "IDX10273: AlgorithmValidationDelegate threw an exception, see inner exception." -> string
const Microsoft.IdentityModel.Tokens.LogMessages.IDX10274 = "IDX10274: IssuerSigningKeyValidationDelegate threw an exception, see inner exception." -> string
iNinja marked this conversation as resolved.
Show resolved Hide resolved
Expand Down Expand Up @@ -63,6 +64,7 @@ static Microsoft.IdentityModel.Tokens.ValidationError.GetCurrentStackFrame(strin
static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.AlgorithmValidatorThrew -> Microsoft.IdentityModel.Tokens.ValidationFailureType
static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.IssuerSigningKeyValidatorThrew -> Microsoft.IdentityModel.Tokens.ValidationFailureType
static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.IssuerValidatorThrew -> Microsoft.IdentityModel.Tokens.ValidationFailureType
static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.LifetimeValidatorThrew -> Microsoft.IdentityModel.Tokens.ValidationFailureType
static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.NoTokenAudiencesProvided -> Microsoft.IdentityModel.Tokens.ValidationFailureType
static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.NoValidationParameterAudiencesProvided -> Microsoft.IdentityModel.Tokens.ValidationFailureType
static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.SignatureAlgorithmValidationFailed -> Microsoft.IdentityModel.Tokens.ValidationFailureType
Expand Down
1 change: 1 addition & 0 deletions src/Microsoft.IdentityModel.Tokens/LogMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ internal static class LogMessages
public const string IDX10267 = "IDX10267: '{0}' has been called by a derived class '{1}' which has not implemented this method. For this call graph to succeed, '{1}' will need to implement '{0}'.";
public const string IDX10268 = "IDX10268: Unable to validate audience, validationParameters.ValidAudiences.Count == 0.";
public const string IDX10269 = "IDX10269: IssuerValidationDelegate threw an exception, see inner exception.";
public const string IDX10271 = "IDX10271: LifetimeValidationDelegate threw an exception, see inner exception.";
public const string IDX10272 = "IDX10272: SignatureValidationDelegate threw an exception, see inner exception.";
public const string IDX10273 = "IDX10273: AlgorithmValidationDelegate threw an exception, see inner exception.";
public const string IDX10274 = "IDX10274: IssuerSigningKeyValidationDelegate threw an exception, see inner exception.";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,11 @@ private class XmlValidationFailure : ValidationFailureType { internal XmlValidat
public static readonly ValidationFailureType IssuerValidatorThrew = new IssuerValidatorFailure("IssuerValidatorThrew");
private class IssuerValidatorFailure : ValidationFailureType { internal IssuerValidatorFailure(string name) : base(name) { } }

/// <summary>
/// Defines a type that represents the fact that the lifetime validation delegate threw an exception.
/// </summary>
public static readonly ValidationFailureType LifetimeValidatorThrew = new LifetimeValidationFailure("LifetimeValidatorThrew");

/// <summary>
/// Defines a type that represents the fact that the issuer signing key validation delegate threw an exception.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Threading.Tasks;
using Microsoft.IdentityModel.TestUtils.TokenValidationExtensibility.Tests;
using Xunit;

#nullable enable
namespace Microsoft.IdentityModel.JsonWebTokens.Extensibility.Tests
{
public partial class JsonWebTokenHandlerValidateTokenAsyncTests
{
[Theory, MemberData(
nameof(GenerateLifetimeExtensibilityTestCases),
parameters: ["JWT", 2],
DisableDiscoveryEnumeration = true)]
public async Task ValidateTokenAsync_LifetimeValidator_Extensibility(
LifetimeExtensibilityTheoryData theoryData)
{
await ExtensibilityTesting.ValidateTokenAsync_Extensibility(
theoryData,
this,
nameof(ValidateTokenAsync_LifetimeValidator_Extensibility));
}

public static TheoryData<LifetimeExtensibilityTheoryData> GenerateLifetimeExtensibilityTestCases(
string tokenHandlerType,
int extraStackFrames)
{
return ExtensibilityTesting.GenerateLifetimeExtensibilityTestCases(
tokenHandlerType,
extraStackFrames,
"JsonWebTokenHandler.ValidateToken.Internal.cs");
}
}
}
#nullable restore
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using Microsoft.IdentityModel.Tokens;

#nullable enable
namespace Microsoft.IdentityModel.TestUtils
{
internal class CustomLifetimeValidationDelegates
{
internal static ValidationResult<ValidatedLifetime> CustomLifetimeValidatorDelegate(
DateTime? notBefore,
DateTime? expires,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
// Returns a CustomLifetimeValidationError : LifetimeValidationError
return new CustomLifetimeValidationError(
new MessageDetail(nameof(CustomLifetimeValidatorDelegate), null),
ValidationFailureType.LifetimeValidationFailed,
typeof(SecurityTokenInvalidLifetimeException),
ValidationError.GetCurrentStackFrame(),
notBefore,
expires,
null);
}

internal static ValidationResult<ValidatedLifetime> CustomLifetimeValidatorCustomExceptionDelegate(
DateTime? notBefore,
DateTime? expires,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new CustomLifetimeValidationError(
new MessageDetail(nameof(CustomLifetimeValidatorCustomExceptionDelegate), null),
ValidationFailureType.LifetimeValidationFailed,
typeof(CustomSecurityTokenInvalidLifetimeException),
ValidationError.GetCurrentStackFrame(),
notBefore,
expires,
null);
}

internal static ValidationResult<ValidatedLifetime> CustomLifetimeValidatorCustomExceptionCustomFailureTypeDelegate(
DateTime? notBefore,
DateTime? expires,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new CustomLifetimeValidationError(
new MessageDetail(nameof(CustomLifetimeValidatorCustomExceptionCustomFailureTypeDelegate), null),
CustomLifetimeValidationError.CustomLifetimeValidationFailureType,
typeof(CustomSecurityTokenInvalidLifetimeException),
ValidationError.GetCurrentStackFrame(),
notBefore,
expires);
}

internal static ValidationResult<ValidatedLifetime> CustomLifetimeValidatorUnknownExceptionDelegate(
DateTime? notBefore,
DateTime? expires,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new CustomLifetimeValidationError(
new MessageDetail(nameof(CustomLifetimeValidatorUnknownExceptionDelegate), null),
ValidationFailureType.LifetimeValidationFailed,
typeof(NotSupportedException),
ValidationError.GetCurrentStackFrame(),
notBefore,
expires,
null);
}

internal static ValidationResult<ValidatedLifetime> CustomLifetimeValidatorWithoutGetExceptionOverrideDelegate(
DateTime? notBefore,
DateTime? expires,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new CustomLifetimeWithoutGetExceptionValidationOverrideError(
new MessageDetail(nameof(CustomLifetimeValidatorWithoutGetExceptionOverrideDelegate), null),
ValidationFailureType.LifetimeValidationFailed,
typeof(CustomSecurityTokenInvalidLifetimeException),
ValidationError.GetCurrentStackFrame(),
notBefore,
expires,
null);
}

internal static ValidationResult<ValidatedLifetime> LifetimeValidatorDelegate(
DateTime? notBefore,
DateTime? expires,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new LifetimeValidationError(
new MessageDetail(nameof(LifetimeValidatorDelegate), null),
ValidationFailureType.LifetimeValidationFailed,
typeof(SecurityTokenInvalidLifetimeException),
ValidationError.GetCurrentStackFrame(),
notBefore,
expires,
null);
}

internal static ValidationResult<ValidatedLifetime> LifetimeValidatorThrows(
DateTime? notBefore,
DateTime? expires,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
throw new CustomSecurityTokenInvalidLifetimeException(nameof(LifetimeValidatorThrows), null);
}

internal static ValidationResult<ValidatedLifetime> LifetimeValidatorCustomLifetimeExceptionTypeDelegate(
DateTime? notBefore,
DateTime? expires,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new LifetimeValidationError(
new MessageDetail(nameof(LifetimeValidatorCustomLifetimeExceptionTypeDelegate), null),
ValidationFailureType.LifetimeValidationFailed,
typeof(CustomSecurityTokenInvalidLifetimeException),
ValidationError.GetCurrentStackFrame(),
notBefore,
expires,
null);
}

internal static ValidationResult<ValidatedLifetime> LifetimeValidatorCustomExceptionTypeDelegate(
DateTime? notBefore,
DateTime? expires,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new LifetimeValidationError(
new MessageDetail(nameof(LifetimeValidatorCustomExceptionTypeDelegate), null),
ValidationFailureType.LifetimeValidationFailed,
typeof(CustomSecurityTokenException),
ValidationError.GetCurrentStackFrame(),
notBefore,
expires,
null);
}
}
}
#nullable restore
Loading
Loading