From fc4fd512e532dd3776be01e21a333a09c4e4cdb1 Mon Sep 17 00:00:00 2001 From: pieroviano Date: Tue, 15 Sep 2026 03:04:04 +0300 Subject: [PATCH] Restrict only JWS signing algorithms and harden the FAPI 2.0 server profile validation --- .../OpenIddictAlgorithmHelpers.cs | 64 +++++ .../OpenIddictResources.resx | 6 + .../OpenIddictClientConfiguration.cs | 5 +- .../OpenIddictClientHandlers.Protection.cs | 3 +- .../OpenIddictServerBuilder.cs | 8 +- .../OpenIddictServerConfiguration.cs | 31 +++ .../OpenIddictServerHandlers.Fapi.cs | 13 +- ...OpenIddictValidationHandlers.Protection.cs | 3 +- ...lientAspNetCoreBffDistributedCacheTests.cs | 40 ++- .../OpenIddictClientHandlersTests.Fapi.cs | 44 +++- ...ientHandlersTests.IntrospectionResponse.cs | 15 +- .../OpenIddictServerIntegrationTests.Fapi.cs | 228 ++++++++++++++++-- ...rIntegrationTests.IntrospectionResponse.cs | 9 +- .../OpenIddictServerFapi2ProfileTests.cs | 82 +++++++ ...tionHandlersTests.IntrospectionResponse.cs | 15 +- 15 files changed, 519 insertions(+), 47 deletions(-) create mode 100644 shared/OpenIddict.Extensions/IdentityModel/OpenIddictAlgorithmHelpers.cs diff --git a/shared/OpenIddict.Extensions/IdentityModel/OpenIddictAlgorithmHelpers.cs b/shared/OpenIddict.Extensions/IdentityModel/OpenIddictAlgorithmHelpers.cs new file mode 100644 index 00000000..67a7bea5 --- /dev/null +++ b/shared/OpenIddict.Extensions/IdentityModel/OpenIddictAlgorithmHelpers.cs @@ -0,0 +1,64 @@ +/* + * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) + * See https://github.com/openiddict/openiddict-core for more information concerning + * the license and the contributors participating to this project. + */ + +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; + +namespace OpenIddict.Extensions; + +/// +/// Exposes the helpers used to restrict the algorithms accepted when validating JSON Web Tokens. +/// +internal static class OpenIddictAlgorithmHelpers +{ + /// + /// Creates an that only restricts the JWS signing algorithms. + /// + /// + /// Unlike , which IdentityModel also applies to + /// the JWE key management and content encryption algorithms ("alg"/"enc" headers of encrypted tokens), + /// the returned validator ignores the algorithms of encrypted tokens (which are implicitly restricted + /// by the configured decryption keys) and only applies the list to the signature of the (inner) JWS. + /// If already defines an algorithm validator or valid algorithms, + /// they are also enforced. + /// + /// The allowed signing algorithms. + /// The token validation parameters whose existing restrictions must be preserved. + /// The algorithm validator. + public static AlgorithmValidator CreateSigningAlgorithmValidator( + IEnumerable algorithms, TokenValidationParameters? parameters = null) + { + ArgumentNullException.ThrowIfNull(algorithms); + + var allowed = new HashSet(algorithms, StringComparer.Ordinal); + var validator = parameters?.AlgorithmValidator; + var list = parameters?.ValidAlgorithms?.ToArray(); + + return (algorithm, key, token, parameters) => + { + if (validator is not null) + { + if (!validator(algorithm, key, token, parameters)) + { + return false; + } + } + + else if (list is { Length: > 0 } && !list.Contains(algorithm, StringComparer.Ordinal)) + { + return false; + } + + // Note: the "alg" and "enc" headers of JWE tokens are not signing algorithms. + if (token is JsonWebToken { IsEncrypted: true }) + { + return true; + } + + return allowed.Contains(algorithm); + }; + } +} diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx index 1ec4ed7d..72eb22c4 100644 --- a/src/OpenIddict.Abstractions/OpenIddictResources.resx +++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx @@ -2306,6 +2306,12 @@ Make sure the authorization server supports 'private_key_jwt', 'tls_client_auth' Distributed caching was enabled in the backend-for-frontend options but no IDistributedCache implementation was registered in the dependency injection container. To register a distributed cache, use 'services.AddDistributedMemoryCache()' or a cache provider package (e.g 'services.AddStackExchangeRedisCache()'). + + The FAPI 2.0 security profile requires rejecting proofs issued more than 60 seconds in the future: the DPoP proof lifetime cannot exceed 60 seconds when the profile is enforced. + + + No asymmetric signing credentials using one of the introspection response signing algorithms allowed in the server options were registered. + The security token is missing. diff --git a/src/OpenIddict.Client/OpenIddictClientConfiguration.cs b/src/OpenIddict.Client/OpenIddictClientConfiguration.cs index ec29c4b7..e6df1ebd 100644 --- a/src/OpenIddict.Client/OpenIddictClientConfiguration.cs +++ b/src/OpenIddict.Client/OpenIddictClientConfiguration.cs @@ -405,7 +405,10 @@ public sealed class OpenIddictClientConfiguration : IPostConfigureOptions 0) { - parameters.ValidAlgorithms = [.. context.Registration.IntrospectionResponseSigningAlgorithms]; + parameters.AlgorithmValidator = OpenIddictAlgorithmHelpers.CreateSigningAlgorithmValidator( + context.Registration.IntrospectionResponseSigningAlgorithms, parameters); } } diff --git a/src/OpenIddict.Server/OpenIddictServerBuilder.cs b/src/OpenIddict.Server/OpenIddictServerBuilder.cs index fc8f7ce7..502ba912 100644 --- a/src/OpenIddict.Server/OpenIddictServerBuilder.cs +++ b/src/OpenIddict.Server/OpenIddictServerBuilder.cs @@ -2311,13 +2311,15 @@ public sealed class OpenIddictServerBuilder /// JWTs sent by clients (client assertions, request objects) must use PS256, ES256 or EdDSA /// and the RSA signing credentials of the server use PS256; /// authorization codes expire after at most 60 seconds and request URIs after less than 600 seconds; - /// pushed authorization requests must include an https (or loopback) redirect_uri; - /// rolling refresh tokens are disabled by default, as recommended by the profile. + /// pushed authorization requests must include an https (or loopback IP literal http) redirect_uri; + /// rolling refresh tokens are disabled, as required by the profile (section 5.3.2.1, item 10). Since the + /// profile tolerates refresh token rotation in extraordinary circumstances, re-enabling it is not reported as an error. /// /// /// /// Note: settings that conflict with the profile (e.g enabling the password flow or setting a longer - /// authorization code lifetime after calling this method) are reported when the options are validated. + /// authorization code lifetime or a DPoP proof lifetime exceeding 60 seconds after calling this method) + /// are reported when the options are validated. /// /// The instance. public OpenIddictServerBuilder EnableFapi2SecurityProfile() diff --git a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs index 164481aa..2a3ce1b4 100644 --- a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs +++ b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs @@ -615,6 +615,15 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions OpenIddictServerFapi2Profile.MaximumFutureDateOffset) + { + builder.AddError(SR.GetResourceString(SR.ID0989)); + } + + // Note: rolling refresh tokens are disabled by EnableFapi2SecurityProfile() but are not rejected here, + // as the profile allows refresh token rotation "in extraordinary circumstances" (section 5.3.2.1, item 10). } if (options.EnableFapi2MessageSigningProfile && (!options.EnableFapi2SecurityProfile || @@ -747,6 +756,28 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions 0 && + options.SigningCredentials.Exists(static credentials => credentials.Key is AsymmetricSecurityKey) && + !options.SigningCredentials.Exists(credentials => credentials.Key is AsymmetricSecurityKey && + options.IntrospectionResponseSigningAlgorithms.Contains(credentials.Algorithm switch + { + SecurityAlgorithms.EcdsaSha256Signature => SecurityAlgorithms.EcdsaSha256, + SecurityAlgorithms.EcdsaSha384Signature => SecurityAlgorithms.EcdsaSha384, + SecurityAlgorithms.EcdsaSha512Signature => SecurityAlgorithms.EcdsaSha512, + SecurityAlgorithms.RsaSha256Signature => SecurityAlgorithms.RsaSha256, + SecurityAlgorithms.RsaSha384Signature => SecurityAlgorithms.RsaSha384, + SecurityAlgorithms.RsaSha512Signature => SecurityAlgorithms.RsaSha512, + SecurityAlgorithms.RsaSsaPssSha256Signature => SecurityAlgorithms.RsaSsaPssSha256, + SecurityAlgorithms.RsaSsaPssSha384Signature => SecurityAlgorithms.RsaSsaPssSha384, + SecurityAlgorithms.RsaSsaPssSha512Signature => SecurityAlgorithms.RsaSsaPssSha512, + string algorithm => algorithm + }))) + { + builder.AddError(SR.GetResourceString(SR.ID0990)); + } + var now = options.TimeProvider.GetUtcNow().LocalDateTime; // If all the registered encryption credentials are backed by a X.509 certificate, at least one of them must be valid. diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Fapi.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Fapi.cs index 7a66e4d2..cae861f0 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.Fapi.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Fapi.cs @@ -1,4 +1,4 @@ -/* +/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/openiddict/openiddict-core for more information concerning * the license and the contributors participating to this project. @@ -215,8 +215,12 @@ public static partial class OpenIddictServerHandlers } // Note: the redirect_uri was already validated as an absolute URI at this stage. + // + // Only loopback IP literals are accepted for http redirect URIs (RFC 8252, section 7.3): since "localhost" + // is a DNS name that may not resolve to the loopback interface, it is not accepted (RFC 8252, section 8.3). if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out Uri? uri) && - string.Equals(uri.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) && !uri.IsLoopback) + string.Equals(uri.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) && + !(uri.HostNameType is UriHostNameType.IPv4 or UriHostNameType.IPv6 && uri.IsLoopback)) { context.Logger.LogInformation(6760, SR.GetResourceString(SR.ID6760), SR.FormatID2484(Parameters.RedirectUri)); @@ -259,7 +263,10 @@ public static partial class OpenIddictServerHandlers return ValueTask.CompletedTask; } - context.TokenValidationParameters.ValidAlgorithms = OpenIddictServerFapi2Profile.SigningAlgorithms; + // Note: TokenValidationParameters.ValidAlgorithms is not used as IdentityModel also applies it to the + // key management and content encryption algorithms of encrypted request objects (RFC 7516). + context.TokenValidationParameters.AlgorithmValidator = OpenIddictAlgorithmHelpers.CreateSigningAlgorithmValidator( + OpenIddictServerFapi2Profile.SigningAlgorithms, context.TokenValidationParameters); return ValueTask.CompletedTask; } diff --git a/src/OpenIddict.Validation/OpenIddictValidationHandlers.Protection.cs b/src/OpenIddict.Validation/OpenIddictValidationHandlers.Protection.cs index b6029d61..11dfb562 100644 --- a/src/OpenIddict.Validation/OpenIddictValidationHandlers.Protection.cs +++ b/src/OpenIddict.Validation/OpenIddictValidationHandlers.Protection.cs @@ -146,7 +146,8 @@ public static partial class OpenIddictValidationHandlers if (context.Options.IntrospectionResponseSigningAlgorithms.Count is > 0 && context.ValidTokenTypes.Count is 1 && context.ValidTokenTypes.Contains(TokenTypeIdentifiers.Private.IntrospectionResponse)) { - parameters.ValidAlgorithms = [.. context.Options.IntrospectionResponseSigningAlgorithms]; + parameters.AlgorithmValidator = OpenIddictAlgorithmHelpers.CreateSigningAlgorithmValidator( + context.Options.IntrospectionResponseSigningAlgorithms, parameters); } context.SecurityTokenHandler = context.Options.JsonWebTokenHandler; diff --git a/test/OpenIddict.Client.AspNetCore.Bff.Tests/OpenIddictClientAspNetCoreBffDistributedCacheTests.cs b/test/OpenIddict.Client.AspNetCore.Bff.Tests/OpenIddictClientAspNetCoreBffDistributedCacheTests.cs index c71e9295..3254e645 100644 --- a/test/OpenIddict.Client.AspNetCore.Bff.Tests/OpenIddictClientAspNetCoreBffDistributedCacheTests.cs +++ b/test/OpenIddict.Client.AspNetCore.Bff.Tests/OpenIddictClientAspNetCoreBffDistributedCacheTests.cs @@ -214,6 +214,41 @@ public class OpenIddictClientAspNetCoreBffDistributedCacheTests Assert.Equal("Contoso", notification.Registration.RegistrationId); } + [Theory] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, true)] + [InlineData(SecurityAlgorithms.RsaSha256, false)] + public async Task BackchannelLogoutEndpoint_EncryptedLogoutTokenIsValidatedForFapi2Registration(string algorithm, bool valid) + { + // Arrange + var handler = new RecordingLogoutHandler(); + + await using var host = await OpenIddictClientAspNetCoreBffTestHost.CreateAsync( + client: options => options.EnableDPoPTokenBinding().Configure(options => + { + var registration = options.Registrations[0]; + registration.ClientSecret = null; + registration.EnableFapi2SecurityProfile = true; + registration.SigningCredentials.Add(new SigningCredentials( + new ECDsaSecurityKey(ECDsa.Create(ECCurve.NamedCurves.nistP256)), SecurityAlgorithms.EcdsaSha256)); + }), + services: services => services.AddSingleton(handler)); + + var options = host.Services.GetRequiredService>().CurrentValue; + Assert.True(options.Registrations[0].EnableFapi2SecurityProfile); + + // Note: the key management and content encryption algorithms must not be + // restricted by the signing algorithms allowed by the FAPI 2.0 profile. + var token = CreateLogoutToken(host.SigningKey, new EncryptingCredentials( + options.EncryptionCredentials[0].Key, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512), algorithm); + + // Act + using var response = await SendLogoutTokenAsync(host, token); + + // Assert + Assert.Equal(valid ? HttpStatusCode.OK : HttpStatusCode.BadRequest, response.StatusCode); + Assert.Equal(valid ? 1 : 0, handler.Notifications.Count); + } + [Fact] public async Task BackchannelLogoutEndpoint_EncryptedLogoutTokenUsingUnknownKeyIsRejected() { @@ -286,7 +321,8 @@ public class OpenIddictClientAspNetCoreBffDistributedCacheTests signingKey: key); } - private static string CreateLogoutToken(SecurityKey? signingKey, EncryptingCredentials? encryptingCredentials = null) + private static string CreateLogoutToken(SecurityKey? signingKey, + EncryptingCredentials? encryptingCredentials = null, string algorithm = SecurityAlgorithms.RsaSha256) { var now = DateTime.UtcNow; @@ -307,7 +343,7 @@ public class OpenIddictClientAspNetCoreBffDistributedCacheTests IssuedAt = now, NotBefore = now, Issuer = OpenIddictClientAspNetCoreBffTestHost.Issuer.AbsoluteUri, - SigningCredentials = signingKey is null ? null : new SigningCredentials(signingKey, SecurityAlgorithms.RsaSha256), + SigningCredentials = signingKey is null ? null : new SigningCredentials(signingKey, algorithm), TokenType = JsonWebTokenTypes.LogoutToken }); } diff --git a/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Fapi.cs b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Fapi.cs index df6f5c8d..e892d83c 100644 --- a/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Fapi.cs +++ b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Fapi.cs @@ -1,6 +1,7 @@ using System.Security.Cryptography; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using Xunit; using static OpenIddict.Client.OpenIddictClientEvents; @@ -33,7 +34,8 @@ public class OpenIddictClientHandlersFapiTests Assert.Contains(TokenBindingMethods.Private.DPoP, registration.TokenBindingMethods); Assert.Contains(TokenBindingMethods.Private.TlsClientCertificate, registration.TokenBindingMethods); Assert.True(registration.IntrospectionResponseSigningAlgorithms.SetEquals(OpenIddictClientFapi2Profile.SigningAlgorithms)); - Assert.Equal(OpenIddictClientFapi2Profile.SigningAlgorithms, registration.TokenValidationParameters.ValidAlgorithms, StringComparer.Ordinal); + Assert.Null(registration.TokenValidationParameters.ValidAlgorithms); + Assert.NotNull(registration.TokenValidationParameters.AlgorithmValidator); Assert.Equal(SecurityAlgorithms.RsaSsaPssSha256, Assert.Single(registration.SigningCredentials, static credentials => credentials.Key is RsaSecurityKey).Algorithm); Assert.NotNull(registration.DPoPSigningCredentials); @@ -90,6 +92,46 @@ public class OpenIddictClientHandlersFapiTests Assert.Empty(registration.CodeChallengeMethods); Assert.Empty(registration.ResponseTypes); Assert.Null(registration.TokenValidationParameters.ValidAlgorithms); + Assert.Null(registration.TokenValidationParameters.AlgorithmValidator); + } + + [Theory] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, false, true)] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, true, true)] + [InlineData(SecurityAlgorithms.RsaSha256, false, false)] + [InlineData(SecurityAlgorithms.RsaSha256, true, false)] + public async Task PostConfigure_OnlySigningAlgorithmsAreRestricted(string algorithm, bool encrypted, bool valid) + { + // Arrange + using var provider = CreateProvider(); + var registration = GetRegistration(provider); + + var signing = new RsaSecurityKey(RSA.Create(2048)); + var encryption = new RsaSecurityKey(RSA.Create(2048)); + + var handler = new JsonWebTokenHandler(); + var token = handler.CreateToken(new SecurityTokenDescriptor + { + Audience = "Fabrikam", + Claims = new Dictionary(StringComparer.Ordinal) { [Claims.Subject] = "Bob" }, + // Note: the key management and content encryption algorithms must not be restricted by the profile. + EncryptingCredentials = encrypted ? new EncryptingCredentials(encryption, + SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512) : null, + Issuer = "https://www.contoso.com/", + SigningCredentials = new SigningCredentials(signing, algorithm) + }); + + var parameters = registration.TokenValidationParameters.Clone(); + parameters.IssuerSigningKey = signing; + parameters.TokenDecryptionKey = encryption; + parameters.ValidAudience = "Fabrikam"; + parameters.ValidIssuer = "https://www.contoso.com/"; + + // Act + var result = await handler.ValidateTokenAsync(token, parameters); + + // Assert + Assert.Equal(valid, result.IsValid); } public static TheoryData> InvalidRegistrations => new() diff --git a/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.IntrospectionResponse.cs b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.IntrospectionResponse.cs index be68870a..25a16e2c 100644 --- a/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.IntrospectionResponse.cs +++ b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.IntrospectionResponse.cs @@ -148,13 +148,20 @@ public class OpenIddictClientHandlersIntrospectionResponseTests } [Theory] - [InlineData(SecurityAlgorithms.RsaSha256, true)] - [InlineData(SecurityAlgorithms.RsaSsaPssSha256, false)] - public async Task ValidateIntrospectionResponseToken_TokenSignedUsingDisallowedAlgorithmIsRejected(string algorithm, bool rejected) + [InlineData(SecurityAlgorithms.RsaSha256, false, true)] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, false, false)] + [InlineData(SecurityAlgorithms.RsaSha256, true, true)] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, true, false)] + public async Task ValidateIntrospectionResponseToken_TokenSignedUsingDisallowedAlgorithmIsRejected(string algorithm, bool encrypted, bool rejected) { // Arrange using var provider = CreateProvider(required: true, algorithms: [SecurityAlgorithms.RsaSsaPssSha256]); - var context = CreateContext(provider, CreateToken(signing: new SigningCredentials(ServerSigningKey, algorithm))); + var options = provider.GetRequiredService>().CurrentValue; + + // Note: the key management and content encryption algorithms must not be restricted by the signing algorithms. + var context = CreateContext(provider, CreateToken(signing: new SigningCredentials(ServerSigningKey, algorithm), + encryption: encrypted ? new EncryptingCredentials(options.EncryptionCredentials[0].Key, + SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512) : null)); // Act await CreateHandler(provider).HandleAsync(context); diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Fapi.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Fapi.cs index 67abb095..73f1b376 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Fapi.cs +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Fapi.cs @@ -7,8 +7,10 @@ using System.Collections.Immutable; using System.Globalization; using System.Security.Claims; +using System.Security.Cryptography; using System.Text.Json.Nodes; using Microsoft.Extensions.DependencyInjection; +using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using Moq; using Xunit; @@ -164,15 +166,17 @@ public abstract partial class OpenIddictServerIntegrationTests Assert.Equal(SR.FormatID8000(SR.ID2029), response.ErrorUri); } - [Fact] - public async Task ValidatePushedAuthorizationRequest_Fapi2SecurityProfileRejectsNonLoopbackHttpRedirectUri() + [Theory] + [InlineData("http://www.fabrikam.com/path")] + [InlineData("http://localhost:5000/callback")] + public async Task ValidatePushedAuthorizationRequest_Fapi2SecurityProfileRejectsNonLoopbackHttpRedirectUri(string uri) { // Arrange await using var server = await CreateServerAsync(ConfigureFapiServer); await using var client = await server.CreateClientAsync(); // Act - var response = await client.PostAsync("/connect/par", CreateFapiPushedAuthorizationRequest("http://www.fabrikam.com/path")); + var response = await client.PostAsync("/connect/par", CreateFapiPushedAuthorizationRequest(uri)); // Assert Assert.Equal(Errors.InvalidRequest, response.Error); @@ -183,6 +187,7 @@ public abstract partial class OpenIddictServerIntegrationTests [Theory] [InlineData("https://www.fabrikam.com/path")] [InlineData("http://127.0.0.1:5000/callback")] + [InlineData("http://[::1]:5000/callback")] [InlineData("com.fabrikam.app:/callback")] public async Task ValidatePushedAuthorizationRequest_Fapi2SecurityProfileAcceptsHttpsLoopbackAndPrivateUseRedirectUris(string uri) { @@ -305,12 +310,13 @@ public abstract partial class OpenIddictServerIntegrationTests // Assert // - // Note: the client secret authentication methods are removed from the server options by the profile. + // Note: the client secret authentication methods are removed from the server options by the profile, + // so the request is rejected before Fapi.ValidateClientAuthentication is invoked (covered by unit tests). Assert.Equal(Errors.InvalidClient, response.Error); Assert.Equal(SR.FormatID2174(ClientAuthenticationMethods.ClientSecretPost), response.ErrorDescription); } -[Fact] + [Fact] public async Task ValidateIntrospectionRequest_Fapi2SecurityProfileRejectsPublicClients() { // Arrange @@ -451,43 +457,154 @@ public abstract partial class OpenIddictServerIntegrationTests Assert.Equal(TokenTypes.DPoP, response.TokenType); } - [Fact] - public async Task ValidateTokenRequest_Fapi2SecurityProfileRestrictsClientAssertionAlgorithms() + [Theory] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, true)] + [InlineData(SecurityAlgorithms.EcdsaSha256, true)] + [InlineData(SecurityAlgorithms.RsaSha256, false)] + [InlineData(SecurityAlgorithms.HmacSha256, false)] + [InlineData(SecurityAlgorithms.EcdsaSha384, false)] + public async Task ValidateTokenRequest_Fapi2SecurityProfileRestrictsClientAssertionAlgorithms(string algorithm, bool valid) { // Arrange await using var server = await CreateServerAsync(options => { ConfigureFapiServer(options); + AttachFapiClientSigningKeys(options, TokenTypeIdentifiers.Private.ClientAssertion); + }); + + await using var client = await server.CreateClientAsync(); + client.RequestHeaders["DPoP"] = [CreateDPoPProof()]; - options.AddEventHandler(builder => + // Act + var response = await client.PostAsync("/connect/token", new OpenIddictRequest + { + ClientAssertion = CreateFapiClientToken(algorithm, JsonWebTokenTypes.ClientAuthentication, new(StringComparer.Ordinal) { - builder.UseInlineHandler(context => - { - Assert.Equal([SecurityAlgorithms.RsaSsaPssSha256, SecurityAlgorithms.EcdsaSha256, "EdDSA"], - context.TokenValidationParameters.ValidAlgorithms, StringComparer.Ordinal); + [Claims.JwtId] = Guid.NewGuid().ToString(), + [Claims.Subject] = "Fabrikam" + }), + ClientAssertionType = ClientAssertionTypes.JwtBearer, + GrantType = GrantTypes.ClientCredentials + }); - context.Reject(error: "algorithms_checked"); + // Assert + if (valid) + { + Assert.Null(response.Error); + Assert.Equal(TokenTypes.DPoP, response.TokenType); + } - return ValueTask.CompletedTask; - }); + else + { + Assert.Equal(Errors.InvalidClient, response.Error); + } + } - builder.SetOrder(Fapi.RestrictClientTokenSigningAlgorithms.Descriptor.Order + 1); - }); + [Theory] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, false, true)] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, true, true)] + [InlineData(SecurityAlgorithms.EcdsaSha256, true, true)] + [InlineData(SecurityAlgorithms.RsaSha256, false, false)] + [InlineData(SecurityAlgorithms.RsaSha256, true, false)] + [InlineData(SecurityAlgorithms.HmacSha256, false, false)] + public async Task ValidatePushedAuthorizationRequest_Fapi2SecurityProfileRestrictsRequestObjectAlgorithms( + string algorithm, bool encrypted, bool valid) + { + // Arrange + await using var server = await CreateServerAsync(options => + { + ConfigureFapiServer(options); + options.EnableRequestObjectSupport(); + options.AddEncryptionKey(FapiServerEncryptionKey); + AttachFapiClientSigningKeys(options, TokenTypeIdentifiers.Private.RequestObject); }); await using var client = await server.CreateClientAsync(); - client.RequestHeaders["DPoP"] = [CreateDPoPProof()]; + + // Note: the key management and content encryption algorithms of encrypted + // request objects must not be restricted by the allowed signing algorithms. + var request = CreateFapiClientToken(algorithm, JsonWebTokenTypes.AuthorizationRequest, CreateFapiRequestObjectClaims(), + encryption: encrypted ? new EncryptingCredentials(FapiServerEncryptionKey, + SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512) : null); // Act - var response = await client.PostAsync("/connect/token", new OpenIddictRequest + var response = await client.PostAsync("/connect/par", new OpenIddictRequest { - ClientAssertion = "assertion", - ClientAssertionType = ClientAssertionTypes.JwtBearer, - GrantType = GrantTypes.ClientCredentials + ClientId = "Fabrikam", + Request = request }); // Assert - Assert.Equal("algorithms_checked", response.Error); + if (valid) + { + Assert.Null(response.Error); + Assert.NotNull(response.RequestUri); + } + + else + { + Assert.Equal(Errors.InvalidRequestObject, response.Error); + Assert.Equal(SR.GetResourceString(SR.ID2211), response.ErrorDescription); + } + } + + [Theory] + [InlineData(120, false)] + [InlineData(10, true)] + public async Task ValidatePushedAuthorizationRequest_Fapi2SecurityProfileRejectsRequestObjectsIssuedInTheFuture(int offset, bool valid) + { + // Arrange + await using var server = await CreateServerAsync(options => + { + ConfigureFapiServer(options); + options.EnableRequestObjectSupport(); + AttachFapiClientSigningKeys(options, TokenTypeIdentifiers.Private.RequestObject); + }); + + await using var client = await server.CreateClientAsync(); + + var claims = CreateFapiRequestObjectClaims(); + claims[Claims.IssuedAt] = DateTimeOffset.UtcNow.AddSeconds(offset).ToUnixTimeSeconds(); + + // Act + var response = await client.PostAsync("/connect/par", new OpenIddictRequest + { + ClientId = "Fabrikam", + Request = CreateFapiClientToken(SecurityAlgorithms.RsaSsaPssSha256, JsonWebTokenTypes.AuthorizationRequest, claims) + }); + + // Assert + if (valid) + { + Assert.Null(response.Error); + } + + else + { + // Note: the specific error returned by the FAPI handler (ID2485) is replaced by a generic error. + Assert.Equal(Errors.InvalidRequestObject, response.Error); + Assert.Equal(SR.GetResourceString(SR.ID2211), response.ErrorDescription); + } + } + + [Fact] + public async Task HandleConfigurationRequest_Fapi2SecurityProfileRestrictsRequestObjectSigningAlgorithms() + { + // Arrange + await using var server = await CreateServerAsync(options => + { + ConfigureFapiServer(options); + options.EnableRequestObjectSupport(); + }); + + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.GetAsync("/.well-known/openid-configuration"); + + // Assert + Assert.Equal([SecurityAlgorithms.RsaSsaPssSha256, SecurityAlgorithms.EcdsaSha256], + ((ImmutableArray?) response[Metadata.RequestObjectSigningAlgValuesSupported])!.Value, StringComparer.Ordinal); } [Fact] @@ -624,6 +741,71 @@ public abstract partial class OpenIddictServerIntegrationTests }); } + private static readonly RsaSecurityKey FapiClientRsaKey = new(RSA.Create(keySizeInBits: 2048)) { KeyId = "fapi_rsa" }; + private static readonly ECDsaSecurityKey FapiClientP256Key = new(ECDsa.Create(ECCurve.NamedCurves.nistP256)) { KeyId = "fapi_p256" }; + private static readonly ECDsaSecurityKey FapiClientP384Key = new(ECDsa.Create(ECCurve.NamedCurves.nistP384)) { KeyId = "fapi_p384" }; + private static readonly SymmetricSecurityKey FapiClientSymmetricKey = new(RandomNumberGenerator.GetBytes(32)) { KeyId = "fapi_hmac" }; + private static readonly RsaSecurityKey FapiServerEncryptionKey = new(RSA.Create(keySizeInBits: 2048)) { KeyId = "fapi_encryption" }; + + private static void AttachFapiClientSigningKeys(OpenIddictServerBuilder options, string type) + { + // Note: in degraded mode, the signing keys used to validate client tokens must be attached manually. + options.AddEventHandler(builder => + { + builder.UseInlineHandler(context => + { + if (context.ValidTokenTypes.Contains(type)) + { + context.TokenValidationParameters.IssuerSigningKeys = + new SecurityKey[] { FapiClientRsaKey, FapiClientP256Key, FapiClientP384Key, FapiClientSymmetricKey }; + } + + return ValueTask.CompletedTask; + }); + + builder.SetOrder(ResolveTokenValidationParameters.Descriptor.Order + 500); + }); + } + + private static Dictionary CreateFapiRequestObjectClaims() => new(StringComparer.Ordinal) + { + [Claims.ClientId] = "Fabrikam", + [Parameters.CodeChallenge] = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", + [Parameters.CodeChallengeMethod] = CodeChallengeMethods.Sha256, + [Parameters.RedirectUri] = "https://www.fabrikam.com/path", + [Parameters.ResponseType] = ResponseTypes.Code + }; + + private static string CreateFapiClientToken(string algorithm, string type, + Dictionary claims, EncryptingCredentials? encryption = null) + { + SecurityKey key = algorithm switch + { + SecurityAlgorithms.EcdsaSha256 => FapiClientP256Key, + SecurityAlgorithms.EcdsaSha384 => FapiClientP384Key, + SecurityAlgorithms.HmacSha256 => FapiClientSymmetricKey, + _ => FapiClientRsaKey + }; + + var now = DateTimeOffset.UtcNow; + + if (!claims.ContainsKey(Claims.IssuedAt)) + { + claims[Claims.IssuedAt] = now.ToUnixTimeSeconds(); + } + + return new JsonWebTokenHandler { SetDefaultTimesOnTokenCreation = false }.CreateToken(new SecurityTokenDescriptor + { + Audience = "http://localhost/", + Claims = claims, + EncryptingCredentials = encryption, + Expires = now.AddMinutes(1).UtcDateTime, + Issuer = "Fabrikam", + SigningCredentials = new SigningCredentials(key, algorithm), + TokenType = type + }); + } + private static OpenIddictRequest CreateFapiPushedAuthorizationRequest(string? redirectUri) => new() { ClientId = "Fabrikam", diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.IntrospectionResponse.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.IntrospectionResponse.cs index f64e1982..78491c02 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.IntrospectionResponse.cs +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.IntrospectionResponse.cs @@ -9,6 +9,7 @@ using System.Security.Claims; using System.Security.Cryptography; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using Moq; @@ -558,7 +559,7 @@ public abstract partial class OpenIddictServerIntegrationTests [Theory] [InlineData(SecurityAlgorithms.EcdsaSha384, null)] - [InlineData(SecurityAlgorithms.RsaSha256, SecurityAlgorithms.EcdsaSha256)] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, SecurityAlgorithms.RsaSha256)] public async Task ApplyIntrospectionResponse_UnusableAlgorithmSelectedByClientCausesAnException(string value, string? allowed) { // Arrange @@ -591,7 +592,7 @@ public abstract partial class OpenIddictServerIntegrationTests } [Fact] - public async Task ApplyIntrospectionResponse_MissingCredentialsForAllowedAlgorithmsCauseAnException() + public async Task ApplyIntrospectionResponse_MissingCredentialsForAllowedAlgorithmsAreReportedWhenValidatingOptions() { // Arrange await using var server = await CreateServerAsync(options => @@ -607,12 +608,12 @@ public abstract partial class OpenIddictServerIntegrationTests client.RequestHeaders["Accept"] = [IntrospectionResponseMediaType]; // Act and assert - var exception = await Assert.ThrowsAsync(delegate + var exception = await Assert.ThrowsAsync(delegate { return client.PostAsync("/connect/introspect", CreateIntrospectionRequest()); }); - Assert.Equal(SR.GetResourceString(SR.ID0970), exception.Message); + Assert.Contains(SR.GetResourceString(SR.ID0990), exception.Failures, StringComparer.Ordinal); } private OpenIddictApplicationManager CreateIntrospectionResponseApplicationManager( diff --git a/test/OpenIddict.Server.Tests/OpenIddictServerFapi2ProfileTests.cs b/test/OpenIddict.Server.Tests/OpenIddictServerFapi2ProfileTests.cs index 3255f6d8..0f0d310f 100644 --- a/test/OpenIddict.Server.Tests/OpenIddictServerFapi2ProfileTests.cs +++ b/test/OpenIddict.Server.Tests/OpenIddictServerFapi2ProfileTests.cs @@ -1,8 +1,11 @@ using System.Security.Cryptography; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Xunit; +using static OpenIddict.Server.OpenIddictServerEvents; namespace OpenIddict.Server.Tests; @@ -202,6 +205,84 @@ public class OpenIddictServerFapi2ProfileTests public void Validate_ReturnsAnErrorWhenIntrospectionResponseSigningAlgorithmIsEmpty() => AssertFailure(options => options.IntrospectionResponseSigningAlgorithms.Add(string.Empty), SR.ID0971); + [Fact] + public void Validate_ReturnsAnErrorWhenDPoPProofLifetimeIsTooLong() + => AssertFailure(options => options.DPoPProofLifetime = TimeSpan.FromMinutes(5), SR.ID0989); + + [Fact] + public void Validate_DoesNotReturnAnErrorWhenRollingRefreshTokensAreEnabled() + { + // Arrange + var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider()); + var options = CreateCompliantOptions(); + options.DisableRollingRefreshTokens = false; + configuration.PostConfigure(name: null, options); + + // Act + var result = configuration.Validate(name: null, options); + + // Assert + Assert.True(result.Succeeded, string.Join(Environment.NewLine, result.Failures ?? [])); + } + + [Theory] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, true)] + [InlineData(SecurityAlgorithms.EcdsaSha256, false)] + public void Validate_ReturnsAnErrorWhenNoCredentialsMatchIntrospectionResponseSigningAlgorithms(string algorithm, bool failure) + { + // Arrange + var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider()); + var options = CreateCompliantOptions(); + options.EnableJsonWebTokenIntrospectionResponses = true; + options.IntrospectionResponseSigningAlgorithms.Add(algorithm); + configuration.PostConfigure(name: null, options); + + // Act + var result = configuration.Validate(name: null, options); + + // Assert + Assert.Equal(failure, result.Failures?.Contains(SR.GetResourceString(SR.ID0990), StringComparer.Ordinal) ?? false); + } + + [Theory] + [InlineData(OpenIddictServerEndpointType.Token, true)] + [InlineData(OpenIddictServerEndpointType.PushedAuthorization, true)] + [InlineData(OpenIddictServerEndpointType.Introspection, true)] + [InlineData(OpenIddictServerEndpointType.Authorization, false)] + public async Task ValidateClientAuthentication_RejectsClientSecrets(OpenIddictServerEndpointType type, bool rejected) + { + // Arrange + var services = new ServiceCollection(); + services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>)); + + var options = CreateCompliantOptions(); + options.EnableDegradedMode = true; + + var transaction = new OpenIddictServerTransaction + { + CancellationToken = CancellationToken.None, + EndpointType = type, + Options = options, + Request = new OpenIddictRequest { ClientId = "Fabrikam", ClientSecret = "7Fjfp0ZBr1KtDRbnfVdmIw" }, + ServiceProvider = services.BuildServiceProvider() + }; + + var context = new ProcessAuthenticationContext(transaction); + + // Act + await new OpenIddictServerHandlers.Fapi.ValidateClientAuthentication().HandleAsync(context); + + // Assert + Assert.Equal(rejected, context.IsRejected); + + if (rejected) + { + Assert.Equal(Errors.InvalidClient, context.Error); + Assert.Equal(SR.GetResourceString(SR.ID2480), context.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2480), context.ErrorUri); + } + } + private static void AssertFailure(Action configure, string identifier) { // Arrange @@ -223,6 +304,7 @@ public class OpenIddictServerFapi2ProfileTests { AuthorizationCodeLifetime = TimeSpan.FromSeconds(60), EnableDPoPSupport = true, + DPoPProofLifetime = TimeSpan.FromSeconds(60), EnableFapi2SecurityProfile = true, RequestTokenLifetime = TimeSpan.FromMinutes(5), RequireProofKeyForCodeExchange = true, diff --git a/test/OpenIddict.Validation.Tests/OpenIddictValidationHandlersTests.IntrospectionResponse.cs b/test/OpenIddict.Validation.Tests/OpenIddictValidationHandlersTests.IntrospectionResponse.cs index 8429270a..4c6787ea 100644 --- a/test/OpenIddict.Validation.Tests/OpenIddictValidationHandlersTests.IntrospectionResponse.cs +++ b/test/OpenIddict.Validation.Tests/OpenIddictValidationHandlersTests.IntrospectionResponse.cs @@ -148,13 +148,20 @@ public class OpenIddictValidationHandlersIntrospectionResponseTests } [Theory] - [InlineData(SecurityAlgorithms.RsaSha256, true)] - [InlineData(SecurityAlgorithms.RsaSsaPssSha256, false)] - public async Task ValidateIntrospectionResponseToken_TokenSignedUsingDisallowedAlgorithmIsRejected(string algorithm, bool rejected) + [InlineData(SecurityAlgorithms.RsaSha256, false, true)] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, false, false)] + [InlineData(SecurityAlgorithms.RsaSha256, true, true)] + [InlineData(SecurityAlgorithms.RsaSsaPssSha256, true, false)] + public async Task ValidateIntrospectionResponseToken_TokenSignedUsingDisallowedAlgorithmIsRejected(string algorithm, bool encrypted, bool rejected) { // Arrange using var provider = CreateProvider(required: true, algorithms: [SecurityAlgorithms.RsaSsaPssSha256]); - var context = CreateContext(provider, CreateToken(signing: new SigningCredentials(ServerSigningKey, algorithm))); + var options = provider.GetRequiredService>().CurrentValue; + + // Note: the key management and content encryption algorithms must not be restricted by the signing algorithms. + var context = CreateContext(provider, CreateToken(signing: new SigningCredentials(ServerSigningKey, algorithm), + encryption: encrypted ? new EncryptingCredentials(options.EncryptionCredentials[0].Key, + SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512) : null)); // Act await CreateHandler(provider).HandleAsync(context);