From a275ee4209a055caa5c485ebaae4c304b1cf273a Mon Sep 17 00:00:00 2001 From: Ignacio Inglese Date: Fri, 8 Nov 2024 18:36:00 +0000 Subject: [PATCH] SAML and SAML2 new model validation: Read Token (#2980) * Added ReadToken to SamlTokenHandler returning a ValidationResult. Added log messages for the malformed case, and SamlValidationError to return the correct exception. * Added ReadToken to Saml2TokenHandler returning a ValidationResult. Added log messages for the malformed case, and Saml2ValidationError to return the correct exception. * Addressed PR feedback --- .../InternalAPI.Unshipped.txt | 15 ++- .../Saml/Exceptions/SamlValidationError.cs | 26 ++++ .../Saml/LogMessages.cs | 1 + .../SamlSecurityTokenHandler.ReadToken.cs | 57 +++++++++ ...rityTokenHandler.ValidateToken.Internal.cs | 21 +++- .../Saml2/Exceptions/Saml2ValidationError.cs | 26 ++++ .../Saml2/LogMessages.cs | 1 + .../Saml2SecurityTokenHandler.ReadToken.cs | 59 ++++++++++ ...rityTokenHandler.ValidateToken.Internal.cs | 19 +++ .../InternalAPI.Unshipped.txt | 1 + .../Validation/ValidationFailureType.cs | 6 + .../ExpectedException.cs | 12 ++ ...aml2SecurityTokenHandlerTests.ReadToken.cs | 111 ++++++++++++++++++ ...SamlSecurityTokenHandlerTests.ReadToken.cs | 111 ++++++++++++++++++ 14 files changed, 463 insertions(+), 3 deletions(-) create mode 100644 src/Microsoft.IdentityModel.Tokens.Saml/Saml/Exceptions/SamlValidationError.cs create mode 100644 src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ReadToken.cs create mode 100644 src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Exceptions/Saml2ValidationError.cs create mode 100644 src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ReadToken.cs create mode 100644 test/Microsoft.IdentityModel.Tokens.Saml.Tests/Saml2SecurityTokenHandlerTests.ReadToken.cs create mode 100644 test/Microsoft.IdentityModel.Tokens.Saml.Tests/SamlSecurityTokenHandlerTests.ReadToken.cs diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt b/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt index 057dee7277..ec74043d3d 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt +++ b/src/Microsoft.IdentityModel.Tokens.Saml/InternalAPI.Unshipped.txt @@ -1,3 +1,5 @@ +const Microsoft.IdentityModel.Tokens.Saml.LogMessages.IDX11402 = "IDX11402: Unable to read SamlSecurityToken. Exception thrown: '{0}'." -> string +const Microsoft.IdentityModel.Tokens.Saml2.LogMessages.IDX13003 = "IDX13003: Unable to read Saml2SecurityToken. Exception thrown: '{0}'." -> string Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidatedConditions Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidatedConditions.ValidatedAudience.get -> string @@ -7,13 +9,22 @@ Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidatedConditions Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidatedConditions.ValidatedLifetime.get -> Microsoft.IdentityModel.Tokens.ValidatedLifetime? Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidatedConditions.ValidatedLifetime.set -> void Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidateTokenAsync(Microsoft.IdentityModel.Tokens.Saml.SamlSecurityToken samlToken, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task> +Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidateTokenAsync(string token, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task> +Microsoft.IdentityModel.Tokens.Saml.SamlValidationError +Microsoft.IdentityModel.Tokens.Saml.SamlValidationError.SamlValidationError(Microsoft.IdentityModel.Tokens.MessageDetail MessageDetail, Microsoft.IdentityModel.Tokens.ValidationFailureType failureType, System.Type exceptionType, System.Diagnostics.StackFrame stackFrame) -> void +Microsoft.IdentityModel.Tokens.Saml.SamlValidationError.SamlValidationError(Microsoft.IdentityModel.Tokens.MessageDetail messageDetail, Microsoft.IdentityModel.Tokens.ValidationFailureType failureType, System.Type exceptionType, System.Diagnostics.StackFrame stackFrame, System.Exception innerException) -> void Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ValidateTokenAsync(Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken samlToken, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task> +Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ValidateTokenAsync(string token, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task> +Microsoft.IdentityModel.Tokens.Saml2.Saml2ValidationError +Microsoft.IdentityModel.Tokens.Saml2.Saml2ValidationError.Saml2ValidationError(Microsoft.IdentityModel.Tokens.MessageDetail MessageDetail, Microsoft.IdentityModel.Tokens.ValidationFailureType failureType, System.Type exceptionType, System.Diagnostics.StackFrame stackFrame) -> void +Microsoft.IdentityModel.Tokens.Saml2.Saml2ValidationError.Saml2ValidationError(Microsoft.IdentityModel.Tokens.MessageDetail messageDetail, Microsoft.IdentityModel.Tokens.ValidationFailureType failureType, System.Type exceptionType, System.Diagnostics.StackFrame stackFrame, System.Exception innerException) -> void +override Microsoft.IdentityModel.Tokens.Saml.SamlValidationError.GetException() -> System.Exception +override Microsoft.IdentityModel.Tokens.Saml2.Saml2ValidationError.GetException() -> System.Exception static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.IssuerValidationFailed -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.SignatureValidationFailed -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidateSignature(Microsoft.IdentityModel.Tokens.Saml.SamlSecurityToken samlToken, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult static Microsoft.IdentityModel.Tokens.Saml.SamlTokenUtilities.PopulateValidationParametersWithCurrentConfigurationAsync(Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task -Microsoft.IdentityModel.Tokens.Saml2.SamlSecurityTokenHandler.ValidateTokenAsync(SamlSecurityToken samlToken, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task> static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.AssertionConditionsNull -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.AssertionConditionsValidationFailed -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.StackFrames.AssertionNull -> System.Diagnostics.StackFrame @@ -32,4 +43,6 @@ static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrame static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.OneTimeUseValidationFailed -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.TokenNull -> System.Diagnostics.StackFrame static Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.StackFrames.TokenValidationParametersNull -> System.Diagnostics.StackFrame +virtual Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ReadSamlToken(string token, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult virtual Microsoft.IdentityModel.Tokens.Saml.SamlSecurityTokenHandler.ValidateConditions(Microsoft.IdentityModel.Tokens.Saml.SamlSecurityToken samlToken, Microsoft.IdentityModel.Tokens.ValidationParameters validationParameters, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult +virtual Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityTokenHandler.ReadSaml2Token(string token, Microsoft.IdentityModel.Tokens.CallContext callContext) -> Microsoft.IdentityModel.Tokens.ValidationResult diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/Exceptions/SamlValidationError.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/Exceptions/SamlValidationError.cs new file mode 100644 index 0000000000..48aff2a17d --- /dev/null +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/Exceptions/SamlValidationError.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Diagnostics; + +namespace Microsoft.IdentityModel.Tokens.Saml +{ + internal class SamlValidationError : ValidationError + { + internal SamlValidationError(MessageDetail messageDetail, ValidationFailureType failureType, Type exceptionType, StackFrame stackFrame, Exception innerException) : base(messageDetail, failureType, exceptionType, stackFrame, innerException) + { + } + + internal override Exception GetException() + { + if (ExceptionType == typeof(SamlSecurityTokenReadException)) + { + var exception = new SamlSecurityTokenReadException(MessageDetail.Message, InnerException); + return exception; + } + + return base.GetException(); + } + } +} diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/LogMessages.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/LogMessages.cs index 60814cdb2a..ad28653191 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/LogMessages.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/LogMessages.cs @@ -15,6 +15,7 @@ internal static class LogMessages // SecurityTokenHandler messages internal const string IDX11400 = "IDX11400: The '{0}', can only process SecurityTokens of type: '{1}'. The SecurityToken received is of type: '{2}'."; internal const string IDX11401 = "IDX11401: Unable to validate token. TokenValidationParameters.RequireAudience is true but no AudienceRestrictions were found in the inbound token."; + internal const string IDX11402 = "IDX11402: Unable to read SamlSecurityToken. Exception thrown: '{0}'."; // signature creation / validation internal const string IDX11312 = "IDX11312: Unable to validate token. A SamlSamlAttributeStatement can only have one SamlAttribute of type 'Actor'. This special SamlAttribute is used in delegation scenarios."; diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ReadToken.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ReadToken.cs new file mode 100644 index 0000000000..f9c658aaf1 --- /dev/null +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ReadToken.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Text; +using System.Xml; +using Microsoft.IdentityModel.Logging; +using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages; + +namespace Microsoft.IdentityModel.Tokens.Saml +{ + public partial class SamlSecurityTokenHandler : SecurityTokenHandler + { + /// + /// Converts a string into an instance of . + /// + /// a Saml token as a string. + /// An opaque context used to store work when working with authentication artifacts. + /// A + /// If is null or empty. + /// If 'token.Length' is greater than . + internal virtual ValidationResult ReadSamlToken(string token, CallContext callContext) + { + if (string.IsNullOrEmpty(token)) + return ValidationError.NullParameter(nameof(token), ValidationError.GetCurrentStackFrame()); + + if (token.Length > MaximumTokenSizeInBytes) + return new ValidationError( + new MessageDetail( + TokenLogMessages.IDX10209, + LogHelper.MarkAsNonPII(token.Length), + LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes)), + ValidationFailureType.TokenExceedsMaximumSize, + typeof(ArgumentOutOfRangeException), + ValidationError.GetCurrentStackFrame()); + + try + { + using (var reader = XmlDictionaryReader.CreateTextReader(Encoding.UTF8.GetBytes(token), XmlDictionaryReaderQuotas.Max)) + { + return ReadSamlToken(reader); + } + } +#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 SamlValidationError( + new MessageDetail(LogMessages.IDX11402, ex.Message), + ValidationFailureType.TokenReadingFailed, + typeof(SamlSecurityTokenReadException), + ValidationError.GetCurrentStackFrame(), + ex); + } + } + } +} diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.Internal.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.Internal.cs index 04a2d3c92e..b5115646f3 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.Internal.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml/SamlSecurityTokenHandler.ValidateToken.Internal.cs @@ -14,9 +14,26 @@ namespace Microsoft.IdentityModel.Tokens.Saml /// public partial class SamlSecurityTokenHandler : SecurityTokenHandler { -#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously internal async Task> ValidateTokenAsync( -#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously + string token, + ValidationParameters validationParameters, + CallContext callContext, + CancellationToken cancellationToken) + { + if (token is null) + return ValidationError.NullParameter(nameof(token), ValidationError.GetCurrentStackFrame()); + + if (validationParameters is null) + return ValidationError.NullParameter(nameof(validationParameters), ValidationError.GetCurrentStackFrame()); + + var tokenReadingResult = ReadSamlToken(token, callContext); + if (!tokenReadingResult.IsValid) + return tokenReadingResult.UnwrapError().AddCurrentStackFrame(); + + return await ValidateTokenAsync(tokenReadingResult.UnwrapResult(), validationParameters, callContext, cancellationToken).ConfigureAwait(false); + } + + internal async Task> ValidateTokenAsync( SamlSecurityToken samlToken, ValidationParameters validationParameters, CallContext callContext, diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Exceptions/Saml2ValidationError.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Exceptions/Saml2ValidationError.cs new file mode 100644 index 0000000000..b8f5803e23 --- /dev/null +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Exceptions/Saml2ValidationError.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Diagnostics; + +namespace Microsoft.IdentityModel.Tokens.Saml2 +{ + internal class Saml2ValidationError : ValidationError + { + internal Saml2ValidationError(MessageDetail messageDetail, ValidationFailureType failureType, Type exceptionType, StackFrame stackFrame, Exception innerException) : base(messageDetail, failureType, exceptionType, stackFrame, innerException) + { + } + + internal override Exception GetException() + { + if (ExceptionType == typeof(Saml2SecurityTokenReadException)) + { + var exception = new Saml2SecurityTokenReadException(MessageDetail.Message, InnerException); + return exception; + } + + return base.GetException(); + } + } +} diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/LogMessages.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/LogMessages.cs index c440f6694f..a0e71cf811 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/LogMessages.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/LogMessages.cs @@ -16,6 +16,7 @@ internal static class LogMessages internal const string IDX13400 = "IDX13400: The '{0}', can only process SecurityTokens of type: '{1}'. The SecurityToken received is of type: '{2}'."; internal const string IDX13001 = "IDX13001: A SAML2 assertion that specifies an AuthenticationContext DeclarationReference is not supported.To handle DeclarationReference, extend the Saml2SecurityTokenHandler and override ProcessAuthenticationStatement."; internal const string IDX13002 = "IDX13002: Unable to validate token. TokenValidationParameters.RequireAudience is true but no AudienceRestrictions were found in the inbound token."; + internal const string IDX13003 = "IDX13003: Unable to read Saml2SecurityToken. Exception thrown: '{0}'."; // signature creation / validation internal const string IDX13509 = "IDX13509: Unable to validate token, Subject is null."; diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ReadToken.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ReadToken.cs new file mode 100644 index 0000000000..cf74c5fc0b --- /dev/null +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ReadToken.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Text; +using System.Xml; +using Microsoft.IdentityModel.Logging; +using Microsoft.IdentityModel.Tokens.Saml; + +using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages; + +namespace Microsoft.IdentityModel.Tokens.Saml2 +{ + public partial class Saml2SecurityTokenHandler : SecurityTokenHandler + { + /// + /// Converts a string into an instance of . + /// + /// a Saml token as a string. + /// An opaque context used to store work when working with authentication artifacts. + /// A + /// If is null or empty. + /// If 'token.Length' is greater than . + internal virtual ValidationResult ReadSaml2Token(string token, CallContext callContext) + { + if (string.IsNullOrEmpty(token)) + return ValidationError.NullParameter(nameof(token), ValidationError.GetCurrentStackFrame()); + + if (token.Length > MaximumTokenSizeInBytes) + return new ValidationError( + new MessageDetail( + TokenLogMessages.IDX10209, + LogHelper.MarkAsNonPII(token.Length), + LogHelper.MarkAsNonPII(MaximumTokenSizeInBytes)), + ValidationFailureType.TokenReadingFailed, + typeof(ArgumentException), + ValidationError.GetCurrentStackFrame()); + + try + { + using (var reader = XmlDictionaryReader.CreateTextReader(Encoding.UTF8.GetBytes(token), XmlDictionaryReaderQuotas.Max)) + { + return ReadSaml2Token(reader); + } + } +#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 Saml2ValidationError( + new MessageDetail(LogMessages.IDX13003, ex.Message), + ValidationFailureType.TokenReadingFailed, + typeof(Saml2SecurityTokenReadException), + ValidationError.GetCurrentStackFrame(), + ex); + } + } + } +} diff --git a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.Internal.cs b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.Internal.cs index 0d23b4644f..5291cde721 100644 --- a/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.Internal.cs +++ b/src/Microsoft.IdentityModel.Tokens.Saml/Saml2/Saml2SecurityTokenHandler.ValidateToken.Internal.cs @@ -15,6 +15,25 @@ namespace Microsoft.IdentityModel.Tokens.Saml2 /// public partial class Saml2SecurityTokenHandler : SecurityTokenHandler { + internal async Task> ValidateTokenAsync( + string token, + ValidationParameters validationParameters, + CallContext callContext, + CancellationToken cancellationToken) + { + if (token is null) + return ValidationError.NullParameter(nameof(token), ValidationError.GetCurrentStackFrame()); + + if (validationParameters is null) + return ValidationError.NullParameter(nameof(validationParameters), ValidationError.GetCurrentStackFrame()); + + var tokenReadingResult = ReadSaml2Token(token, callContext); + if (!tokenReadingResult.IsValid) + return tokenReadingResult.UnwrapError().AddCurrentStackFrame(); + + return await ValidateTokenAsync(tokenReadingResult.UnwrapResult(), validationParameters, callContext, cancellationToken).ConfigureAwait(false); + } + internal async Task> ValidateTokenAsync( Saml2SecurityToken samlToken, ValidationParameters validationParameters, diff --git a/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt b/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt index 1d35266764..2ec92b086f 100644 --- a/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt +++ b/src/Microsoft.IdentityModel.Tokens/InternalAPI.Unshipped.txt @@ -34,4 +34,5 @@ static Microsoft.IdentityModel.Tokens.ValidationError.GetCurrentStackFrame(strin 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 +static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.TokenExceedsMaximumSize -> Microsoft.IdentityModel.Tokens.ValidationFailureType static readonly Microsoft.IdentityModel.Tokens.ValidationFailureType.XmlValidationFailed -> Microsoft.IdentityModel.Tokens.ValidationFailureType diff --git a/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs b/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs index 6cf24dc28c..00aba62c6e 100644 --- a/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs +++ b/src/Microsoft.IdentityModel.Tokens/Validation/ValidationFailureType.cs @@ -99,6 +99,12 @@ private class TokenReplayValidationFailure : ValidationFailureType { internal To public static readonly ValidationFailureType TokenReadingFailed = new TokenReadingFailure("TokenReadingFailed"); private class TokenReadingFailure : ValidationFailureType { internal TokenReadingFailure(string name) : base(name) { } } + /// + /// Defines a type that represents that a token exceeds the maximum size. + /// + public static readonly ValidationFailureType TokenExceedsMaximumSize = new TokenExceedsMaximumSizeFailure("TokenExceedsMaximumSize"); + private class TokenExceedsMaximumSizeFailure : ValidationFailureType { internal TokenExceedsMaximumSizeFailure(string name) : base(name) { } } + /// /// Defines a type that represents that a JWE could not be decrypted. /// diff --git a/test/Microsoft.IdentityModel.TestUtils/ExpectedException.cs b/test/Microsoft.IdentityModel.TestUtils/ExpectedException.cs index 366b357b88..6f8f717392 100644 --- a/test/Microsoft.IdentityModel.TestUtils/ExpectedException.cs +++ b/test/Microsoft.IdentityModel.TestUtils/ExpectedException.cs @@ -9,6 +9,8 @@ using System.Text.Json; using System.Xml; using Microsoft.IdentityModel.Tokens; +using Microsoft.IdentityModel.Tokens.Saml; +using Microsoft.IdentityModel.Tokens.Saml2; namespace Microsoft.IdentityModel.TestUtils { @@ -74,6 +76,16 @@ public static ExpectedException XmlException(string substringExpected = null, Ty return new ExpectedException(typeof(XmlException), substringExpected, inner); } + public static ExpectedException SamlSecurityTokenReadException(string substringExpected = null, Type inner = null, string contains = null) + { + return new ExpectedException(typeof(SamlSecurityTokenReadException), substringExpected, inner); + } + + public static ExpectedException Saml2SecurityTokenReadException(string substringExpected = null, Type inner = null, string contains = null) + { + return new ExpectedException(typeof(Saml2SecurityTokenReadException), substringExpected, inner); + } + public static ExpectedException NoExceptionExpected { get { return new ExpectedException(); } diff --git a/test/Microsoft.IdentityModel.Tokens.Saml.Tests/Saml2SecurityTokenHandlerTests.ReadToken.cs b/test/Microsoft.IdentityModel.Tokens.Saml.Tests/Saml2SecurityTokenHandlerTests.ReadToken.cs new file mode 100644 index 0000000000..d51f1f0c3b --- /dev/null +++ b/test/Microsoft.IdentityModel.Tokens.Saml.Tests/Saml2SecurityTokenHandlerTests.ReadToken.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using Xunit; +using Microsoft.IdentityModel.TestUtils; +using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages; +using Microsoft.IdentityModel.Logging; + +namespace Microsoft.IdentityModel.Tokens.Saml2.Tests +{ + public partial class Saml2SecurityTokenHandlerTests + { + [Theory, MemberData(nameof(ReadTokenTestCases), DisableDiscoveryEnumeration = true)] + public void ReadToken_ResultType(TokenReadingTheoryData theoryData) + { + CompareContext context = TestUtilities.WriteHeader($"{this}.ReadToken_ResultType", theoryData); + Saml2SecurityTokenHandler handler = new Saml2SecurityTokenHandler(); + ValidationResult result = handler.ReadSaml2Token( + theoryData.Token, + new CallContext()); + + if (result.IsValid) + { + IdentityComparer.AreEqual( + result.UnwrapResult(), + handler.ReadToken(theoryData.Token), + context); + + theoryData.ExpectedException.ProcessNoException(context); + } + else + { + ValidationError validationError = result.UnwrapError(); + IdentityComparer.AreStringsEqual( + validationError.FailureType.Name, + theoryData.Result.UnwrapError().FailureType.Name, + context); + + Exception exception = validationError.GetException(); + theoryData.ExpectedException.ProcessException(exception, context); + } + + TestUtilities.AssertFailIfErrors(context); + } + + public static TheoryData ReadTokenTestCases + { + get + { + var theoryData = new TheoryData(); + + theoryData.Add(new TokenReadingTheoryData("Valid_SAML_Token") + { + Token = ReferenceTokens.Saml2Token_Valid, + }); + + theoryData.Add(new TokenReadingTheoryData("Invalid_NullToken") + { + Token = null, + ExpectedException = ExpectedException.SecurityTokenArgumentNullException("IDX10000:"), + Result = new ValidationError( + new MessageDetail( + TokenLogMessages.IDX10000, + LogHelper.MarkAsNonPII("token")), + ValidationFailureType.NullArgument, + typeof(SecurityTokenArgumentNullException), + null) + }); + + theoryData.Add(new TokenReadingTheoryData("Invalid_EmptyToken") + { + Token = string.Empty, + ExpectedException = ExpectedException.SecurityTokenArgumentNullException("IDX10000:"), + Result = new ValidationError( + new MessageDetail( + TokenLogMessages.IDX10000, + LogHelper.MarkAsNonPII("token")), + ValidationFailureType.NullArgument, + typeof(SecurityTokenArgumentNullException), + null) + }); + + theoryData.Add(new TokenReadingTheoryData("Invalid_MalformedToken") + { + Token = ReferenceTokens.Saml2Token_MissingVersion, + ExpectedException = ExpectedException.Saml2SecurityTokenReadException("IDX13003:", inner: typeof(Saml2SecurityTokenReadException)), + Result = new ValidationError( + new MessageDetail(LogMessages.IDX13003, "exception message"), + ValidationFailureType.TokenReadingFailed, + typeof(Saml2SecurityTokenReadException), + null), + }); + + return theoryData; + } + } + } + + public class TokenReadingTheoryData : TheoryDataBase + { + public TokenReadingTheoryData(string testId) + { + TestId = testId; + } + + public string Token { get; set; } + + internal ValidationResult Result { get; set; } + } +} diff --git a/test/Microsoft.IdentityModel.Tokens.Saml.Tests/SamlSecurityTokenHandlerTests.ReadToken.cs b/test/Microsoft.IdentityModel.Tokens.Saml.Tests/SamlSecurityTokenHandlerTests.ReadToken.cs new file mode 100644 index 0000000000..a62c5c4938 --- /dev/null +++ b/test/Microsoft.IdentityModel.Tokens.Saml.Tests/SamlSecurityTokenHandlerTests.ReadToken.cs @@ -0,0 +1,111 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using Xunit; +using Microsoft.IdentityModel.TestUtils; +using TokenLogMessages = Microsoft.IdentityModel.Tokens.LogMessages; +using Microsoft.IdentityModel.Logging; + +namespace Microsoft.IdentityModel.Tokens.Saml.Tests +{ + public partial class SamlSecurityTokenHandlerTests + { + [Theory, MemberData(nameof(ReadTokenTestCases), DisableDiscoveryEnumeration = true)] + public void ReadToken_ResultType(TokenReadingTheoryData theoryData) + { + CompareContext context = TestUtilities.WriteHeader($"{this}.ReadToken_ResultType", theoryData); + SamlSecurityTokenHandler handler = new SamlSecurityTokenHandler(); + ValidationResult result = handler.ReadSamlToken( + theoryData.Token, + new CallContext()); + + if (result.IsValid) + { + IdentityComparer.AreEqual( + result.UnwrapResult(), + handler.ReadToken(theoryData.Token), + context); + + theoryData.ExpectedException.ProcessNoException(context); + } + else + { + ValidationError validationError = result.UnwrapError(); + IdentityComparer.AreStringsEqual( + validationError.FailureType.Name, + theoryData.Result.UnwrapError().FailureType.Name, + context); + + Exception exception = validationError.GetException(); + theoryData.ExpectedException.ProcessException(exception, context); + } + + TestUtilities.AssertFailIfErrors(context); + } + + public static TheoryData ReadTokenTestCases + { + get + { + var theoryData = new TheoryData(); + + theoryData.Add(new TokenReadingTheoryData("Valid_SAML_Token") + { + Token = ReferenceTokens.SamlToken_Valid, + }); + + theoryData.Add(new TokenReadingTheoryData("Invalid_NullToken") + { + Token = null, + ExpectedException = ExpectedException.SecurityTokenArgumentNullException("IDX10000:"), + Result = new ValidationError( + new MessageDetail( + TokenLogMessages.IDX10000, + LogHelper.MarkAsNonPII("token")), + ValidationFailureType.NullArgument, + typeof(SecurityTokenArgumentNullException), + null) + }); + + theoryData.Add(new TokenReadingTheoryData("Invalid_EmptyToken") + { + Token = string.Empty, + ExpectedException = ExpectedException.SecurityTokenArgumentNullException("IDX10000:"), + Result = new ValidationError( + new MessageDetail( + TokenLogMessages.IDX10000, + LogHelper.MarkAsNonPII("token")), + ValidationFailureType.NullArgument, + typeof(SecurityTokenArgumentNullException), + null) + }); + + theoryData.Add(new TokenReadingTheoryData("Invalid_MalformedToken") + { + Token = ReferenceTokens.SamlToken_MissingMajorVersion, + ExpectedException = ExpectedException.SamlSecurityTokenReadException("IDX11402:", inner: typeof(SamlSecurityTokenReadException)), + Result = new ValidationError( + new MessageDetail(LogMessages.IDX11402, "exception message"), + ValidationFailureType.TokenReadingFailed, + typeof(SamlSecurityTokenReadException), + null), + }); + + return theoryData; + } + } + } + + public class TokenReadingTheoryData : TheoryDataBase + { + public TokenReadingTheoryData(string testId) + { + TestId = testId; + } + + public string Token { get; set; } + + internal ValidationResult Result { get; set; } + } +}