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: Audience - JWT, SAML and SAML2 #3027

Merged
merged 14 commits into from
Dec 9, 2024
Merged
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 @@ -267,13 +267,30 @@ private async ValueTask<ValidationResult<ValidatedToken>> ValidateJWSAsync(
if (jsonWebToken.Audiences is not IList<string> tokenAudiences)
tokenAudiences = jsonWebToken.Audiences.ToList();

ValidationResult<string> audienceValidationResult = validationParameters.AudienceValidator(
tokenAudiences, jsonWebToken, validationParameters, callContext);
ValidationResult<string> audienceValidationResult;
try
{
audienceValidationResult = validationParameters.AudienceValidator(
tokenAudiences, jsonWebToken, validationParameters, callContext);

if (!audienceValidationResult.IsValid)
if (!audienceValidationResult.IsValid)
{
StackFrame audienceValidationFailureStackFrame = StackFrames.AudienceValidationFailed ??= new StackFrame(true);
return audienceValidationResult.UnwrapError().AddStackFrame(audienceValidationFailureStackFrame);
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 audienceValidationFailureStackFrame = StackFrames.AudienceValidationFailed ??= new StackFrame(true);
return audienceValidationResult.UnwrapError().AddStackFrame(audienceValidationFailureStackFrame);
return new AudienceValidationError(
new MessageDetail(TokenLogMessages.IDX10270),
ValidationFailureType.AudienceValidatorThrew,
typeof(SecurityTokenInvalidAudienceException),
ValidationError.GetCurrentStackFrame(),
tokenAudiences,
null,
ex);
}

ValidationResult<ValidatedIssuer> issuerValidationResult;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,18 +211,34 @@ internal virtual ValidationResult<ValidatedConditions> ValidateConditions(

if (condition is SamlAudienceRestrictionCondition audienceRestriction)
{

// AudienceRestriction.Audiences is an ICollection<Uri> so we need make a conversion to List<string> before calling our audience validator
var audiencesAsList = audienceRestriction.Audiences.Select(static x => x.OriginalString).ToList();

var audienceValidationResult = validationParameters.AudienceValidator(
audiencesAsList,
samlToken,
validationParameters,
callContext);

if (!audienceValidationResult.IsValid)
return audienceValidationResult.UnwrapError();
ValidationResult<string> audienceValidationResult;

try
{
audienceValidationResult = validationParameters.AudienceValidator(
audiencesAsList,
samlToken,
validationParameters,
callContext);

if (!audienceValidationResult.IsValid)
return audienceValidationResult.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 AudienceValidationError(
new MessageDetail(Tokens.LogMessages.IDX10270),
ValidationFailureType.AudienceValidatorThrew,
typeof(SecurityTokenInvalidAudienceException),
ValidationError.GetCurrentStackFrame(),
audiencesAsList,
validationParameters.ValidAudiences,
ex);
}

validatedAudience = audienceValidationResult.UnwrapResult();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -235,15 +235,31 @@ internal virtual ValidationResult<ValidatedConditions> ValidateConditions(
if (audienceRestriction.Audiences is not List<string> audiencesAsList)
audiencesAsList = [.. audienceRestriction.Audiences];

var audienceValidationResult = validationParameters.AudienceValidator(
audiencesAsList,
samlToken,
validationParameters,
callContext);
if (!audienceValidationResult.IsValid)
ValidationResult<string> audienceValidationResult;

try
{
StackFrames.AudienceValidationFailed ??= new StackFrame(true);
return audienceValidationResult.UnwrapError().AddStackFrame(StackFrames.AudienceValidationFailed);
audienceValidationResult = validationParameters.AudienceValidator(
audiencesAsList,
samlToken,
validationParameters,
callContext);

if (!audienceValidationResult.IsValid)
return audienceValidationResult.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 AudienceValidationError(
new MessageDetail(Tokens.LogMessages.IDX10270),
ValidationFailureType.AudienceValidatorThrew,
typeof(SecurityTokenInvalidAudienceException),
ValidationError.GetCurrentStackFrame(),
audiencesAsList,
validationParameters.ValidAudiences,
ex);
}

// Audience is valid, save it for later.
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.IDX10270 = "IDX10270: AudienceValidationDelegate 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 @@ -61,6 +62,7 @@ static Microsoft.IdentityModel.Tokens.TokenTypeValidationError.NullParameter(str
static Microsoft.IdentityModel.Tokens.Utility.SerializeAsSingleCommaDelimitedString(System.Collections.Generic.IList<string> strings) -> string
static Microsoft.IdentityModel.Tokens.ValidationError.GetCurrentStackFrame(string filePath = "", int lineNumber = 0, int skipFrames = 1) -> System.Diagnostics.StackFrame
static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.AlgorithmValidatorThrew -> Microsoft.IdentityModel.Tokens.ValidationFailureType
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.NoTokenAudiencesProvided -> 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 IDX10270 = "IDX10270: AudienceValidationDelegate 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 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 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(GenerateAudienceExtensibilityTestCases),
parameters: ["JWT", 2],
DisableDiscoveryEnumeration = true)]
public async Task ValidateTokenAsync_AudienceValidator_Extensibility(
AudienceExtensibilityTheoryData theoryData)
{
await ExtensibilityTesting.ValidateTokenAsync_Extensibility(
theoryData,
this,
nameof(ValidateTokenAsync_AudienceValidator_Extensibility));
}

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

using System;
using System.Collections.Generic;
using Microsoft.IdentityModel.Tokens;

#nullable enable
namespace Microsoft.IdentityModel.TestUtils
{
internal class CustomAudienceValidationDelegates
{
internal static ValidationResult<string> CustomAudienceValidatorDelegate(
IList<string> tokenAudiences,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
// Returns a CustomAudienceValidationError : AudienceValidationError
return new CustomAudienceValidationError(
new MessageDetail(nameof(CustomAudienceValidatorDelegate), null),
ValidationFailureType.AudienceValidationFailed,
typeof(SecurityTokenInvalidAudienceException),
ValidationError.GetCurrentStackFrame(),
tokenAudiences,
null);
}

internal static ValidationResult<string> CustomAudienceValidatorCustomExceptionDelegate(
IList<string> tokenAudiences,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new CustomAudienceValidationError(
new MessageDetail(nameof(CustomAudienceValidatorCustomExceptionDelegate), null),
ValidationFailureType.AudienceValidationFailed,
typeof(CustomSecurityTokenInvalidAudienceException),
ValidationError.GetCurrentStackFrame(),
tokenAudiences,
null);
}

internal static ValidationResult<string> CustomAudienceValidatorCustomExceptionCustomFailureTypeDelegate(
IList<string> tokenAudiences,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new CustomAudienceValidationError(
new MessageDetail(nameof(CustomAudienceValidatorCustomExceptionCustomFailureTypeDelegate), null),
CustomAudienceValidationError.CustomAudienceValidationFailureType,
typeof(CustomSecurityTokenInvalidAudienceException),
ValidationError.GetCurrentStackFrame(),
tokenAudiences,
null);
}

internal static ValidationResult<string> CustomAudienceValidatorUnknownExceptionDelegate(
IList<string> tokenAudiences,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new CustomAudienceValidationError(
new MessageDetail(nameof(CustomAudienceValidatorUnknownExceptionDelegate), null),
ValidationFailureType.AudienceValidationFailed,
typeof(NotSupportedException),
ValidationError.GetCurrentStackFrame(),
tokenAudiences,
null);
}

internal static ValidationResult<string> CustomAudienceValidatorWithoutGetExceptionOverrideDelegate(
IList<string> tokenAudiences,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new CustomAudienceWithoutGetExceptionValidationOverrideError(
new MessageDetail(nameof(CustomAudienceValidatorWithoutGetExceptionOverrideDelegate), null),
typeof(CustomSecurityTokenInvalidAudienceException),
ValidationError.GetCurrentStackFrame(),
tokenAudiences,
null);
}

internal static ValidationResult<string> AudienceValidatorDelegate(
IList<string> tokenAudiences,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new AudienceValidationError(
new MessageDetail(nameof(AudienceValidatorDelegate), null),
ValidationFailureType.AudienceValidationFailed,
typeof(SecurityTokenInvalidAudienceException),
ValidationError.GetCurrentStackFrame(),
tokenAudiences,
null);
}

internal static ValidationResult<string> AudienceValidatorThrows(
IList<string> tokenAudiences,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
throw new CustomSecurityTokenInvalidAudienceException(nameof(AudienceValidatorThrows), null);
}

internal static ValidationResult<string> AudienceValidatorCustomAudienceExceptionTypeDelegate(
IList<string> tokenAudiences,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new AudienceValidationError(
new MessageDetail(nameof(AudienceValidatorCustomAudienceExceptionTypeDelegate), null),
ValidationFailureType.AudienceValidationFailed,
typeof(CustomSecurityTokenInvalidAudienceException),
ValidationError.GetCurrentStackFrame(),
tokenAudiences,
null);
}

internal static ValidationResult<string> AudienceValidatorCustomExceptionTypeDelegate(
IList<string> tokenAudiences,
SecurityToken? securityToken,
ValidationParameters validationParameters,
CallContext callContext)
{
return new AudienceValidationError(
new MessageDetail(nameof(AudienceValidatorCustomExceptionTypeDelegate), null),
ValidationFailureType.AudienceValidationFailed,
typeof(CustomSecurityTokenException),
ValidationError.GetCurrentStackFrame(),
tokenAudiences,
null);
}
}
}
#nullable restore
Loading
Loading