Browse Source

Restrict only JWS signing algorithms and harden the FAPI 2.0 server profile validation

pull/2549/head
pieroviano 2 months ago
parent
commit
fc4fd512e5
  1. 64
      shared/OpenIddict.Extensions/IdentityModel/OpenIddictAlgorithmHelpers.cs
  2. 6
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  3. 5
      src/OpenIddict.Client/OpenIddictClientConfiguration.cs
  4. 3
      src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs
  5. 8
      src/OpenIddict.Server/OpenIddictServerBuilder.cs
  6. 31
      src/OpenIddict.Server/OpenIddictServerConfiguration.cs
  7. 13
      src/OpenIddict.Server/OpenIddictServerHandlers.Fapi.cs
  8. 3
      src/OpenIddict.Validation/OpenIddictValidationHandlers.Protection.cs
  9. 40
      test/OpenIddict.Client.AspNetCore.Bff.Tests/OpenIddictClientAspNetCoreBffDistributedCacheTests.cs
  10. 44
      test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Fapi.cs
  11. 15
      test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.IntrospectionResponse.cs
  12. 228
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Fapi.cs
  13. 9
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.IntrospectionResponse.cs
  14. 82
      test/OpenIddict.Server.Tests/OpenIddictServerFapi2ProfileTests.cs
  15. 15
      test/OpenIddict.Validation.Tests/OpenIddictValidationHandlersTests.IntrospectionResponse.cs

64
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;
/// <summary>
/// Exposes the helpers used to restrict the algorithms accepted when validating JSON Web Tokens.
/// </summary>
internal static class OpenIddictAlgorithmHelpers
{
/// <summary>
/// Creates an <see cref="AlgorithmValidator"/> that only restricts the JWS signing algorithms.
/// </summary>
/// <remarks>
/// Unlike <see cref="TokenValidationParameters.ValidAlgorithms"/>, 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 <paramref name="parameters"/> already defines an algorithm validator or valid algorithms,
/// they are also enforced.
/// </remarks>
/// <param name="algorithms">The allowed signing algorithms.</param>
/// <param name="parameters">The token validation parameters whose existing restrictions must be preserved.</param>
/// <returns>The algorithm validator.</returns>
public static AlgorithmValidator CreateSigningAlgorithmValidator(
IEnumerable<string> algorithms, TokenValidationParameters? parameters = null)
{
ArgumentNullException.ThrowIfNull(algorithms);
var allowed = new HashSet<string>(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);
};
}
}

6
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -2306,6 +2306,12 @@ Make sure the authorization server supports 'private_key_jwt', 'tls_client_auth'
<value>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()').</value>
</data>
<data name="ID0989" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID0990" xml:space="preserve">
<value>No asymmetric signing credentials using one of the introspection response signing algorithms allowed in the server options were registered.</value>
</data>
<data name="ID2000" xml:space="preserve">
<value>The security token is missing.</value>
</data>

5
src/OpenIddict.Client/OpenIddictClientConfiguration.cs

@ -405,7 +405,10 @@ public sealed class OpenIddictClientConfiguration : IPostConfigureOptions<OpenId
registration.IntrospectionResponseSigningAlgorithms.UnionWith(OpenIddictClientFapi2Profile.SigningAlgorithms);
}
registration.TokenValidationParameters.ValidAlgorithms ??= [.. OpenIddictClientFapi2Profile.SigningAlgorithms];
// Note: TokenValidationParameters.ValidAlgorithms is not used as IdentityModel also applies it to the
// key management and content encryption algorithms of encrypted tokens (e.g identity tokens).
registration.TokenValidationParameters.AlgorithmValidator = OpenIddictAlgorithmHelpers.CreateSigningAlgorithmValidator(
OpenIddictClientFapi2Profile.SigningAlgorithms, registration.TokenValidationParameters);
// RSASSA-PKCS1-v1_5 is not allowed by the profile but the same RSA keys can be used with RSASSA-PSS:
// to support the credentials registered using the default RS256 algorithm, PS256 is used instead.

3
src/OpenIddict.Client/OpenIddictClientHandlers.Protection.cs

@ -201,7 +201,8 @@ public static partial class OpenIddictClientHandlers
// If the signing algorithms were restricted, reject introspection responses using other algorithms.
if (context.Registration.IntrospectionResponseSigningAlgorithms.Count is > 0)
{
parameters.ValidAlgorithms = [.. context.Registration.IntrospectionResponseSigningAlgorithms];
parameters.AlgorithmValidator = OpenIddictAlgorithmHelpers.CreateSigningAlgorithmValidator(
context.Registration.IntrospectionResponseSigningAlgorithms, parameters);
}
}

8
src/OpenIddict.Server/OpenIddictServerBuilder.cs

@ -2311,13 +2311,15 @@ public sealed class OpenIddictServerBuilder
/// <item><description>JWTs sent by clients (client assertions, request objects) must use PS256, ES256 or EdDSA
/// and the RSA signing credentials of the server use PS256;</description></item>
/// <item><description>authorization codes expire after at most 60 seconds and request URIs after less than 600 seconds;</description></item>
/// <item><description>pushed authorization requests must include an https (or loopback) redirect_uri;</description></item>
/// <item><description>rolling refresh tokens are disabled by default, as recommended by the profile.</description></item>
/// <item><description>pushed authorization requests must include an https (or loopback IP literal http) redirect_uri;</description></item>
/// <item><description>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.</description></item>
/// </list>
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <returns>The <see cref="OpenIddictServerBuilder"/> instance.</returns>
public OpenIddictServerBuilder EnableFapi2SecurityProfile()

31
src/OpenIddict.Server/OpenIddictServerConfiguration.cs

@ -615,6 +615,15 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions<OpenId
{
builder.AddError(SR.GetResourceString(SR.ID0967));
}
// Note: proofs whose "iat" claim is more than 60 seconds in the future must be rejected (section 5.3.2.1, item 13).
if (options.EnableDPoPSupport && options.DPoPProofLifetime > 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<OpenId
builder.AddError(SR.GetResourceString(SR.ID0086));
}
// When static credentials are used, ensure the introspection response signing algorithms can be honored.
if (options.EnableJsonWebTokenIntrospectionResponses &&
options.IntrospectionResponseSigningAlgorithms.Count is > 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.

13
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;
}

3
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;

40
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<IOpenIddictClientAspNetCoreBffBackchannelLogoutHandler>(handler));
var options = host.Services.GetRequiredService<IOptionsMonitor<OpenIddictClientOptions>>().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
});
}

44
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<string, object>(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<string, Action<OpenIddictClientRegistration>> InvalidRegistrations => new()

15
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<IOptionsMonitor<OpenIddictClientOptions>>().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);

228
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<ValidateTokenContext>(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<string?>?) 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<ValidateTokenContext>(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<string, object> 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<string, object> 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",

9
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<InvalidOperationException>(delegate
var exception = await Assert.ThrowsAsync<OptionsValidationException>(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<OpenIddictApplication> CreateIntrospectionResponseApplicationManager(

82
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<OpenIddictServerOptions> 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,

15
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<IOptionsMonitor<OpenIddictValidationOptions>>().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);

Loading…
Cancel
Save