diff --git a/shared/OpenIddict.Extensions/OpenIddictHelpers.cs b/shared/OpenIddict.Extensions/OpenIddictHelpers.cs index f73b4204..d333b42f 100644 --- a/shared/OpenIddict.Extensions/OpenIddictHelpers.cs +++ b/shared/OpenIddict.Extensions/OpenIddictHelpers.cs @@ -610,6 +610,69 @@ internal static class OpenIddictHelpers return true; } + /// + /// Determines whether the specified value conforms to the syntax of Bearer credentials, as defined in + /// RFC 6750 section 2.1: + /// b64token = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"=". + /// + /// The value. + /// if the value is a valid b64token, otherwise. + public static bool IsValidBearerCredential([NotNullWhen(true)] string? value) + { + if (string.IsNullOrEmpty(value)) + { + return false; + } + + // Determine where the trailing padding characters start. + var length = value.Length; + while (length > 0 && value[length - 1] is '=') + { + length--; + } + + // At least one non-padding character is required. + if (length is 0) + { + return false; + } + + for (var index = 0; index < length; index++) + { + if (value[index] is not ((>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or (>= '0' and <= '9') or + '-' or '.' or '_' or '~' or '+' or '/')) + { + return false; + } + } + + return true; + } + + /// + /// Determines whether the specified value is a valid CIBA client notification endpoint (i.e an + /// absolute HTTPS URI that doesn't contain a fragment), as required by + /// + /// CIBA Core 1.0 section 4. + /// + /// The value. + /// The parsed endpoint, if valid. + /// if the endpoint is valid, otherwise. + public static bool TryParseClientNotificationEndpoint(string? value, [NotNullWhen(true)] out Uri? endpoint) + { + if (string.IsNullOrEmpty(value) || + !Uri.TryCreate(value, UriKind.Absolute, out Uri? uri) || + !string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) || + !string.IsNullOrEmpty(uri.Fragment)) + { + endpoint = null; + return false; + } + + endpoint = uri; + return true; + } + /// /// Note: this implementation was taken from ASP.NET Core. /// diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx index 6650393e..d6d1081a 100644 --- a/src/OpenIddict.Abstractions/OpenIddictResources.resx +++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx @@ -2006,12 +2006,15 @@ To send notifications using System.Net.Http, reference the 'OpenIddict.Server.Sy The notification, the expected client notification token and the token delivery mode must be set. Backchannel notifications can only be processed for the 'ping' and 'push' token delivery modes. + + The push token delivery mode cannot be enabled when DPoP proofs are required for all token requests, as pushed tokens are not issued in response to a token request and thus cannot be bound to a DPoP proof key. + A signed backchannel authentication request must be sent but the authorization server doesn't support signed backchannel authentication requests using the '{0}' algorithm. To send signed backchannel authentication requests, attach an asymmetric signing key using an algorithm listed in the 'backchannel_authentication_request_signing_alg_values_supported' server metadata. - - The push token delivery mode cannot be enabled when DPoP proofs are required for all token requests, as pushed tokens are not issued in response to a token request and thus cannot be bound to a DPoP proof key. + + The client notification token must conform to the syntax of Bearer credentials defined in RFC 6750 section 2.1. The backchannel authentication request was not correctly extracted. @@ -2973,6 +2976,12 @@ Error URI: {2} The push token delivery mode cannot be used by client applications that require sender-constrained tokens. + + The '{0}' parameter must conform to the syntax of Bearer credentials. + + + The signed authentication request uses an algorithm that is not supported by the authorization server. + The '{0}' setting must be an absolute HTTP or HTTPS URI that doesn't contain a fragment. @@ -4089,6 +4098,9 @@ This may indicate that the hashed entry is corrupted or malformed. An error occurred while sending the {Mode} notification of the completed backchannel authentication request '{Identifier}' to the client application '{ClientId}'. + + The signed backchannel authentication request sent by the client application '{ClientId}' was rejected because the '{Algorithm}' signing algorithm is not supported. + A concurrency exception occurred while trying to extend the session '{Identifier}'. diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.Exchange.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.Exchange.cs index 98abf700..eec0af1d 100644 --- a/src/OpenIddict.Client/OpenIddictClientHandlers.Exchange.cs +++ b/src/OpenIddict.Client/OpenIddictClientHandlers.Exchange.cs @@ -122,6 +122,8 @@ public static partial class OpenIddictClientHandlers Errors.InvalidScope => Errors.InvalidScope, Errors.InvalidRequest => Errors.InvalidRequest, Errors.SlowDown => Errors.SlowDown, + // Note: transaction_failed is only returned by CIBA push notifications (CIBA Core 1.0, section 12). + Errors.TransactionFailed => Errors.TransactionFailed, Errors.UnauthorizedClient => Errors.UnauthorizedClient, Errors.UnsupportedGrantType => Errors.UnsupportedGrantType, _ => Errors.ServerError diff --git a/src/OpenIddict.Client/OpenIddictClientHandlers.cs b/src/OpenIddict.Client/OpenIddictClientHandlers.cs index 801d538b..4a60e845 100644 --- a/src/OpenIddict.Client/OpenIddictClientHandlers.cs +++ b/src/OpenIddict.Client/OpenIddictClientHandlers.cs @@ -83,6 +83,7 @@ public static partial class OpenIddictClientHandlers GenerateClientAssertion.Descriptor, AttachTokenRequestClientCredentials.Descriptor, SendTokenRequest.Descriptor, + HandleBackchannelPushedTokenResponse.Descriptor, EvaluateValidatedBackchannelTokens.Descriptor, ResolveValidatedBackchannelTokens.Descriptor, @@ -3109,6 +3110,60 @@ public static partial class OpenIddictClientHandlers } } + /// + /// Contains the logic responsible for applying the standard token response validation (well-known parameter + /// types and error handling) to the token response pushed to the client notification endpoint (CIBA push mode). + /// + /// + /// See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.10.3. + /// + public sealed class HandleBackchannelPushedTokenResponse : IOpenIddictClientHandler + { + private readonly OpenIddictClientService _service; + + public HandleBackchannelPushedTokenResponse(OpenIddictClientService service) + => _service = service ?? throw new ArgumentNullException(nameof(service)); + + /// + /// Gets the default descriptor definition assigned to this handler. + /// + public static OpenIddictClientHandlerDescriptor Descriptor { get; } + = OpenIddictClientHandlerDescriptor.CreateBuilder() + .UseSingletonHandler() + .SetOrder(SendTokenRequest.Descriptor.Order + 500) + .SetType(OpenIddictClientHandlerType.BuiltIn) + .Build(); + + /// + public async ValueTask HandleAsync(ProcessAuthenticationContext context) + { + ArgumentNullException.ThrowIfNull(context); + + if (context.SendTokenRequest || context.TokenResponse is null || + context.GrantType is not GrantTypes.Ciba || + context.BackchannelTokenDeliveryMode is not BackchannelTokenDeliveryModes.Push) + { + return; + } + + try + { + context.TokenResponse = await _service.HandleBackchannelPushedTokenResponseAsync( + context.Registration, context.Configuration, context.TokenResponse, context.CancellationToken); + } + + catch (ProtocolException exception) + { + context.Reject( + error: exception.Error, + description: exception.ErrorDescription, + uri: exception.ErrorUri); + + return; + } + } + } + /// /// Contains the logic responsible for determining the set of backchannel tokens to validate. /// @@ -7440,6 +7495,16 @@ public static partial class OpenIddictClientHandlers { throw new InvalidOperationException(SR.GetResourceString(SR.ID0607)); } + + // The client_notification_token MUST conform to the syntax for Bearer credentials. + // + // See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.7.1 + // and https://datatracker.ietf.org/doc/html/rfc6750#section-2.1. + if (!string.IsNullOrEmpty(context.ClientNotificationToken) && + !OpenIddictHelpers.IsValidBearerCredential(context.ClientNotificationToken)) + { + throw new InvalidOperationException(SR.GetResourceString(SR.ID0611)); + } } return ValueTask.CompletedTask; diff --git a/src/OpenIddict.Client/OpenIddictClientHelpers.cs b/src/OpenIddict.Client/OpenIddictClientHelpers.cs index e24a4705..784d8d86 100644 --- a/src/OpenIddict.Client/OpenIddictClientHelpers.cs +++ b/src/OpenIddict.Client/OpenIddictClientHelpers.cs @@ -15,6 +15,12 @@ namespace OpenIddict.Client; /// public static class OpenIddictClientHelpers { + /// + /// Represents the maximum length, in bytes, of the JSON body accepted by + /// (256 KB). + /// + public const int MaximumBackchannelNotificationLength = 256 * 1024; + /// /// Creates a from the raw HTTP request received by the client notification /// endpoint (CIBA ping and push modes): the bearer token is extracted from the "Authorization" header and the @@ -25,7 +31,8 @@ public static class OpenIddictClientHelpers /// The request body. /// The that can be used to abort the operation. /// - /// The notification or if the request is not a valid JSON notification. + /// The notification or if the request is not a valid JSON notification, doesn't include + /// a syntactically valid bearer token or has a body exceeding . /// /// /// See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.10.2. @@ -41,11 +48,46 @@ public static class OpenIddictClientHelpers return null; } + // Note: the client notification endpoint is publicly reachable, so requests that don't include a syntactically + // valid bearer token (RFC 6750, section 2.1) are rejected before the request body is read. The token itself + // is validated by OpenIddictClientService.AuthenticateWithBackchannelNotificationAsync(). + // + // Note: the authentication scheme is case-insensitive (RFC 9110, section 11.1). + if (string.IsNullOrEmpty(authorization) || + !AuthenticationHeaderValue.TryParse(authorization, out AuthenticationHeaderValue? header) || + !string.Equals(header.Scheme, "Bearer", StringComparison.OrdinalIgnoreCase) || + !OpenIddictHelpers.IsValidBearerCredential(header.Parameter)) + { + return null; + } + + // To prevent unbounded allocations, the body is buffered up to the maximum allowed length. + using var buffer = new MemoryStream(); + var chunk = new byte[4096]; + + while (true) + { + var read = await body.ReadAsync(chunk, 0, chunk.Length, cancellationToken); + if (read is 0) + { + break; + } + + if (buffer.Length + read > MaximumBackchannelNotificationLength) + { + return null; + } + + buffer.Write(chunk, 0, read); + } + + buffer.Position = 0; + JsonDocument document; try { - document = await JsonDocument.ParseAsync(body, cancellationToken: cancellationToken); + document = await JsonDocument.ParseAsync(buffer, cancellationToken: cancellationToken); } catch (JsonException) @@ -62,10 +104,7 @@ public static class OpenIddictClientHelpers return new BackchannelNotification { - // Note: the authentication scheme is case-insensitive (RFC 9110, section 11.1). - ClientNotificationToken = !string.IsNullOrEmpty(authorization) && - AuthenticationHeaderValue.TryParse(authorization, out AuthenticationHeaderValue? header) && - string.Equals(header.Scheme, "Bearer", StringComparison.OrdinalIgnoreCase) ? header.Parameter : null, + ClientNotificationToken = header.Parameter, Payload = new OpenIddictResponse(document.RootElement.Clone()) }; } diff --git a/src/OpenIddict.Client/OpenIddictClientService.cs b/src/OpenIddict.Client/OpenIddictClientService.cs index 2d314a05..3800ed3f 100644 --- a/src/OpenIddict.Client/OpenIddictClientService.cs +++ b/src/OpenIddict.Client/OpenIddictClientService.cs @@ -1054,16 +1054,10 @@ public partial class OpenIddictClientService Errors.InvalidRequest, SR.GetResourceString(SR.ID2311), SR.FormatID8000(SR.ID2311)); } - // In push mode, errors (e.g access_denied or expired_token) are directly sent to the client notification endpoint. - // - // See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.12. - if (request.TokenDeliveryMode is BackchannelTokenDeliveryModes.Push && !string.IsNullOrEmpty(request.Notification.Payload.Error)) - { - var payload = request.Notification.Payload; - - throw new ProtocolException(SR.FormatID0374(payload.Error, payload.ErrorDescription, payload.ErrorUri), - payload.Error, payload.ErrorDescription, payload.ErrorUri); - } + // Note: in push mode, errors (e.g access_denied or expired_token) are directly sent to the client notification + // endpoint (see https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.12). + // Pushed payloads are handled by the HandleBackchannelPushedTokenResponse handler, that applies the same structural + // validation and error handling as the one used for token responses returned by the token endpoint. await using var scope = _provider.CreateAsyncScope(); @@ -3249,6 +3243,58 @@ public partial class OpenIddictClientService } } + /// + /// Handles the token response pushed by the authorization server to the client notification endpoint + /// (CIBA push mode) using the same pipeline as the one used for token endpoint responses. + /// + /// The client registration. + /// The server configuration. + /// The pushed token response. + /// The that can be used to abort the operation. + /// The validated token response. + internal async ValueTask HandleBackchannelPushedTokenResponseAsync( + OpenIddictClientRegistration registration, OpenIddictConfiguration configuration, + OpenIddictResponse response, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(registration); + ArgumentNullException.ThrowIfNull(configuration); + ArgumentNullException.ThrowIfNull(response); + + cancellationToken.ThrowIfCancellationRequested(); + + await using var scope = _provider.CreateAsyncScope(); + + var dispatcher = scope.ServiceProvider.GetRequiredService(); + var options = scope.ServiceProvider.GetRequiredService>(); + + var transaction = new OpenIddictClientTransaction + { + CancellationToken = cancellationToken, + Options = options.CurrentValue, + ServiceProvider = scope.ServiceProvider + }; + + var context = new HandleTokenResponseContext(transaction) + { + Configuration = configuration, + Registration = registration, + // Note: pushed responses are not associated with a token request. + Request = new(), + Response = response + }; + + await dispatcher.DispatchAsync(context); + + if (context.IsRejected) + { + throw new ProtocolException( + SR.FormatID0323(context.Error, context.ErrorDescription, context.ErrorUri), + context.Error, context.ErrorDescription, context.ErrorUri); + } + + return context.Response; + } + /// /// Sends the userinfo request and retrieves the corresponding response. /// diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Backchannel.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Backchannel.cs index d75645bd..a3a353c9 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.Backchannel.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Backchannel.cs @@ -11,6 +11,7 @@ using System.Security.Claims; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.IdentityModel.Tokens; namespace OpenIddict.Server; @@ -18,6 +19,24 @@ public static partial class OpenIddictServerHandlers { public static class Backchannel { + /// + /// Gets the asymmetric signing algorithms that are accepted for signed backchannel authentication + /// requests and advertised in the "backchannel_authentication_request_signing_alg_values_supported" + /// server metadata (CIBA Core 1.0 section 4 forbids "none" and symmetric algorithms). + /// + internal static ImmutableArray RequestSigningAlgorithms { get; } = + [ + SecurityAlgorithms.EcdsaSha256, + SecurityAlgorithms.EcdsaSha384, + SecurityAlgorithms.EcdsaSha512, + SecurityAlgorithms.RsaSha256, + SecurityAlgorithms.RsaSha384, + SecurityAlgorithms.RsaSha512, + SecurityAlgorithms.RsaSsaPssSha256, + SecurityAlgorithms.RsaSsaPssSha384, + SecurityAlgorithms.RsaSsaPssSha512 + ]; + public static ImmutableArray DefaultHandlers { get; } = [ /* @@ -410,6 +429,21 @@ public static partial class OpenIddictServerHandlers return; } + // Only the advertised asymmetric algorithms can be used to sign authentication requests. + // + // See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.4. + if (string.IsNullOrEmpty(algorithm) || !RequestSigningAlgorithms.Contains(algorithm, StringComparer.Ordinal)) + { + context.Logger.LogInformation(6418, SR.GetResourceString(SR.ID6418), context.Request.ClientId, algorithm); + + context.Reject( + error: Errors.InvalidRequest, + description: SR.GetResourceString(SR.ID2314), + uri: SR.FormatID8000(SR.ID2314)); + + return; + } + // Signed authentication requests MUST contain the "exp", "iat", "nbf" and "jti" claims. // // See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.7.1.1. @@ -1027,16 +1061,9 @@ public static partial class OpenIddictServerHandlers Debug.Assert(!string.IsNullOrEmpty(context.ClientId), SR.FormatID4000(Parameters.ClientId)); - // Note: when only the poll mode is enabled, the delivery mode registered by - // the client application is not resolved and the poll mode is always used. - if (context.Options.BackchannelTokenDeliveryModes.Count is 1 && - context.Options.BackchannelTokenDeliveryModes.Contains(BackchannelTokenDeliveryModes.Poll)) - { - context.TokenDeliveryMode = BackchannelTokenDeliveryModes.Poll; - - return; - } - + // Note: the delivery mode registered by the client application is always resolved (even when only + // the poll mode is enabled) so that clients registered with a mode that is not enabled are rejected + // instead of being silently downgraded to the poll mode and never receiving any notification. var manager = context.ServiceProvider.GetService() ?? throw new InvalidOperationException(SR.GetResourceString(SR.ID0016)); @@ -1068,9 +1095,7 @@ public static partial class OpenIddictServerHandlers // // See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.4. if (!settings.TryGetValue(Settings.BackchannelAuthentication.ClientNotificationEndpoint, out string? endpoint) || - !Uri.TryCreate(endpoint, UriKind.Absolute, out Uri? uri) || - !string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) || - !string.IsNullOrEmpty(uri.Fragment)) + !OpenIddictHelpers.TryParseClientNotificationEndpoint(endpoint, out _)) { context.Logger.LogWarning(6403, SR.GetResourceString(SR.ID6403), context.ClientId); @@ -1104,6 +1129,20 @@ public static partial class OpenIddictServerHandlers return; } + + // The client_notification_token MUST conform to the syntax for Bearer credentials. + // + // See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.7.1 + // and https://datatracker.ietf.org/doc/html/rfc6750#section-2.1. + if (!OpenIddictHelpers.IsValidBearerCredential(context.Request.ClientNotificationToken)) + { + context.Reject( + error: Errors.InvalidRequest, + description: SR.FormatID2313(Parameters.ClientNotificationToken), + uri: SR.FormatID8000(SR.ID2313)); + + return; + } } // Tokens delivered using the push mode are generated outside the context of a token request and diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs index 7e738a10..e565b17d 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs @@ -902,17 +902,7 @@ public static partial class OpenIddictServerHandlers context.Options.BackchannelAuthenticationEndpointUris.Count is > 0) { context.Metadata[Metadata.BackchannelAuthenticationRequestSigningAlgValuesSupported] = new JsonArray( - [ - SecurityAlgorithms.EcdsaSha256, - SecurityAlgorithms.EcdsaSha384, - SecurityAlgorithms.EcdsaSha512, - SecurityAlgorithms.RsaSha256, - SecurityAlgorithms.RsaSha384, - SecurityAlgorithms.RsaSha512, - SecurityAlgorithms.RsaSsaPssSha256, - SecurityAlgorithms.RsaSsaPssSha384, - SecurityAlgorithms.RsaSsaPssSha512 - ]); + [.. Backchannel.RequestSigningAlgorithms.Select(static algorithm => (JsonNode) algorithm)]); } // If DPoP support was enabled, return the signing algorithms allowed for DPoP proofs. diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.cs index 08431ec6..daf83474 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.cs @@ -1686,9 +1686,9 @@ public static partial class OpenIddictServerHandlers { ArgumentNullException.ThrowIfNull(context); - // Note: when the push mode is not enabled, all the clients are treated as poll or ping clients. - if (context.EndpointType is not OpenIddictServerEndpointType.Token || - !context.Options.BackchannelTokenDeliveryModes.Contains(BackchannelTokenDeliveryModes.Push)) + // Note: the registered delivery mode is always resolved, independently of the delivery modes enabled + // in the server options, as CIBA 1.0 section 11 forbids push clients from using the token endpoint. + if (context.EndpointType is not OpenIddictServerEndpointType.Token) { return; } diff --git a/src/OpenIddict.Server/OpenIddictServerService.cs b/src/OpenIddict.Server/OpenIddictServerService.cs index 3623b727..5e78d3b7 100644 --- a/src/OpenIddict.Server/OpenIddictServerService.cs +++ b/src/OpenIddict.Server/OpenIddictServerService.cs @@ -362,8 +362,7 @@ public class OpenIddictServerService var settings = await manager.GetSettingsAsync(application, cancellationToken); if (!settings.TryGetValue(Settings.BackchannelAuthentication.ClientNotificationEndpoint, out string? value) || - !Uri.TryCreate(value, UriKind.Absolute, out Uri? endpoint) || - !string.Equals(endpoint.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) + !OpenIddictHelpers.TryParseClientNotificationEndpoint(value, out Uri? endpoint)) { logger.LogWarning(6403, SR.GetResourceString(SR.ID6403), request.ClientId); diff --git a/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Backchannel.cs b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Backchannel.cs index 1aa4ef92..3cad9223 100644 --- a/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Backchannel.cs +++ b/test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Backchannel.cs @@ -465,6 +465,35 @@ public class OpenIddictClientHandlersBackchannelTests Assert.Null(await OpenIddictClientHelpers.CreateBackchannelNotificationAsync("Bearer 8C3C7A6D", type, body)); } + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("Basic 8C3C7A6D")] + [InlineData("Bearer")] + [InlineData("Bearer =8C3C7A6D")] + public async Task CreateBackchannelNotificationAsync_ReturnsNullWithoutValidBearerToken(string? authorization) + { + // Arrange + using var body = new MemoryStream(Encoding.UTF8.GetBytes("""{ "auth_req_id": "F6B3B1E4" }""")); + + // Act and assert + Assert.Null(await OpenIddictClientHelpers.CreateBackchannelNotificationAsync(authorization, "application/json", body)); + + // Note: the body must not be read when the bearer token is missing or invalid. + Assert.Equal(0, body.Position); + } + + [Fact] + public async Task CreateBackchannelNotificationAsync_ReturnsNullForOversizedBodies() + { + // Arrange + var payload = "{ \"auth_req_id\": \"" + new string('a', OpenIddictClientHelpers.MaximumBackchannelNotificationLength) + "\" }"; + using var body = new MemoryStream(Encoding.UTF8.GetBytes(payload)); + + // Act and assert + Assert.Null(await OpenIddictClientHelpers.CreateBackchannelNotificationAsync("Bearer 8C3C7A6D", "application/json", body)); + } + [Theory] [InlineData(null, "F6B3B1E4", null, Errors.InvalidToken)] [InlineData("invalid", "F6B3B1E4", null, Errors.InvalidToken)] @@ -495,6 +524,38 @@ public class OpenIddictClientHandlersBackchannelTests Assert.Equal(expected, exception.Error); } + [Theory] + [InlineData("""{ "auth_req_id": "F6B3B1E4", "access_token": 42, "token_type": "Bearer" }""", Errors.ServerError)] + [InlineData("""{ "auth_req_id": "F6B3B1E4", "error": [ "access_denied" ] }""", Errors.ServerError)] + [InlineData("""{ "auth_req_id": "F6B3B1E4", "error": "transaction_failed" }""", Errors.TransactionFailed)] + [InlineData("""{ "auth_req_id": "F6B3B1E4", "error": "custom_error" }""", Errors.ServerError)] + public async Task AuthenticateWithBackchannelNotificationAsync_PushedPayloadsUseStandardTokenResponseValidation( + string payload, string expected) + { + // Arrange + using var provider = CreateProvider(); + var service = provider.GetRequiredService(); + + using var document = JsonDocument.Parse(payload); + + // Act and assert + var exception = await Assert.ThrowsAsync(async () => + await service.AuthenticateWithBackchannelNotificationAsync(new() + { + AuthenticationRequestId = "F6B3B1E4", + ClientNotificationToken = "8C3C7A6D", + DisableUserInfo = true, + Notification = new() + { + ClientNotificationToken = "8C3C7A6D", + Payload = new OpenIddictResponse(document.RootElement.Clone()) + }, + TokenDeliveryMode = BackchannelTokenDeliveryModes.Push + })); + + Assert.Equal(expected, exception.Error); + } + [Fact] public async Task AuthenticateWithBackchannelNotificationAsync_PushedTokensAreValidated() { diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Backchannel.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Backchannel.cs index a7c51f34..deb1d9ad 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Backchannel.cs +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Backchannel.cs @@ -722,23 +722,52 @@ public abstract partial class OpenIddictServerIntegrationTests } [Fact] - public async Task ValidateBackchannelAuthenticationRequest_RegisteredDeliveryModeIsIgnoredWhenOnlyPollIsEnabled() + public async Task ValidateBackchannelAuthenticationRequest_RegisteredDeliveryModeIsRejectedWhenOnlyPollIsEnabled() { // Arrange await using var server = await CreateServerAsync(options => { ConfigureBackchannelAuthentication(options, new(StringComparer.Ordinal) { - [Settings.BackchannelAuthentication.TokenDeliveryMode] = BackchannelTokenDeliveryModes.Push + [Settings.BackchannelAuthentication.TokenDeliveryMode] = BackchannelTokenDeliveryModes.Push, + [Settings.BackchannelAuthentication.ClientNotificationEndpoint] = "https://fabrikam.com/ciba/notify" }); + }); - options.AddEventHandler(builder => - builder.UseInlineHandler(context => - { - context.Reject("custom_error", "The request was accepted by the validation pipeline."); + await using var client = await server.CreateClientAsync(); - return ValueTask.CompletedTask; - })); + // Act + var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest + { + ClientId = "Fabrikam", + ClientNotificationToken = "8C3C7A6D", + LoginHint = "bob@fabrikam.com", + Scope = Scopes.OpenId + }); + + // Assert + Assert.Equal(Errors.UnauthorizedClient, response.Error); + Assert.Equal(SR.FormatID2302(BackchannelTokenDeliveryModes.Push), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2302), response.ErrorUri); + } + + [Theory] + [InlineData("8C3C7A6D notification")] + [InlineData("8C3C7A6D=notification")] + [InlineData("=8C3C7A6D")] + [InlineData("8C3C7A6Dé")] + public async Task ValidateBackchannelAuthenticationRequest_MalformedClientNotificationTokenCausesAnError(string token) + { + // Arrange + await using var server = await CreateServerAsync(options => + { + ConfigureBackchannelAuthentication(options, new(StringComparer.Ordinal) + { + [Settings.BackchannelAuthentication.TokenDeliveryMode] = BackchannelTokenDeliveryModes.Ping, + [Settings.BackchannelAuthentication.ClientNotificationEndpoint] = "https://fabrikam.com/ciba/notify" + }); + + options.AllowBackchannelPingTokenDeliveryMode(); }); await using var client = await server.CreateClientAsync(); @@ -747,12 +776,15 @@ public abstract partial class OpenIddictServerIntegrationTests var response = await client.PostAsync("/connect/ciba", new OpenIddictRequest { ClientId = "Fabrikam", + ClientNotificationToken = token, LoginHint = "bob@fabrikam.com", Scope = Scopes.OpenId }); // Assert - Assert.Equal("custom_error", response.Error); + Assert.Equal(Errors.InvalidRequest, response.Error); + Assert.Equal(SR.FormatID2313(Parameters.ClientNotificationToken), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2313), response.ErrorUri); } [Fact] @@ -965,8 +997,10 @@ public abstract partial class OpenIddictServerIntegrationTests Assert.Equal(SR.FormatID8000(SR.ID2211), response.ErrorUri); } - [Fact] - public async Task ValidateTokenRequest_PushClientsCannotRedeemAuthenticationRequestIdentifiers() + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task ValidateTokenRequest_PushClientsCannotRedeemAuthenticationRequestIdentifiers(bool enabled) { // Arrange await using var server = await CreateServerAsync(options => @@ -977,7 +1011,10 @@ public abstract partial class OpenIddictServerIntegrationTests [Settings.BackchannelAuthentication.ClientNotificationEndpoint] = "https://fabrikam.com/ciba/notify" }); - options.AllowBackchannelPushTokenDeliveryMode(); + if (enabled) + { + options.AllowBackchannelPushTokenDeliveryMode(); + } }); await using var client = await server.CreateClientAsync();