Skip to content

Commit

Permalink
Extensibility tests: Lifetime - JWT, SAML and SAML2 (#3028)
Browse files Browse the repository at this point in the history
* Handle potential exception thrown by the lifetime validation delegate in JWT, SAML, and SAML2

* Added custom lifetime validation delegates for testing

(cherry picked from commit 6f104dc)

* Added lifetime extensibility tests for JWT, SAML, and SAML2

(cherry picked from commit e602638)

* Updated validation failure type position in tests

* Added missing validation failure type to custom lifetime validation delegates

* Handle success case as unexpected in lifetime extensibility tests

* Removed duplicate test code adopting the refactored approach after merging dev
  • Loading branch information
iNinja authored Dec 9, 2024
1 parent bb6433b commit fe4abcf
Show file tree
Hide file tree
Showing 12 changed files with 595 additions and 26 deletions.
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;

if (!lifetimeValidationResult.IsValid)
try
{
lifetimeValidationResult = validationParameters.LifetimeValidator(
notBefore, expires, jsonWebToken, 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
{
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;

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;

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
2 changes: 2 additions & 0 deletions src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const Microsoft.IdentityModel.Tokens.LogMessages.IDX10002 = "IDX10002: Unknown e
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.IDX10270 = "IDX10270: AudienceValidationDelegate 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
Expand Down Expand Up @@ -65,6 +66,7 @@ static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.AlgorithmVa
static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.AudienceValidatorThrew -> 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 @@ -89,6 +89,7 @@ internal static class LogMessages
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 IDX10270 = "IDX10270: AudienceValidationDelegate 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 @@ -134,16 +134,21 @@ private class XmlValidationFailure : ValidationFailureType { internal XmlValidat
/// </summary>
public static readonly ValidationFailureType AlgorithmValidatorThrew = new AlgorithmValidationFailure("AlgorithmValidatorThrew");

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

/// <summary>
/// Defines a type that represents the fact that the issuer validation delegate threw an exception.
/// </summary>
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 audience validation delegate threw an exception.
/// Defines a type that represents the fact that the lifetime validation delegate threw an exception.
/// </summary>
public static readonly ValidationFailureType AudienceValidatorThrew = new AudienceValidationFailure("AudienceValidatorThrew");
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.
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

0 comments on commit fe4abcf

Please sign in to comment.