Browse Source

Enforce CIBA delivery mode registration and harden notification handling

Always resolve the registered token delivery mode (rejecting ping/push clients
when the mode is not enabled and push clients at the token endpoint), validate
client notification tokens against the RFC 6750 b64token syntax, restrict signed
requests to the advertised algorithms, share the notification endpoint check,
reject unauthenticated or oversized notifications before parsing, apply the
standard token response validation to pushed payloads and drop the Polly
dependency of OpenIddict.Server.SystemNetHttp.
pull/2549/head
pieroviano 2 months ago
parent
commit
4ea80d79b9
  1. 63
      shared/OpenIddict.Extensions/OpenIddictHelpers.cs
  2. 16
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  3. 2
      src/OpenIddict.Client/OpenIddictClientHandlers.Exchange.cs
  4. 65
      src/OpenIddict.Client/OpenIddictClientHandlers.cs
  5. 51
      src/OpenIddict.Client/OpenIddictClientHelpers.cs
  6. 66
      src/OpenIddict.Client/OpenIddictClientService.cs
  7. 65
      src/OpenIddict.Server/OpenIddictServerHandlers.Backchannel.cs
  8. 12
      src/OpenIddict.Server/OpenIddictServerHandlers.Discovery.cs
  9. 6
      src/OpenIddict.Server/OpenIddictServerHandlers.cs
  10. 3
      src/OpenIddict.Server/OpenIddictServerService.cs
  11. 61
      test/OpenIddict.Client.Tests/OpenIddictClientHandlersTests.Backchannel.cs
  12. 61
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.Backchannel.cs

63
shared/OpenIddict.Extensions/OpenIddictHelpers.cs

@ -610,6 +610,69 @@ internal static class OpenIddictHelpers
return true;
}
/// <summary>
/// Determines whether the specified value conforms to the syntax of Bearer credentials, as defined in
/// <see href="https://datatracker.ietf.org/doc/html/rfc6750#section-2.1">RFC 6750 section 2.1</see>:
/// <c>b64token = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="</c>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><see langword="true"/> if the value is a valid b64token, <see langword="false"/> otherwise.</returns>
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;
}
/// <summary>
/// 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
/// <see href="https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.4">
/// CIBA Core 1.0 section 4</see>.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="endpoint">The parsed endpoint, if valid.</param>
/// <returns><see langword="true"/> if the endpoint is valid, <see langword="false"/> otherwise.</returns>
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;
}
/// <summary>
/// Note: this implementation was taken from ASP.NET Core.
/// </summary>

16
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -2006,12 +2006,15 @@ To send notifications using System.Net.Http, reference the 'OpenIddict.Server.Sy
<data name="ID0608" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID0609" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID0610" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID0609" xml:space="preserve">
<value>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.</value>
<data name="ID0611" xml:space="preserve">
<value>The client notification token must conform to the syntax of Bearer credentials defined in RFC 6750 section 2.1.</value>
</data>
<data name="ID0532" xml:space="preserve">
<value>The backchannel authentication request was not correctly extracted.
@ -2973,6 +2976,12 @@ Error URI: {2}</value>
<data name="ID2312" xml:space="preserve">
<value>The push token delivery mode cannot be used by client applications that require sender-constrained tokens.</value>
</data>
<data name="ID2313" xml:space="preserve">
<value>The '{0}' parameter must conform to the syntax of Bearer credentials.</value>
</data>
<data name="ID2314" xml:space="preserve">
<value>The signed authentication request uses an algorithm that is not supported by the authorization server.</value>
</data>
<data name="ID2360" xml:space="preserve">
<value>The '{0}' setting must be an absolute HTTP or HTTPS URI that doesn't contain a fragment.</value>
</data>
@ -4089,6 +4098,9 @@ This may indicate that the hashed entry is corrupted or malformed.</value>
<data name="ID6417" xml:space="preserve">
<value>An error occurred while sending the {Mode} notification of the completed backchannel authentication request '{Identifier}' to the client application '{ClientId}'.</value>
</data>
<data name="ID6418" xml:space="preserve">
<value>The signed backchannel authentication request sent by the client application '{ClientId}' was rejected because the '{Algorithm}' signing algorithm is not supported.</value>
</data>
<data name="ID6520" xml:space="preserve">
<value>A concurrency exception occurred while trying to extend the session '{Identifier}'.</value>
</data>

2
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

65
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
}
}
/// <summary>
/// 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).
/// </summary>
/// <remarks>
/// See https://openid.net/specs/openid-client-initiated-backchannel-authentication-core-1_0.html#rfc.section.10.3.
/// </remarks>
public sealed class HandleBackchannelPushedTokenResponse : IOpenIddictClientHandler<ProcessAuthenticationContext>
{
private readonly OpenIddictClientService _service;
public HandleBackchannelPushedTokenResponse(OpenIddictClientService service)
=> _service = service ?? throw new ArgumentNullException(nameof(service));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
public static OpenIddictClientHandlerDescriptor Descriptor { get; }
= OpenIddictClientHandlerDescriptor.CreateBuilder<ProcessAuthenticationContext>()
.UseSingletonHandler<HandleBackchannelPushedTokenResponse>()
.SetOrder(SendTokenRequest.Descriptor.Order + 500)
.SetType(OpenIddictClientHandlerType.BuiltIn)
.Build();
/// <inheritdoc/>
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;
}
}
}
/// <summary>
/// Contains the logic responsible for determining the set of backchannel tokens to validate.
/// </summary>
@ -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;

51
src/OpenIddict.Client/OpenIddictClientHelpers.cs

@ -15,6 +15,12 @@ namespace OpenIddict.Client;
/// </summary>
public static class OpenIddictClientHelpers
{
/// <summary>
/// Represents the maximum length, in bytes, of the JSON body accepted by
/// <see cref="CreateBackchannelNotificationAsync"/> (256 KB).
/// </summary>
public const int MaximumBackchannelNotificationLength = 256 * 1024;
/// <summary>
/// Creates a <see cref="BackchannelNotification"/> 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
/// <param name="body">The request body.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>
/// The notification or <see langword="null"/> if the request is not a valid JSON notification.
/// The notification or <see langword="null"/> if the request is not a valid JSON notification, doesn't include
/// a syntactically valid bearer token or has a body exceeding <see cref="MaximumBackchannelNotificationLength"/>.
/// </returns>
/// <remarks>
/// 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())
};
}

66
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
}
}
/// <summary>
/// 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.
/// </summary>
/// <param name="registration">The client registration.</param>
/// <param name="configuration">The server configuration.</param>
/// <param name="response">The pushed token response.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> that can be used to abort the operation.</param>
/// <returns>The validated token response.</returns>
internal async ValueTask<OpenIddictResponse> 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<IOpenIddictClientDispatcher>();
var options = scope.ServiceProvider.GetRequiredService<IOptionsMonitor<OpenIddictClientOptions>>();
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;
}
/// <summary>
/// Sends the userinfo request and retrieves the corresponding response.
/// </summary>

65
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
{
/// <summary>
/// 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).
/// </summary>
internal static ImmutableArray<string> RequestSigningAlgorithms { get; } =
[
SecurityAlgorithms.EcdsaSha256,
SecurityAlgorithms.EcdsaSha384,
SecurityAlgorithms.EcdsaSha512,
SecurityAlgorithms.RsaSha256,
SecurityAlgorithms.RsaSha384,
SecurityAlgorithms.RsaSha512,
SecurityAlgorithms.RsaSsaPssSha256,
SecurityAlgorithms.RsaSsaPssSha384,
SecurityAlgorithms.RsaSsaPssSha512
];
public static ImmutableArray<OpenIddictServerHandlerDescriptor> 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<IOpenIddictApplicationManager>()
?? 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

12
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.

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

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

61
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<OpenIddictClientService>();
using var document = JsonDocument.Parse(payload);
// Act and assert
var exception = await Assert.ThrowsAsync<OpenIddictExceptions.ProtocolException>(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()
{

61
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<HandleBackchannelAuthenticationRequestContext>(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();

Loading…
Cancel
Save