Path: redb-identity/tests/redb.Identity.Tests/FullStack/PrivateKeyJwtJwksUriTests.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/FullStack/PrivateKeyJwtJwksUriTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Net.Sockets; using System.Security.Cryptography; using System.Text.Json; using AwesomeAssertions; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// RFC 7591 ยง2 / RFC 7523: a client registered dynamically with private_key_jwt and a jwks_uri /// authenticates at the token endpoint with the keys published there; a rotated key is picked up by the one bounded /// refresh an unknown kid triggers; an assertion signed by a key the client never published is refused with /// invalid_client. The key server is a loopback listener. /// [Collection("ProductionHttp")] public sealed class PrivateKeyJwtJwksUriTests : IDisposable { private readonly ProductionHttpFixture _fx; private readonly HttpListener _keys = new(); private readonly string _jwksUri; private volatile string _published = """{"keys":[]}"""; private int _fetches; public PrivateKeyJwtJwksUriTests(ProductionHttpFixture fx) { _fx = fx; var port = FreePort(); _jwksUri = $"http://127.0.0.1:{port}/jwks"; _keys.Prefixes.Add($"http://127.0.0.1:{port}/"); _keys.Start(); _ = Task.Run(ServeAsync); } public void Dispose() => _keys.Close(); private async Task ServeAsync() { while (_keys.IsListening) { HttpListenerContext ctx; try { ctx = await _keys.GetContextAsync(); } catch { return; } Interlocked.Increment(ref _fetches); var body = System.Text.Encoding.UTF8.GetBytes(_published); ctx.Response.ContentType = "application/json"; await ctx.Response.OutputStream.WriteAsync(body); ctx.Response.Close(); } } private static int FreePort() { using var l = new TcpListener(IPAddress.Loopback, 0); l.Start(); return ((IPEndPoint)l.LocalEndpoint).Port; } private static (RSA Rsa, string Kid) NewKey(string kid) => (RSA.Create(2048), kid); private void Publish(params (RSA Rsa, string Kid)[] keys) { var jwks = keys.Select(k => { var jwk = JsonWebKeyConverter.ConvertFromRSASecurityKey(new RsaSecurityKey(k.Rsa.ExportParameters(false)) { KeyId = k.Kid }); return new { kty = jwk.Kty, use = "sig", kid = k.Kid, alg = "RS256", n = jwk.N, e = jwk.E }; }); _published = JsonSerializer.Serialize(new { keys = jwks }); } private string Assertion(string clientId, (RSA Rsa, string Kid) key) => new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor { Issuer = clientId, Audience = $"http://localhost:{_fx.Port}/", Claims = new Dictionary { ["sub"] = clientId, ["jti"] = Guid.NewGuid().ToString("N") }, Expires = DateTime.UtcNow.AddMinutes(2), TokenType = "client-authentication+jwt", SigningCredentials = new SigningCredentials(new RsaSecurityKey(key.Rsa) { KeyId = key.Kid }, SecurityAlgorithms.RsaSha256), }); private async Task RegisterAsync() { using var req = new HttpRequestMessage(HttpMethod.Post, "/connect/register") { Content = JsonContent.Create(new { redirect_uris = new[] { "http://localhost/callback" }, grant_types = new[] { "client_credentials" }, token_endpoint_auth_method = "private_key_jwt", jwks_uri = _jwksUri, scope = "openid", }), }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ProductionHttpFixture.DynamicRegAccessToken); using var resp = await _fx.Http.SendAsync(req); var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.Created, body); var json = JsonDocument.Parse(body).RootElement; json.GetProperty("jwks_uri").GetString().Should().Be(_jwksUri, "the stored address is answered"); json.TryGetProperty("client_secret", out _).Should().BeFalse(); return json.GetProperty("client_id").GetString()!; } private async Task<(HttpStatusCode Status, string Body)> TokenAsync(string clientId, string assertion) { using var resp = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = clientId, ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", ["client_assertion"] = assertion, })); return (resp.StatusCode, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task A_client_with_jwks_uri_authenticates_and_follows_a_key_rotation() { var first = NewKey("k1"); Publish(first); var clientId = await RegisterAsync(); var (ok, okBody) = await TokenAsync(clientId, Assertion(clientId, first)); ok.Should().Be(HttpStatusCode.OK, okBody); // The client rotates: the new key is published, the old one withdrawn. var second = NewKey("k2"); Publish(second); await Task.Delay(TimeSpan.FromSeconds(1.2)); // past the fixture's 1 s refresh interval var (rotated, rotatedBody) = await TokenAsync(clientId, Assertion(clientId, second)); rotated.Should().Be(HttpStatusCode.OK, rotatedBody); } [Fact] public async Task An_assertion_from_an_unpublished_key_is_refused_and_cannot_drive_fetches() { Publish(NewKey("published")); var clientId = await RegisterAsync(); var stranger = NewKey("made-up"); var before = Volatile.Read(ref _fetches); for (var i = 0; i < 10; i++) { var (status, body) = await TokenAsync(clientId, Assertion(clientId, (stranger.Rsa, $"made-up-{i}"))); ((int)status).Should().BeOneOf(400, 401); body.Should().Contain("invalid_client"); } (Volatile.Read(ref _fetches) - before).Should().BeLessThanOrEqualTo(2, "ten unknown kid values inside one refresh interval cause at most the first fetch and one refresh"); } }