Path: redb-identity/tests/redb.Identity.Tests/Security/ClientKeyFetchBoundsTests.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/ClientKeyFetchBoundsTests.cs ---- using System.Net; using AwesomeAssertions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NSubstitute; using redb.Core.Models.Entities; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using Xunit; namespace redb.Identity.Tests.Security; /// /// The bounds of the jwks_uri fetch, which an unauthenticated caller can set off through a client assertion /// or a request object: the cache is reused, at most one fetch starts per MinimumRefreshInterval (forced /// refresh after an unknown kid, retry after a failure), concurrent callers share one fetch, a fetch ends at /// FetchTimeout, the guard runs before every fetch, and the log names the client and the failure class only. /// public sealed class ClientKeyFetchBoundsTests { private const string Jwks = """ {"keys":[{"kty":"RSA","use":"sig","kid":"test-1","alg":"RS256", "n":"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw", "e":"AQAB"}]} """; private sealed class Clock(DateTimeOffset now) : TimeProvider { public DateTimeOffset Now { get; set; } = now; public override DateTimeOffset GetUtcNow() => Now; } private sealed class CountingHandler(Func> respond) : HttpMessageHandler { private int _calls; public int Calls => Volatile.Read(ref _calls); protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) => respond(Interlocked.Increment(ref _calls)); } private sealed class ListLogger : ILogger { public List Lines { get; } = []; public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { lock (Lines) Lines.Add(formatter(state, exception)); } } private static HttpResponseMessage Ok(string body = Jwks) => new(HttpStatusCode.OK) { Content = new StringContent(body) }; private static RedbObject App(string uri = "https://127.0.0.1/jwks") => new(new ApplicationProps { ClientId = "fetch-client", JwksUri = uri }); private static (ClientKeyResolver Resolver, CountingHandler Handler, Clock Clock, ListLogger Log) Build( Func> respond, Action? configure = null) { var handler = new CountingHandler(respond); var factory = Substitute.For(); factory.CreateClient(Arg.Any()).Returns(_ => new HttpClient(handler, disposeHandler: false)); var options = new RedbIdentityOptions(); options.ClientKeys.AllowPrivateNetworkTargets = true; configure?.Invoke(options.ClientKeys); var clock = new Clock(DateTimeOffset.Parse("2026-11-29T12:00:00Z")); var log = new ListLogger(); return (new ClientKeyResolver(factory, Options.Create(options), log, clock), handler, clock, log); } [Fact] public async Task A_fetched_set_is_reused_until_the_cache_lifetime_ends() { var (resolver, handler, clock, _) = Build(_ => Task.FromResult(Ok())); (await resolver.GetSigningKeysAsync(App())).Should().HaveCount(1); clock.Now += TimeSpan.FromHours(11); (await resolver.GetSigningKeysAsync(App())).Should().HaveCount(1); handler.Calls.Should().Be(1); clock.Now += TimeSpan.FromHours(2); // past the 12 h default await resolver.GetSigningKeysAsync(App()); handler.Calls.Should().Be(2); } [Fact] public async Task A_forced_refresh_runs_at_most_once_per_minimum_refresh_interval() { var (resolver, handler, clock, _) = Build(_ => Task.FromResult(Ok())); await resolver.GetSigningKeysAsync(App()); for (var i = 0; i < 20; i++) await resolver.GetSigningKeysAsync(App(), forceRefresh: true); handler.Calls.Should().Be(1, "the first fetch was inside the interval; unknown kid values cannot drive fetches"); clock.Now += TimeSpan.FromMinutes(5); for (var i = 0; i < 20; i++) await resolver.GetSigningKeysAsync(App(), forceRefresh: true); handler.Calls.Should().Be(2, "one refresh per interval"); } [Fact] public async Task A_failed_fetch_is_not_retried_inside_the_interval_and_the_log_names_the_failure_class_only() { var (resolver, handler, clock, log) = Build(_ => Task.FromResult( new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("secret-body-text") })); for (var i = 0; i < 20; i++) (await resolver.GetSigningKeysAsync(App())).Should().BeEmpty("fail closed"); handler.Calls.Should().Be(1); clock.Now += TimeSpan.FromMinutes(5); await resolver.GetSigningKeysAsync(App()); handler.Calls.Should().Be(2); log.Lines.Should().Contain(l => l.Contains("fetch-client") && l.Contains("HTTP 500")); log.Lines.Should().NotContain(l => l.Contains("secret-body-text")); } [Fact] public async Task A_failed_refresh_keeps_the_last_good_set() { var (resolver, _, clock, _) = Build(n => Task.FromResult(n == 1 ? Ok() : new HttpResponseMessage(HttpStatusCode.BadGateway))); await resolver.GetSigningKeysAsync(App()); clock.Now += TimeSpan.FromHours(13); (await resolver.GetSigningKeysAsync(App())).Should().HaveCount(1); } [Fact] public async Task Concurrent_callers_share_one_fetch() { var release = new TaskCompletionSource(); var (resolver, handler, _, _) = Build(async _ => { await release.Task; return Ok(); }); var calls = Enumerable.Range(0, 50).Select(_ => resolver.GetSigningKeysAsync(App()).AsTask()).ToArray(); await Task.Delay(100); release.SetResult(); var results = await Task.WhenAll(calls); handler.Calls.Should().Be(1); results.Should().AllSatisfy(r => r.Should().HaveCount(1)); } [Fact] public async Task A_fetch_ends_at_the_timeout() { var (resolver, _, _, log) = Build(async _ => { await Task.Delay(TimeSpan.FromSeconds(30)); return Ok(); }, o => o.FetchTimeout = TimeSpan.FromMilliseconds(200)); var started = DateTime.UtcNow; (await resolver.GetSigningKeysAsync(App())).Should().BeEmpty(); (DateTime.UtcNow - started).Should().BeLessThan(TimeSpan.FromSeconds(10)); log.Lines.Should().Contain(l => l.Contains("timeout")); } [Fact] public async Task The_guard_runs_before_every_fetch() { // The address is refused at fetch time, not only at registration: here the private-target rule. var (resolver, handler, _, log) = Build(_ => Task.FromResult(Ok()), o => o.AllowPrivateNetworkTargets = false); (await resolver.GetSigningKeysAsync(App())).Should().BeEmpty(); handler.Calls.Should().Be(0); log.Lines.Should().Contain(l => l.Contains("Refusing to fetch jwks_uri") && l.Contains("fetch-client")); } [Fact] public async Task An_inline_set_is_the_only_source() { var (resolver, handler, _, _) = Build(_ => Task.FromResult(Ok())); var app = new RedbObject(new ApplicationProps { ClientId = "both", JsonWebKeySet = """{"keys":[]}""", JwksUri = "https://127.0.0.1/jwks", }); (await resolver.GetSigningKeysAsync(app, forceRefresh: true)).Should().BeEmpty(); handler.Calls.Should().Be(0); } [Fact] public async Task The_cache_holds_at_most_MaxCachedKeySets_addresses_and_a_dropped_one_is_fetched_again() { var (resolver, handler, clock, _) = Build(_ => Task.FromResult(Ok()), o => o.MaxCachedKeySets = 3); RedbObject At(int i) => App($"https://127.0.0.1/jwks/{i}"); for (var i = 0; i < 10; i++) { clock.Now += TimeSpan.FromSeconds(1); await resolver.GetSigningKeysAsync(At(i)); resolver.CachedKeySetCount.Should().BeLessThanOrEqualTo(3); } handler.Calls.Should().Be(10); // The most recent addresses are kept; the first one was dropped and is simply fetched again. await resolver.GetSigningKeysAsync(At(9)); handler.Calls.Should().Be(10, "address 9 is still cached"); (await resolver.GetSigningKeysAsync(At(0))).Should().HaveCount(1); handler.Calls.Should().Be(11, "address 0 was dropped and is fetched again"); resolver.CachedKeySetCount.Should().Be(3); } [Fact] public async Task Expired_entries_are_dropped_before_recently_used_ones() { var (resolver, handler, clock, _) = Build(_ => Task.FromResult(Ok()), o => o.MaxCachedKeySets = 2); await resolver.GetSigningKeysAsync(App("https://127.0.0.1/old")); clock.Now += TimeSpan.FromHours(13); // "old" is past its cache lifetime await resolver.GetSigningKeysAsync(App("https://127.0.0.1/a")); clock.Now += TimeSpan.FromSeconds(1); await resolver.GetSigningKeysAsync(App("https://127.0.0.1/b")); var calls = handler.Calls; await resolver.GetSigningKeysAsync(App("https://127.0.0.1/a")); handler.Calls.Should().Be(calls, "the expired entry went first, so 'a' is still cached"); } [Fact] public async Task A_set_without_usable_signing_keys_counts_as_a_failed_fetch() { var (resolver, _, clock, log) = Build(n => Task.FromResult(n == 1 ? Ok() : Ok("""{"keys":[{"kty":"oct","k":"AAAA"}]}"""))); await resolver.GetSigningKeysAsync(App()); clock.Now += TimeSpan.FromHours(13); (await resolver.GetSigningKeysAsync(App())).Should().HaveCount(1, "the last good set is kept"); log.Lines.Should().Contain(l => l.Contains("no usable signing keys")); } }