Path: redb-identity/tests/redb.Identity.Tests/Services/BackchannelLogoutDispatcherTests.cs
Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Services/BackchannelLogoutDispatcherTests.cs
----
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Security.Cryptography;
using AwesomeAssertions;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using NSubstitute;
using OpenIddict.Server;
using redb.Core;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Query;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Services;
///
/// Unit tests for — verifies that:
/// only RPs with BackchannelLogoutUri set receive logout_token POSTs;
/// the POST body is form-urlencoded with a valid signed JWT;
/// downstream HTTP failures don't break the logout flow.
///
public sealed class BackchannelLogoutDispatcherTests
{
/// The user's public subject: what the RP saw as sub in its id_token and matches the logout token against.
private static readonly Guid Subject = Guid.Parse("7d6a1f2e-3b4c-4d5e-8f90-a1b2c3d4e5f6");
private static (BackchannelLogoutDispatcher dispatcher, RecordingHandler handler, IRedbService redb, List> apps)
CreateDispatcher(SecurityKey? customKey = null, Action? configure = null)
{
var rsa = RSA.Create(2048);
var key = customKey ?? new RsaSecurityKey(rsa.ExportParameters(true)) { KeyId = "test-rsa" };
var creds = new SigningCredentials(key, SecurityAlgorithms.RsaSha256);
var serverOptions = new OpenIddictServerOptions { Issuer = new Uri("https://idp.example.com") };
serverOptions.SigningCredentials.Add(creds);
var monitor = Substitute.For>();
monitor.CurrentValue.Returns(serverOptions);
var tokenBuilder = new LogoutTokenBuilder(monitor);
var handler = new RecordingHandler();
var httpClient = new HttpClient(handler);
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(httpClient);
// The example.com relying parties below are not resolved: private targets are allowed unless a test says
// otherwise, so the guard checks only scheme and shape and these tests need no DNS.
var options = new redb.Identity.Core.Configuration.RedbIdentityOptions();
options.BackchannelLogout.AllowPrivateNetworkTargets = true;
configure?.Invoke(options.BackchannelLogout);
var dispatcher = new BackchannelLogoutDispatcher(factory, tokenBuilder, Options.Create(options));
var redb = Substitute.For();
// Stub the batched Query().WhereInRedb(...).ToListAsync() pipeline.
// Tests register apps via StubApp which appends them to this shared list; the query
// stub then returns the entire list (the dispatcher already filters on its own side).
var apps = new List>();
var queryable = Substitute.For>();
queryable.WhereInRedb(Arg.Any>>(),
Arg.Any>())
.Returns(queryable);
queryable.ToListAsync().Returns(_ => apps.ToList());
redb.Query().Returns(queryable);
return (dispatcher, handler, redb, apps);
}
private static void StubApp(List> apps, long id, string clientId,
string? backchannelUri, bool sessionRequired = false)
{
apps.Add(new RedbObject
{
Id = id,
Name = "App " + id,
value_string = clientId,
Props = new ApplicationProps
{
ClientId = clientId,
BackchannelLogoutUri = backchannelUri,
BackchannelLogoutSessionRequired = sessionRequired
}
});
}
[Fact]
public async Task Dispatch_PostsLogoutToken_ToConfiguredRPs()
{
var (dispatcher, handler, redb, apps) = CreateDispatcher();
StubApp(apps, 100, "client-a", "https://rp-a.example.com/logout");
StubApp(apps, 101, "client-b", "https://rp-b.example.com/logout");
var delivered = await dispatcher.DispatchAsync(redb, Subject, sessionId: 0,
new[] { 100L, 101L });
delivered.Should().Be(2);
handler.Requests.Should().HaveCount(2);
handler.Requests.Select(r => r.RequestUri!.ToString()).Should().BeEquivalentTo(new[]
{
"https://rp-a.example.com/logout",
"https://rp-b.example.com/logout"
});
}
[Fact]
public async Task Dispatch_SkipsRPs_WithoutBackchannelLogoutUri()
{
var (dispatcher, handler, redb, apps) = CreateDispatcher();
StubApp(apps, 200, "client-c", backchannelUri: null);
StubApp(apps, 201, "client-d", "https://rp-d.example.com/logout");
var delivered = await dispatcher.DispatchAsync(redb, Subject, sessionId: 0,
new[] { 200L, 201L });
delivered.Should().Be(1);
handler.Requests.Should().ContainSingle()
.Which.RequestUri!.ToString().Should().Be("https://rp-d.example.com/logout");
}
[Fact]
public async Task Dispatch_SendsValidLogoutToken_AsFormUrlEncoded()
{
var (dispatcher, handler, redb, apps) = CreateDispatcher();
StubApp(apps, 300, "client-e", "https://rp-e.example.com/logout", sessionRequired: true);
await dispatcher.DispatchAsync(redb, Subject, sessionId: 555, new[] { 300L });
var req = handler.Requests.Single();
req.Method.Should().Be(HttpMethod.Post);
req.Content!.Headers.ContentType!.MediaType.Should().Be("application/x-www-form-urlencoded");
var body = handler.RequestBodies.Single();
body.Should().StartWith("logout_token=");
var token = System.Web.HttpUtility.ParseQueryString(body)["logout_token"];
token.Should().NotBeNullOrEmpty();
var jwt = new JwtSecurityTokenHandler { MapInboundClaims = false }.ReadJwtToken(token);
jwt.Audiences.Should().ContainSingle().Which.Should().Be("client-e");
// Back-Channel Logout 1.0 §2.4: sub identifies the End-User as the RP knows them, i.e. the same
// value as the id_token's sub — the public GUID, never the internal user id.
jwt.Payload["sub"].Should().Be(Subject.ToString("D"));
jwt.Payload["sid"].Should().Be("555"); // included because sessionRequired=true and sessionId>0
}
[Fact]
public async Task Dispatch_OmitsSid_WhenSessionRequiredFalse()
{
var (dispatcher, handler, redb, apps) = CreateDispatcher();
StubApp(apps, 400, "client-f", "https://rp-f.example.com/logout", sessionRequired: false);
await dispatcher.DispatchAsync(redb, Subject, sessionId: 999, new[] { 400L });
var body = handler.RequestBodies.Single();
var token = System.Web.HttpUtility.ParseQueryString(body)["logout_token"];
var jwt = new JwtSecurityTokenHandler { MapInboundClaims = false }.ReadJwtToken(token);
jwt.Payload.ContainsKey("sid").Should().BeFalse();
}
[Fact]
public async Task Dispatch_FailedDelivery_DoesNotThrow_AndReportsZeroDelivered()
{
var (dispatcher, handler, redb, apps) = CreateDispatcher();
handler.NextResponseStatus = HttpStatusCode.ServiceUnavailable;
StubApp(apps, 500, "client-g", "https://rp-down.example.com/logout");
var delivered = await dispatcher.DispatchAsync(redb, Subject, sessionId: 0, new[] { 500L });
delivered.Should().Be(0);
handler.Requests.Should().HaveCount(1); // attempt was made
}
[Fact]
public async Task Dispatch_NoApplications_ReturnsZero_NoHttpCalls()
{
var (dispatcher, handler, redb, apps) = CreateDispatcher();
var delivered = await dispatcher.DispatchAsync(redb, Subject, 0, Array.Empty());
delivered.Should().Be(0);
handler.Requests.Should().BeEmpty();
}
///
/// Captures every HTTP request and replies with a configurable status (200 by default).
///
private sealed class RecordingHandler : HttpMessageHandler
{
public List Requests { get; } = new();
public List RequestBodies { get; } = new();
public HttpStatusCode NextResponseStatus { get; set; } = HttpStatusCode.OK;
protected override async Task SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// Read body NOW because the dispatcher's `using var content` will dispose it
// before the test can reach it.
var body = request.Content is null
? string.Empty
: await request.Content.ReadAsStringAsync(cancellationToken);
Requests.Add(request);
RequestBodies.Add(body);
return new HttpResponseMessage(NextResponseStatus);
}
}
// ── outbound guard before every POST ──
[Fact]
public async Task Dispatch_RefusesAPrivateTarget_AndStillDeliversToTheOthers()
{
var (dispatcher, handler, redb, apps) = CreateDispatcher(configure: o => o.AllowPrivateNetworkTargets = false);
StubApp(apps, 700, "client-internal", "https://127.0.0.1/logout");
StubApp(apps, 701, "client-metadata", "https://169.254.169.254/logout");
StubApp(apps, 702, "client-public", "https://203.0.113.10/logout");
var delivered = await dispatcher.DispatchAsync(redb, Subject, sessionId: 0, new[] { 700L, 701L, 702L });
delivered.Should().Be(1, "the refused relying parties are skipped, the logout goes on");
handler.Requests.Should().ContainSingle().Which.RequestUri!.Host.Should().Be("203.0.113.10");
}
[Fact]
public async Task Dispatch_RefusesPlainHttp_WhileHttpsIsRequired()
{
var (dispatcher, handler, redb, apps) = CreateDispatcher();
StubApp(apps, 710, "client-http", "http://rp-http.example.com/logout");
(await dispatcher.DispatchAsync(redb, Subject, sessionId: 0, new[] { 710L })).Should().Be(0);
handler.Requests.Should().BeEmpty();
}
[Fact]
public async Task Dispatch_AllowsPlainHttp_WhenConfigured()
{
var (dispatcher, handler, redb, apps) = CreateDispatcher(configure: o => o.RequireHttps = false);
StubApp(apps, 720, "client-http", "http://rp-http.example.com/logout");
(await dispatcher.DispatchAsync(redb, Subject, sessionId: 0, new[] { 720L })).Should().Be(1);
handler.Requests.Should().ContainSingle();
}
}