Path: redb-identity/tests/redb.Identity.Tests/Security/ValidateRequestObjectHandlerTests.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/Security/ValidateRequestObjectHandlerTests.cs
----
using System.Security.Cryptography;
using AwesomeAssertions;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using NSubstitute;
using OpenIddict.Abstractions;
using OpenIddict.Server;
using redb.Core.Models.Entities;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Models;
using redb.Identity.Core.OpenIddict;
using redb.Identity.Core.OpenIddict.Handlers;
using redb.Identity.Core.Services;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using static OpenIddict.Server.OpenIddictServerEvents;
namespace redb.Identity.Tests.Security;
///
/// Z7 phase 2 — : accepting, verifying and rejecting a
/// JAR (RFC 9101) request object on /connect/authorize .
///
/// The invariant that matters most is the first test: with EnableJar = false the answer is
/// exactly what every pre-JAR release gave — request_not_supported . The flag adds a path; it
/// does not change the default. The rest assert the security properties: no alg:none , no
/// cross-client key use, no unsigned or unverifiable object slips through.
///
///
public sealed class ValidateRequestObjectHandlerTests
{
private const string ClientId = "jar-client";
private const string Issuer = "https://id.example.com/";
private static readonly RSA _clientRsa = RSA.Create(2048);
// ── harness ──────────────────────────────────────────────────────────────
private static string SignRequestObject(
RSA rsa,
string clientId = ClientId,
string alg = "RS256",
Action>? mutate = null,
bool withExp = true)
{
var claims = new Dictionary
{
["iss"] = clientId,
["aud"] = Issuer.TrimEnd('/'),
["client_id"] = clientId,
["response_type"] = "code",
["scope"] = "openid profile",
["redirect_uri"] = "https://client.example.com/cb",
};
mutate?.Invoke(claims);
var now = DateTime.UtcNow;
var descriptor = new SecurityTokenDescriptor
{
Claims = claims,
NotBefore = now,
IssuedAt = now,
Expires = withExp ? now.AddMinutes(5) : null,
SigningCredentials = new SigningCredentials(new RsaSecurityKey(rsa), alg),
};
return new JsonWebTokenHandler().CreateToken(descriptor);
}
private static RedbObject Client(string? declaredAlg = null, params string[] requestUris) =>
new(new ApplicationProps
{
ClientId = ClientId,
RequestObjectSigningAlg = declaredAlg,
RequestUris = requestUris.Length > 0 ? requestUris : null,
});
private static ValidateAuthorizationRequestContext Context(string? requestObject, string? clientId = ClientId, string? requestUri = null)
{
var tx = new OpenIddictServerTransaction { Request = new OpenIddictRequest() };
tx.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = new TestExchange();
var ctx = new ValidateAuthorizationRequestContext(tx);
if (requestObject is not null) ctx.Request.Request = requestObject;
if (requestUri is not null) ctx.Request.RequestUri = requestUri;
if (clientId is not null) ctx.Request.ClientId = clientId;
return ctx;
}
private static ValidateRequestObjectHandler Handler(
bool enableJar = true,
RedbObject? application = null,
IReadOnlyCollection? keys = null,
JarEnforcementMode mode = JarEnforcementMode.LogOnly)
{
var apps = Substitute.For();
apps.FindByClientIdAsync(Arg.Any(), Arg.Any())
.Returns(new ValueTask(application));
var resolver = Substitute.For();
resolver.GetSigningKeysAsync(Arg.Any>(), Arg.Any(), Arg.Any())
.Returns(new ValueTask>(keys ?? []));
var options = new RedbIdentityOptions { Issuer = new Uri(Issuer) };
options.Features.EnableJar = enableJar;
options.Jar.EnforcementMode = mode;
// These tests exercise inline request objects only; a request_uri fetch would fail the test
// (the factory throws), which is what we want — no network in unit tests.
var httpFactory = Substitute.For();
httpFactory.CreateClient(Arg.Any()).Returns(_ =>
throw new InvalidOperationException("no network in unit tests"));
return new ValidateRequestObjectHandler(
apps, resolver, httpFactory, Options.Create(options), NullLogger.Instance);
}
private static IReadOnlyCollection PublicKeyOf(RSA rsa) =>
[new RsaSecurityKey(rsa.ExportParameters(false))];
// ── flag-off invariant ───────────────────────────────────────────────────
[Fact]
public async Task Flag_off_rejects_request_parameter_exactly_as_before()
{
var ctx = Context(SignRequestObject(_clientRsa));
await Handler(enableJar: false).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be(OpenIddictConstants.Errors.RequestNotSupported);
}
[Fact]
public async Task No_request_object_present_is_a_no_op()
{
var ctx = Context(requestObject: null);
await Handler(enableJar: true).HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
}
/// PAR issues urn:ietf:params:oauth:request_uri:* ; OpenIddict resolves it, we must not touch it.
[Fact]
public async Task Par_request_uri_is_left_for_openiddict()
{
var ctx = Context(requestObject: null, requestUri: "urn:ietf:params:oauth:request_uri:abc123");
await Handler(enableJar: true).HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
}
// ── happy path ───────────────────────────────────────────────────────────
[Fact]
public async Task Valid_signed_request_object_is_accepted_and_parameters_merged()
{
var ctx = Context(SignRequestObject(_clientRsa, mutate: c => c["scope"] = "openid email"));
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
// §6.1: the value from inside the signed object wins.
ctx.Request.Scope.Should().Be("openid email");
}
// ── security rejections ──────────────────────────────────────────────────
[Fact]
public async Task Unsigned_alg_none_is_rejected()
{
// A JOSE header with alg=none and no signature.
var header = Base64Url("""{"alg":"none","typ":"JWT"}""");
var body = Base64Url($$"""{"iss":"{{ClientId}}","client_id":"{{ClientId}}","response_type":"code"}""");
var ctx = Context($"{header}.{body}.");
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
[Fact]
public async Task Request_object_signed_by_a_different_key_is_rejected()
{
var attacker = RSA.Create(2048);
var ctx = Context(SignRequestObject(attacker)); // signed by attacker's key...
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx); // ...verified against the client's
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
[Fact]
public async Task Client_has_no_keys_is_rejected()
{
var ctx = Context(SignRequestObject(_clientRsa));
await Handler(application: Client(), keys: []).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
[Fact]
public async Task Missing_client_id_is_rejected()
{
var ctx = Context(SignRequestObject(_clientRsa), clientId: null);
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
[Fact]
public async Task Inner_client_id_mismatch_is_rejected()
{
// Outer client_id says jar-client; the signed object claims someone else.
var ctx = Context(SignRequestObject(_clientRsa, mutate: c => c["client_id"] = "another-client"));
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
[Fact]
public async Task Unknown_client_is_rejected()
{
var ctx = Context(SignRequestObject(_clientRsa));
await Handler(application: null, keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
// ── declared-algorithm enforcement ───────────────────────────────────────
/// LogOnly: a declared/actual mismatch is allowed through (and logged).
[Fact]
public async Task LogOnly_allows_algorithm_mismatch()
{
var ctx = Context(SignRequestObject(_clientRsa, alg: "RS256"));
await Handler(application: Client(declaredAlg: "PS256"), keys: PublicKeyOf(_clientRsa),
mode: JarEnforcementMode.LogOnly).HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
}
/// Enforce: the same mismatch is rejected — here the stored field finally does something.
[Fact]
public async Task Enforce_rejects_algorithm_mismatch()
{
var ctx = Context(SignRequestObject(_clientRsa, alg: "RS256"));
await Handler(application: Client(declaredAlg: "PS256"), keys: PublicKeyOf(_clientRsa),
mode: JarEnforcementMode.Enforce).HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
// ── request_uri (by reference) ───────────────────────────────────────────
/// A PAR-issued request_uri must be left for OpenIddict, never fetched.
[Fact]
public async Task Par_request_uri_is_not_fetched()
{
var ctx = Context(requestObject: null, requestUri: "urn:ietf:params:oauth:request_uri:xyz");
// NoNetwork factory throws on any fetch; reaching a non-rejected state proves we didn't fetch.
await Handler().HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
}
/// A request_uri pointing at an internal address is refused before any socket opens.
[Fact]
public async Task Request_uri_to_internal_target_is_refused()
{
// Default JarOptions: RequestUriAllowPrivateNetworkTargets = false.
var ctx = Context(requestObject: null, requestUri: "https://169.254.169.254/ro");
await Handler(application: Client(null, "https://169.254.169.254/ro"), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx); // NoNetwork factory would throw if a fetch were attempted
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
}
///
/// The client is checked before a request_uri is fetched: an unknown client, or a request without
/// client_id, never makes the server open a connection to the address the caller gave.
///
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task Request_uri_is_not_fetched_before_the_client_is_known(bool clientIdPresent)
{
var fetches = 0;
var handler = new StubHandler(_ =>
{
Interlocked.Increment(ref fetches);
return new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
{ Content = new System.Net.Http.StringContent(SignRequestObject(_clientRsa)) };
});
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(_ => new System.Net.Http.HttpClient(handler));
var apps = Substitute.For();
apps.FindByClientIdAsync(Arg.Any(), Arg.Any())
.Returns(new ValueTask((object?)null));
var options = new RedbIdentityOptions { Issuer = new Uri(Issuer) };
options.Features.EnableJar = true;
options.Jar.RequestUriAllowPrivateNetworkTargets = true;
options.Jar.RequestUriRequireHttps = false;
var h = new ValidateRequestObjectHandler(apps, Substitute.For(), factory,
Options.Create(options), NullLogger.Instance);
var ctx = Context(requestObject: null, clientId: clientIdPresent ? "unknown-client" : null,
requestUri: "http://127.0.0.1:9/ro");
await h.HandleAsync(ctx);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be("invalid_request_object");
fetches.Should().Be(0);
factory.DidNotReceive().CreateClient(Arg.Any());
}
/// A fetched request object is validated exactly like an inline one.
[Fact]
public async Task Fetched_request_uri_is_validated_like_inline()
{
var jwt = SignRequestObject(_clientRsa);
var handler = new StubHandler(_ => new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
{ Content = new System.Net.Http.StringContent(jwt) });
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(_ => new System.Net.Http.HttpClient(handler));
var apps = Substitute.For();
apps.FindByClientIdAsync(Arg.Any(), Arg.Any())
.Returns(new ValueTask(Client(null, "http://127.0.0.1:9/ro")));
var resolver = Substitute.For();
resolver.GetSigningKeysAsync(Arg.Any>(), Arg.Any(), Arg.Any())
.Returns(new ValueTask>(PublicKeyOf(_clientRsa)));
var options = new RedbIdentityOptions { Issuer = new Uri(Issuer) };
options.Features.EnableJar = true;
options.Jar.RequestUriAllowPrivateNetworkTargets = true; // test host is loopback
options.Jar.RequestUriRequireHttps = false;
var h = new ValidateRequestObjectHandler(apps, resolver, factory,
Options.Create(options), NullLogger.Instance);
var ctx = Context(requestObject: null, requestUri: "http://127.0.0.1:9/ro");
await h.HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
ctx.Request.Scope.Should().Be("openid profile");
}
// ── registered request_uris (OIDC DCR §2) ────────────────────────────────
private async Task<(ValidateAuthorizationRequestContext Ctx, List Fetched, ListLogger Log)> FetchWith(
string requestUri, bool requireRegistration, params string[] registered)
{
var fetched = new List();
var jwt = SignRequestObject(_clientRsa);
var stub = new StubHandler(r =>
{
lock (fetched) fetched.Add(r.RequestUri!);
return new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new System.Net.Http.StringContent(jwt) };
});
var factory = Substitute.For();
factory.CreateClient(Arg.Any()).Returns(_ => new System.Net.Http.HttpClient(stub));
var apps = Substitute.For();
apps.FindByClientIdAsync(Arg.Any(), Arg.Any())
.Returns(new ValueTask(Client(null, registered)));
var resolver = Substitute.For();
resolver.GetSigningKeysAsync(Arg.Any>(), Arg.Any(), Arg.Any())
.Returns(new ValueTask>(PublicKeyOf(_clientRsa)));
var options = new RedbIdentityOptions { Issuer = new Uri(Issuer) };
options.Features.EnableJar = true;
options.Jar.RequestUriAllowPrivateNetworkTargets = true;
options.Jar.RequestUriRequireHttps = false;
options.Jar.RequireRequestUriRegistration = requireRegistration;
var log = new ListLogger();
var h = new ValidateRequestObjectHandler(apps, resolver, factory, Options.Create(options), log);
var ctx = Context(requestObject: null, requestUri: requestUri);
await h.HandleAsync(ctx);
return (ctx, fetched, log);
}
[Fact]
public void Registration_is_required_by_default()
=> new JarOptions().RequireRequestUriRegistration.Should().BeTrue();
[Fact]
public async Task A_registered_request_uri_is_fetched()
{
var (ctx, fetched, _) = await FetchWith("http://127.0.0.1:9/ro?v=1", true, "http://127.0.0.1:9/other", "http://127.0.0.1:9/ro?v=1");
ctx.IsRejected.Should().BeFalse();
fetched.Should().ContainSingle().Which.ToString().Should().Be("http://127.0.0.1:9/ro?v=1");
}
[Theory]
[InlineData("http://127.0.0.1:9/ro/")] // trailing slash
[InlineData("http://127.0.0.1:9/RO")] // case
[InlineData("http://127.0.0.1:9/ro?v=2")] // query
[InlineData("http://127.0.0.1:9/ro#abc")] // a fragment the registered value has not
public async Task An_address_that_differs_in_any_character_is_refused_and_not_fetched(string sent)
{
var (ctx, fetched, _) = await FetchWith(sent, true, "http://127.0.0.1:9/ro");
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be(OpenIddictConstants.Errors.InvalidRequestUri);
fetched.Should().BeEmpty();
}
[Fact]
public async Task A_registered_fragment_matches_only_itself_and_is_not_fetched()
{
const string registered = "http://127.0.0.1:9/ro#q9_hash-of-content";
var (same, fetched, _) = await FetchWith(registered, true, registered);
same.IsRejected.Should().BeFalse();
fetched.Should().ContainSingle();
fetched[0].Fragment.Should().BeEmpty("the fragment identifies the registered value, it is not fetched");
fetched[0].ToString().Should().NotContain("q9_hash-of-content");
foreach (var other in new[] { "http://127.0.0.1:9/ro", "http://127.0.0.1:9/ro#other", "http://127.0.0.1:9/ro#Q9_hash-of-content" })
{
var (ctx, none, _) = await FetchWith(other, true, registered);
ctx.IsRejected.Should().BeTrue(other);
ctx.Error.Should().Be(OpenIddictConstants.Errors.InvalidRequestUri);
none.Should().BeEmpty();
}
}
[Fact]
public async Task Without_registered_values_request_uri_is_refused_while_registration_is_required()
{
var (ctx, fetched, _) = await FetchWith("http://127.0.0.1:9/ro", true);
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be(OpenIddictConstants.Errors.InvalidRequestUri);
fetched.Should().BeEmpty();
}
[Fact]
public async Task With_registration_off_an_unregistered_client_passes_with_a_warning_naming_only_the_client()
{
var (ctx, fetched, log) = await FetchWith("http://127.0.0.1:9/ro?secret=s3cr3t-value", false);
ctx.IsRejected.Should().BeFalse();
fetched.Should().ContainSingle();
var warning = log.Lines.Should().ContainSingle(l => l.Contains("without registered request_uris")).Subject;
warning.Should().Contain(ClientId).And.NotContain("127.0.0.1").And.NotContain("s3cr3t-value");
}
[Fact]
public async Task With_registration_off_a_client_with_registered_values_is_still_held_to_them()
{
var (ctx, fetched, _) = await FetchWith("http://127.0.0.1:9/elsewhere", false, "http://127.0.0.1:9/ro");
ctx.IsRejected.Should().BeTrue();
ctx.Error.Should().Be(OpenIddictConstants.Errors.InvalidRequestUri);
fetched.Should().BeEmpty();
}
[Fact]
public async Task An_inline_request_object_needs_no_registered_request_uris()
{
var ctx = Context(SignRequestObject(_clientRsa));
await Handler(application: Client(), keys: PublicKeyOf(_clientRsa)).HandleAsync(ctx);
ctx.IsRejected.Should().BeFalse();
}
private sealed class ListLogger : Microsoft.Extensions.Logging.ILogger
{
public List Lines { get; } = [];
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
public void Log(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId,
TState state, Exception? exception, Func formatter) => Lines.Add(formatter(state, exception));
}
private static string Base64Url(string s) =>
Base64UrlEncoder.Encode(System.Text.Encoding.UTF8.GetBytes(s));
private sealed class StubHandler(Func respond)
: System.Net.Http.HttpMessageHandler
{
protected override Task SendAsync(
System.Net.Http.HttpRequestMessage request, CancellationToken ct)
=> Task.FromResult(respond(request));
}
}