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

Validate Audience for SAML2TokenHandler with New Model #2863

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
18 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
@@ -0,0 +1,138 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

#nullable enable
namespace Microsoft.IdentityModel.Tokens.Saml2
{
/// <summary>
/// A <see cref="SecurityTokenHandler"/> designed for creating and validating Saml2 Tokens. See: http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
/// </summary>
public partial class Saml2SecurityTokenHandler : SecurityTokenHandler
{

FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
internal async Task<ValidationResult<ValidatedToken>> ValidateTokenAsync(
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
Saml2SecurityToken samlToken,
ValidationParameters validationParameters,
CallContext callContext,
#pragma warning disable CA1801 // Review unused parameters
CancellationToken cancellationToken)
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
#pragma warning restore CA1801 // Review unused parameters
{
var conditionsResult = ValidateConditions(samlToken, validationParameters, callContext);

if (!conditionsResult.IsSuccess)
{
return conditionsResult.UnwrapError().AddStackFrame(new StackFrame(true));
}

//These TODO's follow the pattern of the current ValidateToken methods. They should be implemented in the future.
//TODO: ValidateSubject() - Skip for now
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
//TODO: ValidateIssuer()
//TODO: ValidateIssuerSecurityKey()...etc

return new ValidatedToken(samlToken, this, validationParameters);
}


FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved

// ValidatedConditions is basically a named tuple but using a record struct better expresses the intent.
internal record struct ValidatedConditions(string? ValidatedAudience, ValidatedLifetime? ValidatedLifetime);

internal virtual ValidationResult<ValidatedConditions> ValidateConditions(Saml2SecurityToken samlToken, ValidationParameters validationParameters, CallContext callContext)
{
if (samlToken == null)
return ValidationError.NullParameter(nameof(samlToken), new System.Diagnostics.StackFrame(true));
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved

if (validationParameters == null)
return ValidationError.NullParameter(nameof(validationParameters), new System.Diagnostics.StackFrame(true));

if (samlToken.Assertion == null)
return ValidationError.NullParameter(nameof(samlToken.Assertion), new System.Diagnostics.StackFrame(true));

// TokenValidationParameters.RequireAudience is only used for SAML.
// Should we add this to ValidationParameters?
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
// Should it be just a field in Saml2SecurityTokenHandler?
bool requireAudience = true;

if (samlToken.Assertion.Conditions == null)
{
if (requireAudience)
return new ValidationError(
new MessageDetail(LogMessages.IDX13002),
ValidationFailureType.AudienceValidationFailed,
typeof(Saml2SecurityTokenException),
new System.Diagnostics.StackFrame(true));

return new ValidatedConditions(null, null); // no error occurred. There is no validated audience or lifetime.
}

var lifetimeValidationResult = validationParameters.LifetimeValidator(
samlToken.Assertion.Conditions.NotBefore, samlToken.Assertion.Conditions.NotOnOrAfter, samlToken, validationParameters, callContext);
if (!lifetimeValidationResult.IsSuccess)
return lifetimeValidationResult.UnwrapError();

if (samlToken.Assertion.Conditions.OneTimeUse)
{
//ValidateOneTimeUseCondition(samlToken, validationParameters);
// We can keep an overridable method for this, or rely on the TokenReplayValidator delegate.
var oneTimeUseValidationResult = validationParameters.TokenReplayValidator(
samlToken.Assertion.Conditions.NotOnOrAfter, samlToken.Assertion.CanonicalString, validationParameters, callContext);
if (!oneTimeUseValidationResult.IsSuccess)
return oneTimeUseValidationResult.UnwrapError();
}

if (samlToken.Assertion.Conditions.ProxyRestriction != null)
{
//throw LogExceptionMessage(new SecurityTokenValidationException(LogMessages.IDX13511));
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
var proxyValidationError = ValidateProxyRestriction(samlToken, validationParameters, callContext);
if (proxyValidationError is not null)
return proxyValidationError;
}

string? validatedAudience = null;
foreach (var audienceRestriction in samlToken.Assertion.Conditions.AudienceRestrictions)
{
// AudienceRestriction.Audiences is a List<string> but returned as ICollection<string>
// no conversion occurs, ToList() is never called but we have to account for the possibility.
if (!(audienceRestriction.Audiences is List<string> audiencesAsList))
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
audiencesAsList = audienceRestriction.Audiences.ToList();

var audienceValidationResult = validationParameters.AudienceValidator(
audiencesAsList, samlToken, validationParameters, callContext);
if (!audienceValidationResult.IsSuccess)
return audienceValidationResult.UnwrapError();

// Audience is valid, save it for later.
validatedAudience = audienceValidationResult.UnwrapResult();
brentschmaltz marked this conversation as resolved.
Show resolved Hide resolved
}

if (requireAudience && validatedAudience is null)
{
return new ValidationError(
new MessageDetail(LogMessages.IDX13002),
ValidationFailureType.AudienceValidationFailed,
typeof(Saml2SecurityTokenException),
new System.Diagnostics.StackFrame(true));
}

return new ValidatedConditions(validatedAudience, lifetimeValidationResult.UnwrapResult()); // no error occurred. There is nothing else to return.
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
}

#pragma warning disable CA1801 // Review unused parameters
internal virtual ValidationError? ValidateProxyRestriction(Saml2SecurityToken samlToken, ValidationParameters validationParameters, CallContext callContext)
#pragma warning restore CA1801 // Review unused parameters
{
// return an error, or ignore and allow overriding?
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
return null;
}
}
}
#nullable restore
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ namespace Microsoft.IdentityModel.Tokens.Saml2
/// <summary>
/// A <see cref="SecurityTokenHandler"/> designed for creating and validating Saml2 Tokens. See: http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
/// </summary>
public class Saml2SecurityTokenHandler : SecurityTokenHandler
public partial class Saml2SecurityTokenHandler : SecurityTokenHandler
{
private const string _actor = "Actor";
private const string _className = "Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler";
Expand Down Expand Up @@ -1048,99 +1048,6 @@ protected virtual void ValidateConditions(Saml2SecurityToken samlToken, TokenVal
throw LogExceptionMessage(new Saml2SecurityTokenException(LogMessages.IDX13002));
}

#nullable enable
// ValidatedConditions is basically a named tuple but using a record struct better expresses the intent.
internal record struct ValidatedConditions(string? ValidatedAudience, ValidatedLifetime? ValidatedLifetime);

internal virtual ValidationResult<ValidatedConditions> ValidateConditions(Saml2SecurityToken samlToken, ValidationParameters validationParameters, CallContext callContext)
{
if (samlToken == null)
return ValidationError.NullParameter(nameof(samlToken), new System.Diagnostics.StackFrame(true));

if (validationParameters == null)
return ValidationError.NullParameter(nameof(validationParameters), new System.Diagnostics.StackFrame(true));

if (samlToken.Assertion == null)
return ValidationError.NullParameter(nameof(samlToken.Assertion), new System.Diagnostics.StackFrame(true));

// TokenValidationParameters.RequireAudience is only used for SAML.
// Should we add this to ValidationParameters?
// Should it be just a field in Saml2SecurityTokenHandler?
bool requireAudience = true;

if (samlToken.Assertion.Conditions == null)
{
if (requireAudience)
return new ValidationError(
new MessageDetail(LogMessages.IDX13002),
ValidationFailureType.AudienceValidationFailed,
typeof(Saml2SecurityTokenException),
new System.Diagnostics.StackFrame(true));

return new ValidatedConditions(null, null); // no error occurred. There is no validated audience or lifetime.
}

var lifetimeValidationResult = validationParameters.LifetimeValidator(
samlToken.Assertion.Conditions.NotBefore, samlToken.Assertion.Conditions.NotOnOrAfter, samlToken, validationParameters, callContext);
if (!lifetimeValidationResult.IsSuccess)
return lifetimeValidationResult.UnwrapError();

if (samlToken.Assertion.Conditions.OneTimeUse)
{
//ValidateOneTimeUseCondition(samlToken, validationParameters);
// We can keep an overridable method for this, or rely on the TokenReplayValidator delegate.
var oneTimeUseValidationResult = validationParameters.TokenReplayValidator(
samlToken.Assertion.Conditions.NotOnOrAfter, samlToken.Assertion.CanonicalString, validationParameters, callContext);
if (!oneTimeUseValidationResult.IsSuccess)
return oneTimeUseValidationResult.UnwrapError();
}

if (samlToken.Assertion.Conditions.ProxyRestriction != null)
{
//throw LogExceptionMessage(new SecurityTokenValidationException(LogMessages.IDX13511));
var proxyValidationError = ValidateProxyRestriction(samlToken, validationParameters, callContext);
if (proxyValidationError is not null)
return proxyValidationError;
}

string? validatedAudience = null;
foreach (var audienceRestriction in samlToken.Assertion.Conditions.AudienceRestrictions)
{
// AudienceRestriction.Audiences is a List<string> but returned as ICollection<string>
// no conversion occurs, ToList() is never called but we have to account for the possibility.
if (!(audienceRestriction.Audiences is List<string> audiencesAsList))
audiencesAsList = audienceRestriction.Audiences.ToList();

var audienceValidationResult = validationParameters.AudienceValidator(
audiencesAsList, samlToken, validationParameters, callContext);
if (!audienceValidationResult.IsSuccess)
return audienceValidationResult.UnwrapError();

// Audience is valid, save it for later.
validatedAudience = audienceValidationResult.UnwrapResult();
}

if (requireAudience && validatedAudience is null)
{
return new ValidationError(
new MessageDetail(LogMessages.IDX13002),
ValidationFailureType.AudienceValidationFailed,
typeof(Saml2SecurityTokenException),
new System.Diagnostics.StackFrame(true));
}

return new ValidatedConditions(validatedAudience, lifetimeValidationResult.UnwrapResult()); // no error occurred. There is nothing else to return.
}

#pragma warning disable CA1801 // Review unused parameters
internal virtual ValidationError? ValidateProxyRestriction(Saml2SecurityToken samlToken, ValidationParameters validationParameters, CallContext callContext)
#pragma warning restore CA1801 // Review unused parameters
{
// return an error, or ignore and allow overriding?
return null;
}
#nullable restore

/// <summary>
/// Validates the OneTimeUse condition.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.IdentityModel.TestUtils;
using Microsoft.IdentityModel.Tokens.Saml2;
using Xunit;

namespace Microsoft.IdentityModel.Tokens.Saml.Tests
{
#nullable enable
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
public partial class Saml2SecurityTokenHandlerTests
{

[Theory, MemberData(nameof(ValidateTokenAsync_Audience_TestCases), DisableDiscoveryEnumeration = true)]
public async Task ValidateTokenAsync_Audience(ValidateTokenAsyncAudienceTheoryData theoryData)
{
var context = TestUtilities.WriteHeader($"{this}.ValidateTokenAsync_Audience", theoryData);

Saml2SecurityTokenHandler saml2TokenHandler = new Saml2SecurityTokenHandler();

var saml2Token = CreateToken(theoryData.Audience!, theoryData.Saml2Condition!);

var validationParameters = CreateTokenValidationParameters(
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
new List<string> { theoryData.Audience! },
saml2Token,
false); //TODO: continue looking into improving this approach

await ValidateAndCompareResults(saml2Token, validationParameters, theoryData, context);

TestUtilities.AssertFailIfErrors(context);
}

public static TheoryData<ValidateTokenAsyncAudienceTheoryData> ValidateTokenAsync_Audience_TestCases
{
get
{
return new TheoryData<ValidateTokenAsyncAudienceTheoryData>
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
{
new ValidateTokenAsyncAudienceTheoryData("Valid_AudiencesMatch")
{
Audience = Default.Audience,
Saml2Condition = new Saml2Conditions
{
OneTimeUse = false,
NotOnOrAfter = DateTime.UtcNow.AddMinutes(5),
},
ValidationParameters = CreateValidationParameters([Default.Audience])
}
};

static ValidationParameters CreateValidationParameters(
List<string> audiences,
bool ignoreTrailingSlashWhenValidatingAudience = false)
{
ValidationParameters validationParameters = new ValidationParameters();
audiences.ForEach(audience => validationParameters.ValidAudiences.Add(audience));
validationParameters.IgnoreTrailingSlashWhenValidatingAudience = ignoreTrailingSlashWhenValidatingAudience;
validationParameters.LifetimeValidator = SkipValidationDelegates.SkipLifetimeValidation;
validationParameters.TokenReplayValidator = SkipValidationDelegates.SkipTokenReplayValidation;

return validationParameters;
}
}
}

public class ValidateTokenAsyncAudienceTheoryData : ValidateTokenAsyncBaseTheoryData
{
public ValidateTokenAsyncAudienceTheoryData(string testId) : base(testId) { }

public string? Audience { get; internal set; } = Default.Audience;

public Saml2Conditions? Saml2Condition { get; internal set; }

public Saml2SecurityToken? Saml2SecurityToken { get; internal set; }

public bool ignoreTrailingSlashWhenValidatingAudience { get; internal set; }
}

private static Saml2SecurityToken CreateToken(string audience, Saml2Conditions saml2Conditions)
{
Saml2SecurityTokenHandler saml2TokenHandler = new Saml2SecurityTokenHandler();

SecurityTokenDescriptor securityTokenDescriptor = new SecurityTokenDescriptor
{
Expires = DateTime.UtcNow + TimeSpan.FromDays(1),
Audience = audience,
SigningCredentials = Default.AsymmetricSigningCredentials,
Issuer = Default.Issuer,
Subject = Default.SamlClaimsIdentity
};

Saml2SecurityToken saml2Token = (Saml2SecurityToken)saml2TokenHandler.CreateToken(securityTokenDescriptor);
/*
if (saml2Conditions != null)
saml2Token.Assertion.Conditions = saml2Conditions;*/ //TODO: Figure out how to adapt thisto more complex scenarios

return saml2Token;
}

private static TokenValidationParameters CreateTokenValidationParameters(
List<string>? audiences,
Saml2SecurityToken saml2SecurityToken,
bool ignoreTrailingSlashWhenValidatingAudience = false)
{
return new TokenValidationParameters
{
ValidateAudience = true,
ValidateIssuer = false,
ValidateLifetime = false,
ValidateTokenReplay = false,
ValidateIssuerSigningKey = false,
RequireSignedTokens = false,
ValidAudiences = audiences,
FuPingFranco marked this conversation as resolved.
Show resolved Hide resolved
IgnoreTrailingSlashWhenValidatingAudience = ignoreTrailingSlashWhenValidatingAudience,
SignatureValidator = delegate (string token, TokenValidationParameters validationParameters)
{
return saml2SecurityToken;
}
};
}
}
}
#nullable restore
Loading
Loading