Bundle: redb-identity / tests/redb.Identity.Tests (tests.redb.Identity.Tests.txt), 233 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-identity/_index.txt ==== Path: redb-identity/tests/redb.Identity.Tests/Architecture/HttpRouteReservedHeaderStripTests.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/Architecture/HttpRouteReservedHeaderStripTests.cs ---- using System.Text.RegularExpressions; using AwesomeAssertions; using Xunit; namespace redb.Identity.Tests.Architecture; /// /// Every HTTP route strips the reserved inbound headers before it does anything else. /// /// The HTTP consumer copies every request header into the exchange verbatim, while processors downstream /// trust a handful of names as if a facade had set them — session_user_id becomes the principal, /// user_id / ip_address / user_agent sign the audit log. The facade's answer is /// PropagateCorrelationId, whose first act is to remove those names, documented as "the first /// processor on every HTTP route — so no route can forget it". It was a promise kept by hand: the /// management catch-all (http-management-api) and the SCIM catch-all (http-scim-api) /// never called it. Nothing on those two routes reads a reserved name today, so this was a structural /// gap rather than an exploit — which is exactly why it needs a check: the next processor that reads /// one there would have trusted whatever the caller sent. /// /// /// Read from source, like the other fitness tests here: for each From(...) in the HTTP route /// builder, the very first call after RouteId(...) must be the strip — whatever that call is, /// not only a step from some list of DSL names, because a method the list does not know would otherwise /// pass unseen in front of the strip. A route without a RouteId is an offender too: every route /// here is named, and the supervisor's error attribution depends on it. /// /// public class HttpRouteReservedHeaderStripTests { private const string Strip = "Process(HttpIdentityProcessors.PropagateCorrelationId)"; /// /// From the end of RouteId(...) to the start of the next fluent call: optional statement end, /// optional receiver (route.), then the dot. What follows must be the strip. /// private static readonly Regex NextCall = new(@"^\s*;?\s*(?:\w+\s*)?\.", RegexOptions.Compiled); private static string LocateRouteBuilder() { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null) { foreach (var candidate in new[] { Path.Combine(dir.FullName, "src", "redb.Identity.Http", "HttpFacadeRouteBuilder.cs"), Path.Combine(dir.FullName, "redb.Identity", "src", "redb.Identity.Http", "HttpFacadeRouteBuilder.cs"), }) { if (File.Exists(candidate)) return candidate; } dir = dir.Parent; } throw new InvalidOperationException("Could not locate HttpFacadeRouteBuilder.cs from the test base directory."); } [Fact] public void Every_http_route_strips_the_reserved_headers_first() { var source = File.ReadAllText(LocateRouteBuilder()); // Comments talk about From(...) and the strip constantly; only code counts. source = Regex.Replace(source, @"/\*.*?\*/", string.Empty, RegexOptions.Singleline); source = Regex.Replace(source, @"//.*?$", string.Empty, RegexOptions.Multiline); var starts = Regex.Matches(source, @"\bFrom\(").Select(m => m.Index).ToList(); starts.Should().NotBeEmpty("the HTTP facade declares its routes in this file"); var offenders = new List(); for (var i = 0; i < starts.Count; i++) { var end = i + 1 < starts.Count ? starts[i + 1] : source.Length; var route = source[starts[i]..end]; var routeIdCall = Regex.Match(route, @"\.RouteId\(([^)]*)\)"); if (!routeIdCall.Success) { offenders.Add(" " + route[..Math.Min(80, route.Length)].ReplaceLineEndings(" ")); continue; } var afterRouteId = route[(routeIdCall.Index + routeIdCall.Length)..]; var next = NextCall.Match(afterRouteId); var stripsFirst = next.Success && afterRouteId.AsSpan(next.Length).StartsWith(Strip, StringComparison.Ordinal); if (!stripsFirst) offenders.Add(routeIdCall.Groups[1].Value); } // BeEmpty names only the first offender; the list is spelled out so a failure shows all of them. offenders.Should().BeEmpty( "every HTTP route must remove the caller-supplied reserved headers before any step can read them; " + "a route that skips it trusts whatever the caller sent for session_user_id, user_id, ip_address and " + "the rest. Routes without the strip first: {0}", string.Join(", ", offenders)); } } Path: redb-identity/tests/redb.Identity.Tests/Architecture/ReferenceTokenGuardTests.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/Architecture/ReferenceTokenGuardTests.cs ---- using System.Text.RegularExpressions; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using OpenIddict.Server; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Architecture; /// /// The resource side's entry check (ValidateTokenEntryStatusHandler) reads only the token's object row and does not /// refuse an entry that carries a ReferenceId, as OpenIddict's built-in RestoreTokenEntryProperties does (a leaked /// reference payload presented as a plain token). That is sound only while the server issues no reference access or /// refresh tokens. These tests fail the day either is turned on. /// [Collection("ProductionHttp")] public class ReferenceTokenGuardTests { private const string Reason = "reference access or refresh tokens are on: ValidateTokenEntryStatusHandler must then also refuse a token " + "entry that carries a ReferenceId when the token was not validated as a reference token, as OpenIddict's " + "RestoreTokenEntryProperties does"; private readonly ProductionHttpFixture _fx; public ReferenceTokenGuardTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public void The_server_issues_no_reference_access_or_refresh_tokens() { var options = _fx.ServiceProvider.GetRequiredService>().CurrentValue; options.UseReferenceAccessTokens.Should().BeFalse(Reason); options.UseReferenceRefreshTokens.Should().BeFalse(Reason); } [Fact] public void No_source_turns_reference_tokens_on() { // The options check above sees the test host's configuration only; a switch behind a setting the tests do // not set is caught here. var root = LocateSourceRoot(); var sep = Path.DirectorySeparatorChar; var pattern = new Regex(@"\b(UseReferenceAccessTokens|UseReferenceRefreshTokens)\b", RegexOptions.Compiled); var offenders = Directory.EnumerateFiles(root, "*.cs", SearchOption.AllDirectories) .Where(f => !f.Contains($"{sep}obj{sep}", StringComparison.Ordinal) && !f.Contains($"{sep}bin{sep}", StringComparison.Ordinal)) .Where(f => pattern.IsMatch(Regex.Replace(File.ReadAllText(f), @"//[^\n]*", string.Empty))) .Select(f => Path.GetRelativePath(root, f)) .ToList(); offenders.Should().BeEmpty(Reason); } private static string LocateSourceRoot() { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null) { var candidate = Path.Combine(dir.FullName, "redb.Identity", "src"); if (Directory.Exists(Path.Combine(candidate, "redb.Identity.Core"))) return candidate; candidate = Path.Combine(dir.FullName, "src"); if (Directory.Exists(Path.Combine(candidate, "redb.Identity.Core"))) return candidate; dir = dir.Parent; } throw new InvalidOperationException("Could not locate redb.Identity/src from the test base directory."); } } Path: redb-identity/tests/redb.Identity.Tests/Architecture/TokenStatusWriteTests.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/Architecture/TokenStatusWriteTests.cs ---- using System.Text.RegularExpressions; using AwesomeAssertions; using OpenIddict.Abstractions; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Stores; using Xunit; namespace redb.Identity.Tests.Architecture; /// /// A token's status is written only through , which keeps the object row's /// value_bool in step with it; the resource side's entry check reads only that column. A status written past /// the helper would leave the column stale and a revoked token accepted. /// /// The scan is by text, so it fails closed: every .Props.Status = in the Identity sources outside the helper /// has to be one of the known writes of another kind of object (sessions, authorizations), named by file and /// variable below. A new write of a session or authorization status is added to that list; a write of a token's /// status goes through the helper. /// /// public class TokenStatusWriteTests { private static readonly string SourceRoot = LocateSourceRoot(); // file name -> variables whose Props.Status is written there and which are not tokens. private static readonly Dictionary OtherObjectStatusWrites = new(StringComparer.Ordinal) { ["SessionCleanupProcessor.cs"] = ["s"], ["ConsentService.cs"] = ["target"], ["SessionService.cs"] = ["s", "session", "auth"], ["RedbAuthorizationStore.cs"] = ["target", "authorization"], }; private static readonly Regex StatusWrite = new(@"(?[\w\.\]\)]+?)\.Props\.Status\s*=(?![=>])", RegexOptions.Compiled); private static readonly Regex TokenPropsInitializerStatus = new(@"new\s+TokenProps\s*(\(\s*\))?\s*\{[^}]*\bStatus\s*=", RegexOptions.Compiled | RegexOptions.Singleline); private static string LocateSourceRoot() { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null) { var candidate = Path.Combine(dir.FullName, "redb.Identity", "src"); if (Directory.Exists(Path.Combine(candidate, "redb.Identity.Core"))) return candidate; candidate = Path.Combine(dir.FullName, "src"); if (Directory.Exists(Path.Combine(candidate, "redb.Identity.Core"))) return candidate; dir = dir.Parent; } throw new InvalidOperationException("Could not locate redb.Identity/src from the test base directory."); } private static IEnumerable<(string Path, string Source)> Sources() { var sep = Path.DirectorySeparatorChar; foreach (var file in Directory.EnumerateFiles(SourceRoot, "*.cs", SearchOption.AllDirectories)) { if (file.Contains($"{sep}obj{sep}", StringComparison.Ordinal) || file.Contains($"{sep}bin{sep}", StringComparison.Ordinal)) continue; var source = File.ReadAllText(file); source = Regex.Replace(source, @"/\*.*?\*/", string.Empty, RegexOptions.Singleline); source = Regex.Replace(source, @"//[^\n]*", string.Empty); yield return (file, source); } } [Fact] public void A_token_status_is_written_only_through_the_helper() { var offenders = new List(); foreach (var (path, source) in Sources()) { var name = Path.GetFileName(path); if (name == "TokenStatus.cs") continue; OtherObjectStatusWrites.TryGetValue(name, out var allowed); foreach (Match m in StatusWrite.Matches(source)) { var target = m.Groups["target"].Value; if (allowed is null || !allowed.Contains(target, StringComparer.Ordinal)) offenders.Add($"{Path.GetRelativePath(SourceRoot, path)}: {target}.Props.Status ="); } if (TokenPropsInitializerStatus.IsMatch(source)) offenders.Add($"{Path.GetRelativePath(SourceRoot, path)}: new TokenProps {{ Status = ... }}"); } offenders.Should().BeEmpty( "a token's status is set with TokenStatus.Set, which keeps value_bool in step; a session or " + "authorization status write is added to OtherObjectStatusWrites"); } [Fact] public void The_known_other_writes_still_exist() { // The list stays exact: an entry whose write is gone is removed, so the list cannot hide a later token write // under an old name. var seen = new HashSet(StringComparer.Ordinal); foreach (var (path, source) in Sources()) { var name = Path.GetFileName(path); foreach (Match m in StatusWrite.Matches(source)) seen.Add(name + ":" + m.Groups["target"].Value); } foreach (var (file, variables) in OtherObjectStatusWrites) foreach (var variable in variables) seen.Should().Contain(file + ":" + variable); } [Theory] [InlineData(OpenIddictConstants.Statuses.Valid, true)] [InlineData(OpenIddictConstants.Statuses.Revoked, false)] [InlineData(OpenIddictConstants.Statuses.Redeemed, false)] [InlineData(OpenIddictConstants.Statuses.Inactive, false)] [InlineData(OpenIddictConstants.Statuses.Rejected, false)] [InlineData(null, false)] public void The_helper_mirrors_valid_only(string? status, bool expected) { var token = new RedbObject(new TokenProps()); TokenStatus.Set(token, status); token.Props.Status.Should().Be(status); token.value_bool.Should().Be(expected); } } Path: redb-identity/tests/redb.Identity.Tests/Architecture/TransportBoundaryTests.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/Architecture/TransportBoundaryTests.cs ---- using System.Text.RegularExpressions; using AwesomeAssertions; using Xunit; using redb.Identity.Contracts.Routes; namespace redb.Identity.Tests.Architecture; /// /// Architectural fitness tests guarding the redb.Identity.Core transport boundary. /// /// Identity servers live in the HTTP world by nature — the OAuth2 / OIDC / SCIM / RFC /// specifications are defined in HTTP terms (status codes, content-types, headers), so an /// HTTP vocabulary inside core is legitimate. What is NOT legitimate is wire-encoding /// the response into string/byte[] directly in core: that locks the response into JSON and /// breaks the gRPC / Kafka / MQTT facade adapters, which must be able to override the /// native serialization. /// /// /// These tests scan redb.Identity.Core source for forbidden assignments to /// exchange.Out.Body. Domain JSON usage (PROPS column encoding, DataProtection blobs, /// hashing, JsonElement composition) is allowed — only Body-targeted wire encoding is banned. /// /// public class TransportBoundaryTests { private static readonly string CoreSourceRoot = LocateCoreSourceRoot(); private static string LocateCoreSourceRoot() { // Walk up from the test assembly location until we find redb.Identity.Core. var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null) { var candidate = Path.Combine(dir.FullName, "src", "redb.Identity.Core"); if (Directory.Exists(candidate)) return candidate; // Also try repo-root layout: /redb.Identity/src/redb.Identity.Core var repoCandidate = Path.Combine(dir.FullName, "redb.Identity", "src", "redb.Identity.Core"); if (Directory.Exists(repoCandidate)) return repoCandidate; dir = dir.Parent; } throw new InvalidOperationException( "Could not locate redb.Identity.Core source root from test base directory."); } private static IEnumerable<(string Path, string Source)> EnumerateCoreSources() { foreach (var file in Directory.EnumerateFiles(CoreSourceRoot, "*.cs", SearchOption.AllDirectories)) { // Skip generated artefacts. if (file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) continue; if (file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) continue; yield return (file, StripComments(File.ReadAllText(file))); } } /// /// Strips line and block comments (including XML doc comments) so fitness regexes only /// match real code, not commentary that legitimately mentions HTTP types or JSON encoding. /// String literals are left in place — wire-encoding done via interpolated strings would /// still surface as code. /// private static string StripComments(string source) { // Block /* ... */ source = Regex.Replace(source, @"/\*.*?\*/", string.Empty, RegexOptions.Singleline); // Line // ... and /// ... source = Regex.Replace(source, @"//.*$", string.Empty, RegexOptions.Multiline); return source; } [Fact] public void CoreSource_DoesNotAssignSerializedJsonStringToOutBody() { // exchange.Out.Body = JsonSerializer.Serialize(...) ← forbidden (locks transport to JSON string). // SerializeToElement / SerializeToNode / SerializeToUtf8Bytes are caught elsewhere or allowed. var pattern = new Regex( @"\.Out\.Body\s*=\s*JsonSerializer\.Serialize\b(?!ToElement|ToNode|ToUtf8Bytes)", RegexOptions.Compiled); var violations = new List(); foreach (var (path, source) in EnumerateCoreSources()) { foreach (Match m in pattern.Matches(source)) { var line = LineOf(source, m.Index); violations.Add($"{path}:{line} -> {m.Value}"); } } violations.Should().BeEmpty( "core processors must keep exchange.Out.Body as a typed object; wire-encoding to JSON " + "string belongs to the transport facade or an explicit .Marshal(...) DSL step"); } [Fact] public void CoreSource_DoesNotAssignUtf8BytesToOutBody() { // exchange.Out.Body = JsonSerializer.SerializeToUtf8Bytes(...) ← forbidden (locks transport to JSON bytes). var pattern = new Regex( @"\.Out\.Body\s*=\s*JsonSerializer\.SerializeToUtf8Bytes\b", RegexOptions.Compiled); var violations = new List(); foreach (var (path, source) in EnumerateCoreSources()) { foreach (Match m in pattern.Matches(source)) { var line = LineOf(source, m.Index); violations.Add($"{path}:{line} -> {m.Value}"); } } violations.Should().BeEmpty( "core processors must keep exchange.Out.Body as a typed object; pre-encoding to UTF-8 " + "bytes locks the response into a single wire format"); } [Fact] public void CoreSource_DoesNotReferenceAspNetCoreHttp() { // No HttpContext / IHttpContextAccessor leakage — transport is owned by facades. var usingPattern = new Regex( @"^\s*using\s+Microsoft\.AspNetCore\.Http\b", RegexOptions.Compiled | RegexOptions.Multiline); var typeRefPattern = new Regex( @"\b(HttpContext|IHttpContextAccessor)\b", RegexOptions.Compiled); var violations = new List(); foreach (var (path, source) in EnumerateCoreSources()) { foreach (Match m in usingPattern.Matches(source)) violations.Add($"{path}:{LineOf(source, m.Index)} -> {m.Value.Trim()}"); foreach (Match m in typeRefPattern.Matches(source)) violations.Add($"{path}:{LineOf(source, m.Index)} -> {m.Value}"); } violations.Should().BeEmpty( "redb.Identity.Core must not depend on Microsoft.AspNetCore.Http; HTTP-specific " + "wiring belongs to redb.Identity.Http (or another facade)"); } [Fact] public void CoreSource_AuditEventTypeAssignments_UseCatalogConstants() { // H6/H7/H9: every identity-event-type must be sourced from // (or a const ref to it). // String literals are forbidden so the catalog stays the single source of truth and // CategoryOf(...) keeps a closed switch. // Pattern: exchange.Properties["identity-event-type"] = "" var pattern = new Regex( "Properties\\[\"identity-event-type\"\\]\\s*=\\s*\"[^\"]+\"", RegexOptions.Compiled); var violations = new List(); foreach (var (path, source) in EnumerateCoreSources()) { foreach (Match m in pattern.Matches(source)) { var line = LineOf(source, m.Index); violations.Add($"{path}:{line} -> {m.Value}"); } } violations.Should().BeEmpty( "audit event types must reference IdentityAuditEventIds.* constants; literal magic " + "strings break the catalog/category contract and bypass downstream routing."); } private static int LineOf(string source, int index) { var line = 1; for (var i = 0; i < index && i < source.Length; i++) if (source[i] == '\n') line++; return line; } } Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditAmqpIntegrationTests.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/Audit/AuditAmqpIntegrationTests.cs ---- using System.Text; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Amqp; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using Xunit; using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Audit; /// /// Integration tests for AMQP 1.0 audit target (ActiveMQ Artemis). /// Requires Artemis at localhost:5673 (admin/admin). /// public class AuditAmqpIntegrationTests : IAsyncLifetime { private const string PgConnString = "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true"; private const string AmqpHost = "localhost"; private const int AmqpPort = 5673; private const string AmqpUser = "admin"; private const string AmqpPassword = "admin"; private readonly string _amqpQueue = $"identity-audit-{Guid.NewGuid():N}"; private string AmqpUri => "amqp://" + _amqpQueue + "?host=" + AmqpHost + "&port=" + AmqpPort + "&user=" + AmqpUser + "&password=" + AmqpPassword; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? PgConnString; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenThrottleMaxPerPeriod = 1000, Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; services.AddSingleton(Options.Create(identityOptions)); var auditOptions = new IdentityAuditOptions { Enabled = true, Filter = "*", Targets = [ new AuditTarget { Name = "amqp-audit", Enabled = true, Uri = AmqpUri } ] }; services.AddSingleton(Options.Create(auditOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); var redb = _sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back to parameterless overload: {ex.GetType().Name}: {ex.Message}"); await redb.InitializeAsync(); } await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); _ctx = new RouteContext(_sp, "audit-amqp-test"); _ctx.AddComponent(new AmqpComponent()); // The audit targets are sent through the delivery outbox; its table comes from this listener. _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityDeliveryOutboxInitListener(_sp)); _ctx.AddRoutes(new IdentityCoreRouteBuilder( _sp, Options.Create(identityOptions), Options.Create(auditOptions))); await _ctx.Start(); } public async Task DisposeAsync() { if (_ctx != null) await _ctx.Stop(); if (_sp != null) await _sp.DisposeAsync(); } private async Task> ReceiveMessages(int expected, int timeoutMs = 10000) { var uri = EndpointUriParser.Parse(AmqpUri); var component = new AmqpComponent(); var endpoint = (AmqpEndpoint)component.CreateEndpoint(uri); var results = new System.Collections.Concurrent.ConcurrentBag(); var allReceived = new TaskCompletionSource(); var processor = new DelegateProcessor(async (exchange, _) => { var body = exchange.In.Body switch { byte[] bytes => Encoding.UTF8.GetString(bytes), string s => s, _ => exchange.In.Body?.ToString() ?? "" }; results.Add(body); if (results.Count >= expected) allReceived.TrySetResult(); }); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(allReceived.Task, Task.Delay(timeoutMs)); await consumer.Stop(); await endpoint.Stop(); return results.ToList(); } [Fact] public async Task DirectEventSend_PublishesToQueue() { var message = new redb.Route.Core.Message(); message.Headers["client_id"] = "amqp-test-client"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestAmqpDirect"; exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "amqp-test" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull("Events route should not throw: {0}", exchange.Exception?.ToString()); await Task.Delay(500); var messages = await ReceiveMessages(1); messages.Should().HaveCountGreaterThanOrEqualTo(1); var evt = JsonSerializer.Deserialize(messages[0]); evt.GetProperty("eventType").GetString().Should().Be("TestAmqpDirect"); } [Fact] public async Task MultipleEvents_AllPublished() { for (int i = 0; i < 3; i++) { var message = new redb.Route.Core.Message(); message.Headers["client_id"] = $"amqp-multi-{i}"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestAmqpMulti"; exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); } await Task.Delay(500); var messages = await ReceiveMessages(3); messages.Should().HaveCount(3); } [Fact] public async Task EventMessage_ContainsIdentityEventPayload() { var message = new redb.Route.Core.Message(); message.Headers["client_id"] = "amqp-fields-client"; message.Headers["user_id"] = "user-66"; message.Headers["ip_address"] = "10.20.0.1"; message.Headers["user_agent"] = "AmqpTestAgent/1.0"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestAmqpFields"; exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "amqp-check" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); await Task.Delay(500); var messages = await ReceiveMessages(1); messages.Should().HaveCountGreaterThanOrEqualTo(1); var evt = JsonSerializer.Deserialize(messages[0]); evt.GetProperty("eventType").GetString().Should().Be("TestAmqpFields"); evt.GetProperty("clientId").GetString().Should().Be("amqp-fields-client"); evt.GetProperty("userId").GetString().Should().Be("user-66"); evt.GetProperty("ipAddress").GetString().Should().Be("10.20.0.1"); evt.GetProperty("userAgent").GetString().Should().Be("AmqpTestAgent/1.0"); evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty(); } } Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditElasticsearchIntegrationTests.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/Audit/AuditElasticsearchIntegrationTests.cs ---- using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Elasticsearch; using Xunit; using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Audit; /// /// Integration tests for Elasticsearch audit target. /// Requires Elasticsearch at localhost:9200. /// public class AuditElasticsearchIntegrationTests : IAsyncLifetime { private const string PgConnString = "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true"; private const string EsNodes = "http://localhost:9200"; // Per-process index: the three provider suites (PG / MSSQL / SQLite) share one Elasticsearch // container and are routinely run side by side; with a fixed name each process purged and // counted the others' documents (3 expected, 2 or 4 found). The setup still deletes the // index, so nothing accumulates across runs. private static readonly string EsIndex = $"identity-audit-test-{Guid.NewGuid():N}"; private static readonly string EsUri = "es://" + EsIndex + "?nodes=" + EsNodes + "&refresh=wait_for"; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; private readonly HttpClient _http = new(); public async Task InitializeAsync() { // Clean ES index try { // ES returns 404 when the index doesn't exist \u2014 that is the expected first-run state. using var resp = await _http.DeleteAsync($"{EsNodes}/{EsIndex}"); if (!resp.IsSuccessStatusCode && resp.StatusCode != System.Net.HttpStatusCode.NotFound) { Console.Error.WriteLine($"ES index delete returned {(int)resp.StatusCode}: {await resp.Content.ReadAsStringAsync()}"); } } catch (HttpRequestException ex) { Console.Error.WriteLine($"ES index delete failed (server unreachable?): {ex.Message}"); } var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? PgConnString; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenThrottleMaxPerPeriod = 1000, Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; services.AddSingleton(Options.Create(identityOptions)); var auditOptions = new IdentityAuditOptions { Enabled = true, Filter = "*", Targets = [ new AuditTarget { Name = "es-audit", Enabled = true, Uri = EsUri } ] }; services.AddSingleton(Options.Create(auditOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); var redb = _sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back to parameterless overload: {ex.GetType().Name}: {ex.Message}"); await redb.InitializeAsync(); } await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); _ctx = new RouteContext(_sp, "audit-es-test"); _ctx.AddComponent(new ElasticsearchComponent()); // The audit targets are sent through the delivery outbox; its table comes from this listener. _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityDeliveryOutboxInitListener(_sp)); _ctx.AddRoutes(new IdentityCoreRouteBuilder( _sp, Options.Create(identityOptions), Options.Create(auditOptions))); await _ctx.Start(); // Purge TestEs* docs left in the index by a PREVIOUS run. MultipleEvents_AllIndexed asserts // an EXACT hit count (sends 3, expects 3), so without this a second run sees 6, a third 9, // and so on — the same "not isolated from the last run" trap as the SQLite scratch file. // Best-effort: a missing index or an ES hiccup must not fail setup (the tests themselves // skip cleanly when ES is unreachable). refresh=true so the delete is visible immediately. try { await _http.PostAsync( $"{EsNodes}/{EsIndex}/_delete_by_query?refresh=true&conflicts=proceed", new StringContent( "{\"query\":{\"prefix\":{\"eventType.keyword\":\"TestEs\"}}}", System.Text.Encoding.UTF8, "application/json")); } catch { /* ES not reachable / index absent → nothing to purge */ } } public async Task DisposeAsync() { if (_ctx != null) await _ctx.Stop(); if (_sp != null) await _sp.DisposeAsync(); // The index is per process (see EsIndex); drop it so runs do not accumulate indices in // the shared container. Best-effort — an unreachable ES must not fail teardown. try { using var _ = await _http.DeleteAsync($"{EsNodes}/{EsIndex}"); } catch (HttpRequestException) { } _http.Dispose(); } private async Task SearchEsIndex(string? eventType = null) { var query = eventType is not null ? "{\"query\":{\"term\":{\"eventType.keyword\":\"" + eventType + "\"}}}" : "{\"query\":{\"match_all\":{}}}"; var response = await _http.PostAsync( $"{EsNodes}/{EsIndex}/_search", new StringContent(query, System.Text.Encoding.UTF8, "application/json")); if (!response.IsSuccessStatusCode) return null; var json = await response.Content.ReadAsStringAsync(); return JsonDocument.Parse(json).RootElement; } /// Refreshes the index and searches until hits are there or 20 s passed. private async Task WaitForEsHitsAsync(string eventType, int atLeast) { var deadline = DateTime.UtcNow.AddSeconds(20); while (true) { using (await _http.PostAsync($"{EsNodes}/{EsIndex}/_refresh", null)) { } var result = await SearchEsIndex(eventType); var hits = result?.TryGetProperty("hits", out var h) == true ? h.GetProperty("hits").GetArrayLength() : 0; if (hits >= atLeast || DateTime.UtcNow > deadline) return result; await Task.Delay(200); } } [Fact] public async Task DirectEventSend_IndexesDocument() { var message = new Message(); message.Headers["client_id"] = "es-test-client"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestEsDirect"; exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "es-test" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull("Events route should not throw: {0}", exchange.Exception?.ToString()); var result = await WaitForEsHitsAsync("TestEsDirect", 1); // the delivery worker sends the event (it polls every 2 s) result.Should().NotBeNull(); var hits = result!.Value.GetProperty("hits").GetProperty("hits"); hits.GetArrayLength().Should().BeGreaterThanOrEqualTo(1); var source = hits[0].GetProperty("_source"); source.GetProperty("eventType").GetString().Should().Be("TestEsDirect"); } [Fact] public async Task MultipleEvents_AllIndexed() { for (int i = 0; i < 3; i++) { var message = new Message(); message.Headers["client_id"] = $"es-multi-{i}"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestEsMulti"; exchange.Properties["identity-event-data"] = new Dictionary { ["index"] = i }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); } var result = await WaitForEsHitsAsync("TestEsMulti", 3); result.Should().NotBeNull(); var hits = result!.Value.GetProperty("hits").GetProperty("hits"); hits.GetArrayLength().Should().Be(3); } [Fact] public async Task EventDocument_ContainsAllFields() { var message = new Message(); message.Headers["client_id"] = "es-fields-client"; message.Headers["user_id"] = "user-42"; message.Headers["ip_address"] = "10.0.0.5"; message.Headers["user_agent"] = "TestAgent/1.0"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestEsFields"; exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "verify" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); var result = await WaitForEsHitsAsync("TestEsFields", 1); result.Should().NotBeNull(); var hits = result!.Value.GetProperty("hits").GetProperty("hits"); hits.GetArrayLength().Should().BeGreaterThanOrEqualTo(1); var source = hits[0].GetProperty("_source"); source.GetProperty("eventType").GetString().Should().Be("TestEsFields"); source.GetProperty("clientId").GetString().Should().Be("es-fields-client"); source.GetProperty("userId").GetString().Should().Be("user-42"); source.GetProperty("ipAddress").GetString().Should().Be("10.0.0.5"); source.GetProperty("userAgent").GetString().Should().Be("TestAgent/1.0"); source.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty(); } } Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditIbmMqIntegrationTests.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/Audit/AuditIbmMqIntegrationTests.cs ---- using System.Text; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.IbmMq; using redb.Route.Processors; using Xunit; using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Audit; /// /// Integration tests for IBM MQ (WMQ) audit target. /// Requires IBM MQ at localhost:1414 (channel=DEV.APP.SVRCONN, QM=QM1, user=app, password=admin). /// public class AuditIbmMqIntegrationTests : IAsyncLifetime { private const string PgConnString = "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true"; private const string WmqHost = "localhost"; private const int WmqPort = 1414; private const string WmqChannel = "DEV.APP.SVRCONN"; private const string WmqQueueManager = "QM1"; private const string WmqUser = "app"; private const string WmqPassword = "admin"; /// /// A queue of this run's own, picked by the provider under test. /// /// /// The provider matrix runs sqlite / postgres / mssql as three separate processes against one /// broker, started with only a small stagger, so their MQ suites overlap. On a single shared /// queue a sibling process either consumes this run's audit message (this run then waits out its /// 15-second timeout) or hands this run the sibling's message (wrong eventType) - both shapes /// appear in the full-run logs. eventType cannot separate the processes, because all three /// publish the same types; a queue per provider can. DEV.QUEUE.1-5 are pre-created by the IBM MQ /// developer image. /// private static string WmqQueue => TestRedbSetup.SelectedProvider switch { TestRedbSetup.Provider.Postgres => "DEV.QUEUE.2", TestRedbSetup.Provider.MsSql => "DEV.QUEUE.3", _ => "DEV.QUEUE.1" }; private string WmqUri => "wmq:" + WmqQueue + "?host=" + WmqHost + "&port=" + WmqPort + "&channel=" + WmqChannel + "&queueManager=" + WmqQueueManager + "&user=" + WmqUser + "&password=" + WmqPassword; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; public async Task InitializeAsync() { // Drain any leftover messages from previous test runs await DrainQueue(); var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? PgConnString; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenThrottleMaxPerPeriod = 1000, Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; services.AddSingleton(Options.Create(identityOptions)); var auditOptions = new IdentityAuditOptions { Enabled = true, Filter = "*", Targets = [ new AuditTarget { Name = "wmq-audit", Enabled = true, Uri = WmqUri } ] }; services.AddSingleton(Options.Create(auditOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); var redb = _sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back to parameterless overload: {ex.GetType().Name}: {ex.Message}"); await redb.InitializeAsync(); } await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); _ctx = new RouteContext(_sp, "audit-wmq-test"); _ctx.AddComponent(new IbmMqComponent()); // The audit targets are sent through the delivery outbox; its table comes from this listener. _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityDeliveryOutboxInitListener(_sp)); _ctx.AddRoutes(new IdentityCoreRouteBuilder( _sp, Options.Create(identityOptions), Options.Create(auditOptions))); await _ctx.Start(); } public async Task DisposeAsync() { if (_ctx != null) await _ctx.Stop(); if (_sp != null) await _sp.DisposeAsync(); } private async Task DrainQueue() { try { var uri = EndpointUriParser.Parse(WmqUri + "&waitInterval=1000"); var component = new IbmMqComponent(); var endpoint = (IbmMqEndpoint)component.CreateEndpoint(uri); var processor = new DelegateProcessor((_, _) => Task.CompletedTask); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); await Task.Delay(2000); await consumer.Stop(); await endpoint.Stop(); } catch (Exception ex) { // Best-effort drain: queue may be empty / missing on first run, or MQ may be unreachable. // Surface the failure rather than silently swallow so a misconfigured broker is visible. Console.Error.WriteLine($"DrainQueue best-effort failed: {ex.GetType().Name}: {ex.Message}"); } } /// /// Collects audit messages whose eventType is . /// /// /// Every test in this class publishes to the same queue (), and the /// per-test drain is best-effort, so a sibling test's leftover can still be sitting there. /// Taking "the first message that arrives" therefore proves nothing about the event this test /// published: messages carrying a foreign eventType are consumed and skipped, and the wait ends /// only when this test's own events have arrived (or the timeout expires and the caller fails). /// private async Task> ReceiveMessages(string eventType, int expected, int timeoutMs = 15000) { var uri = EndpointUriParser.Parse(WmqUri + "&waitInterval=5000"); var component = new IbmMqComponent(); var endpoint = (IbmMqEndpoint)component.CreateEndpoint(uri); var results = new System.Collections.Concurrent.ConcurrentBag(); var allReceived = new TaskCompletionSource(); var processor = new DelegateProcessor((exchange, _) => { var body = exchange.In.Body switch { byte[] bytes => Encoding.UTF8.GetString(bytes), string s => s, _ => exchange.In.Body?.ToString() ?? "" }; var received = EventTypeOf(body); if (received == eventType) { results.Add(body); if (results.Count >= expected) allReceived.TrySetResult(); } else { Console.Error.WriteLine( $"ReceiveMessages({eventType}): skipped a foreign message from the shared queue, eventType={received ?? ""}"); } return Task.CompletedTask; }); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(allReceived.Task, Task.Delay(timeoutMs)); await consumer.Stop(); await endpoint.Stop(); return results.ToList(); } /// /// eventType of an audit message, or null when the payload is not the expected JSON envelope. /// private static string? EventTypeOf(string body) { try { var doc = JsonSerializer.Deserialize(body); return doc.TryGetProperty("eventType", out var et) ? et.GetString() : null; } catch (JsonException ex) { // Not silently ignored: an unparsable payload on the audit queue is reported and then // treated as foreign, so it cannot be mistaken for this test's event. Console.Error.WriteLine($"EventTypeOf: audit payload is not JSON: {ex.Message}"); return null; } } [Fact] public async Task DirectEventSend_PublishesToQueue() { var message = new Message(); message.Headers["client_id"] = "wmq-test-client"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestWmqDirect"; exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "wmq-test" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull("Events route should not throw: {0}", exchange.Exception?.ToString()); await Task.Delay(500); var messages = await ReceiveMessages("TestWmqDirect", 1); messages.Should().HaveCountGreaterThanOrEqualTo(1, "the Events route must publish TestWmqDirect to the audit queue"); var evt = JsonSerializer.Deserialize(messages[0]); evt.GetProperty("eventType").GetString().Should().Be("TestWmqDirect"); } [Fact] public async Task MultipleEvents_AllPublished() { for (int i = 0; i < 3; i++) { var message = new Message(); message.Headers["client_id"] = $"wmq-multi-{i}"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestWmqMulti"; exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i }; var ep = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = ep.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); } await Task.Delay(500); var messages = await ReceiveMessages("TestWmqMulti", 3); messages.Should().HaveCount(3, "all three TestWmqMulti events must reach the audit queue"); } [Fact] public async Task EventMessage_ContainsIdentityEventPayload() { var message = new Message(); message.Headers["client_id"] = "wmq-fields-client"; message.Headers["user_id"] = "user-99"; message.Headers["ip_address"] = "172.16.0.1"; message.Headers["user_agent"] = "WmqTestAgent/1.0"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestWmqFields"; exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "wmq-check" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); await Task.Delay(500); var messages = await ReceiveMessages("TestWmqFields", 1); messages.Should().HaveCountGreaterThanOrEqualTo(1, "the Events route must publish TestWmqFields to the audit queue"); var evt = JsonSerializer.Deserialize(messages[0]); evt.GetProperty("eventType").GetString().Should().Be("TestWmqFields"); evt.GetProperty("clientId").GetString().Should().Be("wmq-fields-client"); evt.GetProperty("userId").GetString().Should().Be("user-99"); evt.GetProperty("ipAddress").GetString().Should().Be("172.16.0.1"); evt.GetProperty("userAgent").GetString().Should().Be("WmqTestAgent/1.0"); evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty(); } } Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditKafkaIntegrationTests.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/Audit/AuditKafkaIntegrationTests.cs ---- using System.Collections.Concurrent; using System.Text; using System.Text.Json; using Confluent.Kafka; using Confluent.Kafka.Admin; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Kafka; using redb.Route.Processors; using Xunit; using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Audit; /// /// Integration tests for Kafka audit target. /// Requires Kafka at localhost:29092. /// public class AuditKafkaIntegrationTests : IAsyncLifetime { private const string PgConnString = "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true"; private const string KafkaBrokers = "localhost:29092"; private const string KafkaTopic = "identity-audit-test"; private const string KafkaUri = "kafka://" + KafkaTopic + "?brokers=" + KafkaBrokers; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; public async Task InitializeAsync() { // Delete topic if exists (best-effort cleanup via Kafka AdminClient) try { using var adminClient = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = KafkaBrokers }).Build(); await adminClient.DeleteTopicsAsync([KafkaTopic]); await Task.Delay(1000); } catch (DeleteTopicsException ex) when (ex.Results.All(r => r.Error.Code == ErrorCode.UnknownTopicOrPart)) { // Expected on first run when the topic hasn't been created yet. Console.Error.WriteLine($"Kafka DeleteTopics skipped (topic not yet created): {ex.Message}"); } catch (Exception ex) { // Unexpected admin failures must remain visible \u2014 don't silently swallow. Console.Error.WriteLine($"Kafka DeleteTopics failed: {ex.GetType().Name}: {ex.Message}"); } var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? PgConnString; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenThrottleMaxPerPeriod = 1000, Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; services.AddSingleton(Options.Create(identityOptions)); var auditOptions = new IdentityAuditOptions { Enabled = true, Filter = "*", Targets = [ new AuditTarget { Name = "kafka-audit", Enabled = true, Uri = KafkaUri } ] }; services.AddSingleton(Options.Create(auditOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); var redb = _sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back to parameterless overload: {ex.GetType().Name}: {ex.Message}"); await redb.InitializeAsync(); } await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); _ctx = new RouteContext(_sp, "audit-kafka-test"); _ctx.AddComponent(new KafkaComponent()); // The audit targets are sent through the delivery outbox; its table comes from this listener. _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityDeliveryOutboxInitListener(_sp)); _ctx.AddRoutes(new IdentityCoreRouteBuilder( _sp, Options.Create(identityOptions), Options.Create(auditOptions))); await _ctx.Start(); } public async Task DisposeAsync() { if (_ctx != null) await _ctx.Stop(); if (_sp != null) await _sp.DisposeAsync(); } private async Task> ConsumeMessages(int expected, int timeoutMs = 15000) { var groupId = $"audit-verify-{Guid.NewGuid():N}"; var uri = EndpointUriParser.Parse( $"kafka://{KafkaTopic}?brokers={KafkaBrokers}&groupId={groupId}&autoOffsetReset=Earliest"); var component = new KafkaComponent(); var endpoint = (KafkaEndpoint)component.CreateEndpoint(uri); var results = new ConcurrentBag(); var allReceived = new TaskCompletionSource(); var processor = new DelegateProcessor((exchange, _) => { var body = exchange.In.Body switch { byte[] bytes => Encoding.UTF8.GetString(bytes), string s => s, _ => exchange.In.Body?.ToString() ?? "" }; results.Add(body); if (results.Count >= expected) allReceived.TrySetResult(); return Task.CompletedTask; }); var consumer = endpoint.CreateConsumer(processor); await consumer.Start(); await Task.WhenAny(allReceived.Task, Task.Delay(timeoutMs)); await consumer.Stop(); await endpoint.Stop(); return results.ToList(); } [Fact] public async Task DirectEventSend_PublishesToTopic() { var message = new Message(); message.Headers["client_id"] = "kafka-test-client"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestKafkaDirect"; exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "kafka-test" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull("Events route should not throw: {0}", exchange.Exception?.ToString()); var messages = await ConsumeMessages(1); messages.Should().HaveCountGreaterThanOrEqualTo(1); var evt = JsonSerializer.Deserialize(messages[0]); evt.GetProperty("eventType").GetString().Should().Be("TestKafkaDirect"); } [Fact] public async Task MultipleEvents_AllPublished() { for (int i = 0; i < 3; i++) { var message = new Message(); message.Headers["client_id"] = $"kafka-multi-{i}"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestKafkaMulti"; exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); } var messages = await ConsumeMessages(3); messages.Should().HaveCount(3); } [Fact] public async Task EventMessage_ContainsIdentityEventPayload() { var message = new Message(); message.Headers["client_id"] = "kafka-fields-client"; message.Headers["user_id"] = "user-88"; message.Headers["ip_address"] = "172.16.0.10"; message.Headers["user_agent"] = "KafkaTestAgent/1.0"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestKafkaFields"; exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "kafka-check" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); var messages = await ConsumeMessages(1); messages.Should().HaveCountGreaterThanOrEqualTo(1); var evt = JsonSerializer.Deserialize(messages[0]); evt.GetProperty("eventType").GetString().Should().Be("TestKafkaFields"); evt.GetProperty("clientId").GetString().Should().Be("kafka-fields-client"); evt.GetProperty("userId").GetString().Should().Be("user-88"); evt.GetProperty("ipAddress").GetString().Should().Be("172.16.0.10"); evt.GetProperty("userAgent").GetString().Should().Be("KafkaTestAgent/1.0"); evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty(); } } Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditMqttIntegrationTests.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/Audit/AuditMqttIntegrationTests.cs ---- using System.Collections.Concurrent; using System.Text; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MQTTnet; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.MqttNet; using Xunit; using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Audit; /// /// Integration tests for MQTT audit target. /// Requires Mosquitto at localhost:11883. /// public class AuditMqttIntegrationTests : IAsyncLifetime { private const string PgConnString = "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true"; private const string MqttServer = "localhost"; private const int MqttPort = 11883; private const string MqttTopic = "identity/audit/test"; private static readonly string MqttUri = "mqtt://" + MqttTopic + "?mode=Publish&server=" + MqttServer + "&port=" + MqttPort + "&qos=1"; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; private IMqttClient _subscriber = null!; private readonly ConcurrentBag _received = new(); private readonly SemaphoreSlim _signal = new(0); public async Task InitializeAsync() { // Set up MQTT subscriber BEFORE sending events var factory = new MqttClientFactory(); _subscriber = factory.CreateMqttClient(); var opts = new MqttClientOptionsBuilder() .WithTcpServer(MqttServer, MqttPort) .WithClientId($"audit-verify-{Guid.NewGuid():N}") .Build(); _subscriber.ApplicationMessageReceivedAsync += args => { var payload = args.ApplicationMessage.ConvertPayloadToString(); _received.Add(payload); _signal.Release(); return Task.CompletedTask; }; await _subscriber.ConnectAsync(opts); await _subscriber.SubscribeAsync(MqttTopic); var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? PgConnString; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenThrottleMaxPerPeriod = 1000, Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; services.AddSingleton(Options.Create(identityOptions)); var auditOptions = new IdentityAuditOptions { Enabled = true, Filter = "*", Targets = [ new AuditTarget { Name = "mqtt-audit", Enabled = true, Uri = MqttUri } ] }; services.AddSingleton(Options.Create(auditOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); var redb = _sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back to parameterless overload: {ex.GetType().Name}: {ex.Message}"); await redb.InitializeAsync(); } await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); _ctx = new RouteContext(_sp, "audit-mqtt-test"); _ctx.AddComponent(new MqttComponent()); // The audit targets are sent through the delivery outbox; its table comes from this listener. _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityDeliveryOutboxInitListener(_sp)); _ctx.AddRoutes(new IdentityCoreRouteBuilder( _sp, Options.Create(identityOptions), Options.Create(auditOptions))); await _ctx.Start(); } public async Task DisposeAsync() { if (_ctx != null) await _ctx.Stop(); if (_subscriber is { IsConnected: true }) { await _subscriber.UnsubscribeAsync(MqttTopic); await _subscriber.DisconnectAsync(); } _subscriber?.Dispose(); if (_sp != null) await _sp.DisposeAsync(); _signal.Dispose(); } private async Task WaitForMessages(int count, int timeoutMs = 5000) { for (int i = 0; i < count; i++) await _signal.WaitAsync(TimeSpan.FromMilliseconds(timeoutMs)); } [Fact] public async Task DirectEventSend_PublishesToTopic() { var message = new Message(); message.Headers["client_id"] = "mqtt-test-client"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestMqttDirect"; exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "mqtt-test" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull("Events route should not throw: {0}", exchange.Exception?.ToString()); await WaitForMessages(1); _received.Should().HaveCountGreaterThanOrEqualTo(1); var evt = JsonSerializer.Deserialize(_received.First()); evt.GetProperty("eventType").GetString().Should().Be("TestMqttDirect"); } [Fact] public async Task MultipleEvents_AllPublished() { for (int i = 0; i < 3; i++) { var message = new Message(); message.Headers["client_id"] = $"mqtt-multi-{i}"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestMqttMulti"; exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); } await WaitForMessages(3); _received.Should().HaveCount(3); } [Fact] public async Task EventMessage_ContainsIdentityEventPayload() { var message = new Message(); message.Headers["client_id"] = "mqtt-fields-client"; message.Headers["user_id"] = "user-55"; message.Headers["ip_address"] = "192.168.10.5"; message.Headers["user_agent"] = "MqttTestAgent/1.0"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestMqttFields"; exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "mqtt-check" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); await WaitForMessages(1); _received.Should().HaveCountGreaterThanOrEqualTo(1); var evt = JsonSerializer.Deserialize(_received.First()); evt.GetProperty("eventType").GetString().Should().Be("TestMqttFields"); evt.GetProperty("clientId").GetString().Should().Be("mqtt-fields-client"); evt.GetProperty("userId").GetString().Should().Be("user-55"); evt.GetProperty("ipAddress").GetString().Should().Be("192.168.10.5"); evt.GetProperty("userAgent").GetString().Should().Be("MqttTestAgent/1.0"); evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty(); } } Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditRabbitMqIntegrationTests.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/Audit/AuditRabbitMqIntegrationTests.cs ---- using System.Net.Http.Headers; using System.Text; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.RabbitMQ; using Xunit; using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Audit; /// /// Integration tests for RabbitMQ audit target. /// Requires RabbitMQ at localhost:5672 (management at 15672, admin/admin). /// public class AuditRabbitMqIntegrationTests : IAsyncLifetime { private const string PgConnString = "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true"; private const string RabbitQueue = "identity-audit-test"; private const string RabbitUri = "rabbitmq://" + RabbitQueue + "?host=localhost&port=5672&username=admin&password=admin&declare=true"; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; private readonly HttpClient _http = new(); public async Task InitializeAsync() { // Purge queue via management API (if exists) _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:admin"))); try { using var resp = await _http.DeleteAsync($"http://localhost:15672/api/queues/%2f/{RabbitQueue}/contents"); if (!resp.IsSuccessStatusCode && resp.StatusCode != System.Net.HttpStatusCode.NotFound) { Console.Error.WriteLine($"RabbitMQ queue purge returned {(int)resp.StatusCode}: {await resp.Content.ReadAsStringAsync()}"); } } catch (HttpRequestException ex) { Console.Error.WriteLine($"RabbitMQ queue purge failed (mgmt API unreachable?): {ex.Message}"); } var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? PgConnString; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenThrottleMaxPerPeriod = 1000, Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; services.AddSingleton(Options.Create(identityOptions)); var auditOptions = new IdentityAuditOptions { Enabled = true, Filter = "*", Targets = [ new AuditTarget { Name = "rabbitmq-audit", Enabled = true, Uri = RabbitUri } ] }; services.AddSingleton(Options.Create(auditOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); var redb = _sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back to parameterless overload: {ex.GetType().Name}: {ex.Message}"); await redb.InitializeAsync(); } await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); _ctx = new RouteContext(_sp, "audit-rabbitmq-test"); _ctx.AddComponent(new RabbitMQComponent()); // The audit targets are sent through the delivery outbox; its table comes from this listener. _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityDeliveryOutboxInitListener(_sp)); _ctx.AddRoutes(new IdentityCoreRouteBuilder( _sp, Options.Create(identityOptions), Options.Create(auditOptions))); await _ctx.Start(); } public async Task DisposeAsync() { if (_ctx != null) await _ctx.Stop(); if (_sp != null) await _sp.DisposeAsync(); _http.Dispose(); } /// /// Get messages from queue via RabbitMQ Management API (non-destructive peek). /// private async Task> GetQueueMessages(int count = 10) { var body = JsonSerializer.Serialize(new { count, ackmode = "ack_requeue_false", encoding = "auto" }); var response = await _http.PostAsync( $"http://localhost:15672/api/queues/%2f/{RabbitQueue}/get", new StringContent(body, Encoding.UTF8, "application/json")); if (!response.IsSuccessStatusCode) return []; var json = await response.Content.ReadAsStringAsync(); var messages = JsonDocument.Parse(json).RootElement; if (messages.ValueKind != JsonValueKind.Array) return []; return messages.EnumerateArray().ToList(); } /// Reads (and takes) the queue until it gave at least messages or 20 s passed. private async Task> CollectQueueMessagesAsync(int atLeast) { var collected = new List(); var deadline = DateTime.UtcNow.AddSeconds(20); while (collected.Count < atLeast && DateTime.UtcNow < deadline) { collected.AddRange(await GetQueueMessages()); if (collected.Count < atLeast) await Task.Delay(200); } return collected; } [Fact] public async Task DirectEventSend_PublishesToQueue() { var message = new Message(); message.Headers["client_id"] = "rmq-test-client"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestRmqDirect"; exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "rmq-test" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull("Events route should not throw: {0}", exchange.Exception?.ToString()); var messages = await CollectQueueMessagesAsync(1); // the delivery worker sends the event (it polls every 2 s) messages.Should().HaveCountGreaterThanOrEqualTo(1); // Decode payload — it's base64 or raw string var payload = messages[0].GetProperty("payload").GetString(); payload.Should().NotBeNullOrEmpty(); var evt = JsonSerializer.Deserialize(payload!); evt.GetProperty("eventType").GetString().Should().Be("TestRmqDirect"); } [Fact] public async Task MultipleEvents_AllPublished() { for (int i = 0; i < 3; i++) { var message = new Message(); message.Headers["client_id"] = $"rmq-multi-{i}"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestRmqMulti"; exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); } var messages = await CollectQueueMessagesAsync(3); messages.Should().HaveCount(3); } [Fact] public async Task EventMessage_ContainsIdentityEventPayload() { var message = new Message(); message.Headers["client_id"] = "rmq-fields-client"; message.Headers["user_id"] = "user-77"; message.Headers["ip_address"] = "192.168.1.50"; message.Headers["user_agent"] = "RmqTestAgent/2.0"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestRmqFields"; exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "rmq-check" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); var messages = await CollectQueueMessagesAsync(1); messages.Should().HaveCountGreaterThanOrEqualTo(1); var payload = messages[0].GetProperty("payload").GetString()!; var evt = JsonSerializer.Deserialize(payload); evt.GetProperty("eventType").GetString().Should().Be("TestRmqFields"); evt.GetProperty("clientId").GetString().Should().Be("rmq-fields-client"); evt.GetProperty("userId").GetString().Should().Be("user-77"); evt.GetProperty("ipAddress").GetString().Should().Be("192.168.1.50"); evt.GetProperty("userAgent").GetString().Should().Be("RmqTestAgent/2.0"); evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty(); } } Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditRedisIntegrationTests.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/Audit/AuditRedisIntegrationTests.cs ---- using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Redis; using StackExchange.Redis; using Xunit; using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Audit; /// /// Integration tests for Redis audit target (LPUSH to a list). /// Requires Redis at localhost:6379. /// public class AuditRedisIntegrationTests : IAsyncLifetime { private const string PgConnString = "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true"; private const string RedisConnString = "localhost:6379"; private const string RedisKey = "identity-audit-test"; private const string RedisUri = "redis:LPUSH:" + RedisKey + "?connectionString=" + RedisConnString; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; private ConnectionMultiplexer _redis = null!; public async Task InitializeAsync() { _redis = await ConnectionMultiplexer.ConnectAsync(RedisConnString); await _redis.GetDatabase().KeyDeleteAsync(RedisKey); var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? PgConnString; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenThrottleMaxPerPeriod = 1000, Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; services.AddSingleton(Options.Create(identityOptions)); var auditOptions = new IdentityAuditOptions { Enabled = true, Filter = "*", Targets = [ new AuditTarget { Name = "redis-audit", Enabled = true, Uri = RedisUri } ] }; services.AddSingleton(Options.Create(auditOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); var redb = _sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back to parameterless overload: {ex.GetType().Name}: {ex.Message}"); await redb.InitializeAsync(); } await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); _ctx = new RouteContext(_sp, "audit-redis-test"); _ctx.AddComponent(new RedisComponent()); // The audit targets are sent through the delivery outbox; its table comes from this listener. _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityDeliveryOutboxInitListener(_sp)); _ctx.AddRoutes(new IdentityCoreRouteBuilder( _sp, Options.Create(identityOptions), Options.Create(auditOptions))); await _ctx.Start(); } public async Task DisposeAsync() { if (_ctx != null) await _ctx.Stop(); if (_sp != null) await _sp.DisposeAsync(); if (_redis != null) await _redis.DisposeAsync(); } [Fact] public async Task DirectEventSend_PushesToList() { var message = new Message(); message.Headers["client_id"] = "redis-test-client"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestRedisDirect"; exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "redis-test" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull("Events route should not throw: {0}", exchange.Exception?.ToString()); await WaitForListAsync(1); // the delivery worker sends the event (it polls every 2 s) var db = _redis.GetDatabase(); var length = await db.ListLengthAsync(RedisKey); length.Should().BeGreaterThanOrEqualTo(1); var value = await db.ListGetByIndexAsync(RedisKey, 0); value.HasValue.Should().BeTrue(); var evt = JsonSerializer.Deserialize(value.ToString()); evt.GetProperty("eventType").GetString().Should().Be("TestRedisDirect"); } private async Task WaitForListAsync(long atLeast) { var db = _redis.GetDatabase(); var deadline = DateTime.UtcNow.AddSeconds(15); while (await db.ListLengthAsync(RedisKey) < atLeast && DateTime.UtcNow < deadline) await Task.Delay(100); } [Fact] public async Task MultipleEvents_AllPushed() { for (int i = 0; i < 3; i++) { var message = new Message(); message.Headers["client_id"] = $"redis-multi-{i}"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestRedisMulti"; exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); } await WaitForListAsync(3); // the delivery worker sends the event (it polls every 2 s) var db = _redis.GetDatabase(); var length = await db.ListLengthAsync(RedisKey); length.Should().Be(3); } [Fact] public async Task EventMessage_ContainsIdentityEventPayload() { var message = new Message(); message.Headers["client_id"] = "redis-fields-client"; message.Headers["user_id"] = "user-99"; message.Headers["ip_address"] = "10.10.0.1"; message.Headers["user_agent"] = "RedisTestAgent/1.0"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestRedisFields"; exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "redis-check" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); await WaitForListAsync(1); // the delivery worker sends the event (it polls every 2 s) var db = _redis.GetDatabase(); var value = await db.ListGetByIndexAsync(RedisKey, 0); value.HasValue.Should().BeTrue(); var evt = JsonSerializer.Deserialize(value.ToString()); evt.GetProperty("eventType").GetString().Should().Be("TestRedisFields"); evt.GetProperty("clientId").GetString().Should().Be("redis-fields-client"); evt.GetProperty("userId").GetString().Should().Be("user-99"); evt.GetProperty("ipAddress").GetString().Should().Be("10.10.0.1"); evt.GetProperty("userAgent").GetString().Should().Be("RedisTestAgent/1.0"); evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty(); } } Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditSqlIntegrationTests.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/Audit/AuditSqlIntegrationTests.cs ---- using System.Data.Common; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Npgsql; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Identity.Contracts.Scopes; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Sql; using redb.Route.Sql.Connection; using Xunit; using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Audit; /// /// Integration tests for the audit multicast subsystem. /// Uses real PostgreSQL with the identity_audit_log table. /// public class AuditSqlIntegrationTests : IAsyncLifetime { private const string PgConnString = "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true"; private const string SqlInsertUri = "sql:INSERT INTO identity_audit_log(event_id, event_type, \"timestamp\", user_id, client_id, ip_address, user_agent, details) " + "VALUES(:#event_id, :#event_type, :#timestamp, :#user_id, :#client_id, :#ip_address, :#user_agent, :#details::jsonb)" + "?dataSource=identity-audit-pg&outputType=None" + "¶m.event_id=${header.event_id}" + "¶m.event_type=${header.event_type}" + "¶m.timestamp=${header.timestamp}" + "¶m.user_id=${header.user_id}" + "¶m.client_id=${header.client_id}" + "¶m.ip_address=${header.ip_address}" + "¶m.user_agent=${header.user_agent}" + "¶m.details=${header.details}"; // The database the audit table is created in, written to and read back from: the configured one. private string _cs = PgConnString; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; private ProducerTemplate _producer = null!; public async Task InitializeAsync() { DbProviderFactories.RegisterFactory("Npgsql", NpgsqlFactory.Instance); var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = _cs = config.GetPostgresConnectionString() ?? PgConnString; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenThrottleMaxPerPeriod = 1000, Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; services.AddSingleton(Options.Create(identityOptions)); var auditOptions = new IdentityAuditOptions { Enabled = true, Filter = "*", Targets = [ new AuditTarget { Name = "pg-audit", Enabled = true, Uri = SqlInsertUri } ] }; services.AddSingleton(Options.Create(auditOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); var redb = _sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back to parameterless overload: {ex.GetType().Name}: {ex.Message}"); await redb.InitializeAsync(); } await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); // Clean audit table before tests (create if missing — keeps tests // self-contained on a freshly seeded dev DB). await using (var conn = new NpgsqlConnection(cs)) { await conn.OpenAsync(); await using var cmd = conn.CreateCommand(); cmd.CommandText = @" CREATE TABLE IF NOT EXISTS identity_audit_log ( id BIGSERIAL PRIMARY KEY, event_id UUID NOT NULL, event_type VARCHAR(100) NOT NULL, ""timestamp"" TIMESTAMPTZ NOT NULL DEFAULT NOW(), user_id VARCHAR(50), client_id VARCHAR(200), ip_address VARCHAR(50), user_agent VARCHAR(500), details JSONB, CONSTRAINT uq_audit_event_id UNIQUE (event_id) ); DELETE FROM identity_audit_log;"; await cmd.ExecuteNonQueryAsync(); } _ctx = new RouteContext(_sp, "audit-integration-test"); _ctx.AddComponent(new SqlComponent()); _ctx.AddToRegistry("identity-audit-pg", (ISqlConnectionFactory)new SqlConnectionFactory( new SqlConnectionOptions { ConnectionString = cs, ProviderName = "Npgsql" })); // The audit targets are sent through the delivery outbox; its table comes from this listener. _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityDeliveryOutboxInitListener(_sp)); _ctx.AddRoutes(new IdentityCoreRouteBuilder( _sp, Options.Create(identityOptions), Options.Create(auditOptions))); await _ctx.Start(); _producer = new ProducerTemplate(_ctx); _producer.Start(); } public async Task DisposeAsync() { _producer?.Stop(); if (_ctx != null) await _ctx.Stop(); if (_sp != null) await _sp.DisposeAsync(); } private async Task SendScope(string operation, object body) { var message = new Message { Body = body }; message.Headers["operation"] = operation; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOut }; ManagementCallerContext.Apply(exchange, ManagementCaller.Admin); // playing the facade, see ManagementCaller var endpoint = _ctx.GetEndpoint(IdentityEndpoints.ManageScopes); var producer = endpoint.CreateProducer(); await producer.Process(exchange); return exchange; } private async Task>> WaitForAuditRows(string eventType, int atLeast) { var deadline = DateTime.UtcNow.AddSeconds(15); while (true) { var rows = await QueryAuditRows(eventType); if (rows.Count >= atLeast || DateTime.UtcNow > deadline) return rows; await Task.Delay(200); } } private async Task>> QueryAuditRows(string? eventType = null) { await using var conn = new NpgsqlConnection(_cs); await conn.OpenAsync(); var sql = "SELECT event_id, event_type, \"timestamp\", user_id, client_id, ip_address, user_agent, details::text FROM identity_audit_log"; if (eventType is not null) { sql += " WHERE event_type = @et"; } sql += " ORDER BY id"; await using var cmd = new NpgsqlCommand(sql, conn); if (eventType is not null) cmd.Parameters.AddWithValue("et", eventType); await using var reader = await cmd.ExecuteReaderAsync(); var rows = new List>(); while (await reader.ReadAsync()) { var row = new Dictionary(); for (int i = 0; i < reader.FieldCount; i++) row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i); rows.Add(row); } return rows; } [Fact] public async Task BareSql_InsertAuditRow() { // Bypass Events route entirely — send directly to the SQL endpoint var sqlEndpoint = _ctx.GetEndpoint(SqlInsertUri); var sqlProducer = sqlEndpoint.CreateProducer(); await sqlProducer.Start(); var msg = new Message(); msg.Body = "{}"; // JSON body msg.Headers["event_id"] = Guid.NewGuid(); msg.Headers["event_type"] = "BareSqlTest"; msg.Headers["timestamp"] = DateTimeOffset.UtcNow; msg.Headers["user_id"] = DBNull.Value; msg.Headers["client_id"] = "bare-client"; msg.Headers["ip_address"] = DBNull.Value; msg.Headers["user_agent"] = DBNull.Value; msg.Headers["details"] = "{}"; var exchange = new Exchange(msg) { Pattern = ExchangePattern.InOnly }; await sqlProducer.Process(exchange); exchange.Exception.Should().BeNull("SQL INSERT should succeed: {0}", exchange.Exception?.Message); var rows = await QueryAuditRows("BareSqlTest"); rows.Should().ContainSingle(); } [Fact] public async Task DirectEventSend_WritesAuditRow() { // Send directly to the Events endpoint, bypassing WireTap var message = new Message(); message.Headers["client_id"] = "direct-test-client"; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestDirect"; exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "direct" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); // Check that the processor ran: In should have the headers after Out→In merge exchange.In.Headers.Should().ContainKey("event_type", "EventDispatchProcessor should set Out headers which get merged to In"); exchange.Exception.Should().BeNull("Events route should not throw: {0}", exchange.Exception?.ToString()); // The target is sent by the delivery worker (it polls every 2 s), not by the events route. var rows = await WaitForAuditRows("TestDirect", 1); rows.Should().ContainSingle(); rows[0]["event_type"].Should().Be("TestDirect"); rows[0]["client_id"].Should().Be("direct-test-client"); } [Fact] public async Task ScopeCreated_WritesAuditRow() { var scopeName = "audit-create-" + Guid.NewGuid().ToString("N")[..8]; var exchange = await SendScope("create", new CreateScopeRequest { Name = scopeName, DisplayName = "Audit Test" }); exchange.Exception.Should().BeNull(); // WireTap, then the delivery worker: wait for the row. var rows = await WaitForAuditRows("ScopeCreated", 1); rows.Should().HaveCountGreaterThanOrEqualTo(1); rows.Last()["event_type"].Should().Be("ScopeCreated"); rows.Last()["event_id"].Should().NotBeNull(); } [Fact] public async Task Event_NullFields_WrittenAsDbNull() { // Send event without user_id or client_id — verify nulls in DB var message = new Message(); // No user_id or client_id headers var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly }; exchange.Properties["identity-event-type"] = "TestNullFields"; exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "nulls" }; var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events); var producer = endpoint.CreateProducer(); await producer.Start(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); var rows = await WaitForAuditRows("TestNullFields", 1); rows.Should().ContainSingle(); rows[0]["user_id"].Should().BeNull(); rows[0]["client_id"].Should().BeNull(); rows[0]["ip_address"].Should().BeNull(); rows[0]["user_agent"].Should().BeNull(); } [Fact] public async Task AuditRow_ContainsEventIdAndTimestamp() { var scopeName = "audit-ts-" + Guid.NewGuid().ToString("N")[..8]; var before = DateTimeOffset.UtcNow.AddSeconds(-1); var exchange = await SendScope("create", new CreateScopeRequest { Name = scopeName, DisplayName = "TS Test" }); exchange.Exception.Should().BeNull(); var rows = await WaitForAuditRows("ScopeCreated", 1); rows.Should().HaveCountGreaterThanOrEqualTo(1); var row = rows.Last(); row["event_id"].Should().NotBeNull(); var rawTs = row["timestamp"]; var ts = rawTs is DateTimeOffset dto ? dto : new DateTimeOffset((DateTime)rawTs!); ts.Should().BeAfter(before); } [Fact] public async Task MultipleEvents_AllWritten() { // Clean slate for this test await using (var conn = new NpgsqlConnection(_cs)) { await conn.OpenAsync(); await using var cmd = conn.CreateCommand(); cmd.CommandText = "DELETE FROM identity_audit_log"; await cmd.ExecuteNonQueryAsync(); } // Create 3 scopes → 3 ScopeCreated events for (int i = 0; i < 3; i++) { var exchange = await SendScope("create", new CreateScopeRequest { Name = $"audit-multi-{i}-{Guid.NewGuid():N}"[..30], DisplayName = $"Multi {i}" }); exchange.Exception.Should().BeNull(); } // WireTap is fire-and-forget — then the delivery worker: poll until all 3 rows appear (up to 15 s) List> rows = []; for (var attempt = 0; attempt < 30; attempt++) { await Task.Delay(500); rows = await QueryAuditRows("ScopeCreated"); if (rows.Count >= 3) break; } rows.Should().HaveCount(3); // All event_ids should be unique var eventIds = rows.Select(r => r["event_id"]).ToHashSet(); eventIds.Should().HaveCount(3); } } Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditTargetCarriesNoRequestHeadersTests.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/Audit/AuditTargetCarriesNoRequestHeadersTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Audit; /// /// An audit target receives the event and its own headers, never the request that raised it. Events are /// raised on a WireTap copy of the request exchange; up to 4.5.0 that copy's headers (client_secret and the /// other form fields, Authorization, Host, redbHttp.*) travelled on to every audit target. /// [Collection("ProductionHttp")] public sealed class AuditTargetCarriesNoRequestHeadersTests { private static readonly string[] EventHeaders = ["event-type", "event_id", "event_type", "timestamp", "user_id", "client_id", "ip_address", "user_agent", "details"]; private readonly ProductionHttpFixture _fx; private readonly ITestOutputHelper _output; public AuditTargetCarriesNoRequestHeadersTests(ProductionHttpFixture fx, ITestOutputHelper output) { _fx = fx; _output = output; } [Fact] public async Task TokenRequest_EventAtTheTarget_CarriesNoSecretNoTokenNoRequestHeaders() { using var response = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, })); var body = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(HttpStatusCode.OK, "token: {0}", body); var accessToken = JsonDocument.Parse(body).RootElement.GetProperty("access_token").GetString()!; var message = await WaitForAsync(m => Equals(m.Headers.GetValueOrDefault("event_type"), "TokenIssued") && Equals(m.Headers.GetValueOrDefault("client_id"), ProductionHttpFixture.TestClientId)); AssertClean(message, ProductionHttpFixture.TestClientSecret, accessToken); } [Fact] public async Task BearerCall_EventAtTheTarget_CarriesNoAuthorization() { var groupName = "audit-leak-" + Guid.NewGuid().ToString("N")[..8]; using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/groups") { Content = JsonContent.Create(new { name = groupName }), }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); using var response = await _fx.Http.SendAsync(request); response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); var message = await WaitForAsync(m => m.Body.Contains(groupName)); AssertClean(message, ProductionHttpFixture.TestMgmtSecret, _fx.ManagementToken); // The group's name is in the event details and in the call's answer alike: the body must be the event. JsonDocument.Parse(message.Body).RootElement.GetProperty("eventType").GetString().Should().NotBeNullOrEmpty(); } [Fact] public async Task ManagementRoute_EventAtTheTarget_IsTheEventNotTheResponse() { // A startup route of a consumer module, in process: attach a scope to a role, then read the role's // scopes on the same exchange. Both calls answer with a body (a status, a list of scopes); the // target must get the RoleScopeAttached event, never those answers. var suffix = Guid.NewGuid().ToString("N")[..8]; var (roleId, scopeId) = await _fx.UseRedbAsync(async redb => { var svc = new redb.Identity.Core.Services.RoleService(redb); var role = await svc.CreateRoleAsync("audit-body-" + suffix, "organization", applicationId: null, displayName: null, description: null); var scope = new redb.Core.Models.Entities.RedbObject( new redb.Identity.Core.Models.ScopeProps { ScopeName = "audit-body-" + suffix, Description = "Audit body scope" }) { Name = "audit-body-" + suffix }; await redb.SaveAsync(scope); return (role.Id, scope.Id); }); var message = new redb.Route.Core.Message { Body = new Dictionary { ["roleId"] = roleId, ["scopeId"] = scopeId } }; message.Headers["operation"] = "attach-scope"; var exchange = new redb.Route.Core.Exchange(message) { Pattern = redb.Route.Abstractions.ExchangePattern.InOut }; ManagementCallerContext.Apply(exchange, ManagementCaller.Admin); await _fx.Producer.SendAsync(redb.Identity.Contracts.Routes.IdentityEndpoints.ManageRoles, exchange); exchange.Exception.Should().BeNull(); exchange.In = new redb.Route.Core.Message { Body = new Dictionary { ["roleId"] = roleId } }; exchange.In.Headers["operation"] = "list-scopes"; exchange.Out = null; await _fx.Producer.SendAsync(redb.Identity.Contracts.Routes.IdentityEndpoints.ManageRoles, exchange); exchange.Exception.Should().BeNull(); var roleMarker = "\"RoleId\":" + roleId + ","; await WaitForAsync(m => (m.Headers.GetValueOrDefault("details")?.ToString() ?? "").Contains(roleMarker)); await Task.Delay(1500); // the second call's tap, if it raised one, lands shortly after await _fx.DeliverOutboxAsync(); var forRole = _fx.AuditTargetMessages .Where(m => (m.Headers.GetValueOrDefault("details")?.ToString() ?? "").Contains(roleMarker)) .ToList(); // The read on the same exchange raises nothing: the attach is reported once, not again by list-scopes. forRole.Should().ContainSingle(m => Equals(m.Headers.GetValueOrDefault("event_type"), "RoleScopeAttached")); forRole.Should().HaveCount(1); foreach (var m in forRole) { _output.WriteLine("body: " + m.Body); var body = JsonDocument.Parse(m.Body).RootElement; body.ValueKind.Should().Be(JsonValueKind.Object, "the target gets the event, not the call's answer: {0}", m.Body); body.GetProperty("eventType").GetString().Should().Be(m.Headers["event_type"]!.ToString()); body.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty(); m.Body.Should().NotContain("scopeName").And.NotContain("success"); } } [Fact] public async Task ManagementRead_RaisesNoEvent_AndItsAnswerReachesNoTarget() { // Every management operation passes the route's WireTap, reads included. A read raises no event, // and its answer (here the role's scopes) must not be delivered to the audit targets. var suffix = Guid.NewGuid().ToString("N")[..8]; var scopeName = "audit-read-" + suffix; var roleId = await _fx.UseRedbAsync(async redb => { var svc = new redb.Identity.Core.Services.RoleService(redb); var role = await svc.CreateRoleAsync("audit-read-" + suffix, "organization", applicationId: null, displayName: null, description: null); var scope = new redb.Core.Models.Entities.RedbObject( new redb.Identity.Core.Models.ScopeProps { ScopeName = scopeName }) { Name = scopeName }; await redb.SaveAsync(scope); await svc.AttachScopeAsync(role.Id, scope.Id, actingUserId: null); return role.Id; }); var message = new redb.Route.Core.Message { Body = new Dictionary { ["roleId"] = roleId } }; message.Headers["operation"] = "list-scopes"; var exchange = new redb.Route.Core.Exchange(message) { Pattern = redb.Route.Abstractions.ExchangePattern.InOut }; ManagementCallerContext.Apply(exchange, ManagementCaller.Admin); await _fx.Producer.SendAsync(redb.Identity.Contracts.Routes.IdentityEndpoints.ManageRoles, exchange); exchange.Exception.Should().BeNull(); ((exchange.Out ?? exchange.In).Body?.ToString() ?? "").Should().NotBeNull(); await Task.Delay(1500); // the tap is fire-and-forget await _fx.DeliverOutboxAsync(); _fx.AuditTargetMessages.Should().NotContain(m => m.Body.Contains(scopeName), "a read raises no event and its answer goes nowhere"); } private void AssertClean((Dictionary Headers, string Body) message, string secret, string token) { _output.WriteLine("headers: " + string.Join(", ", message.Headers.Keys)); message.Headers.Keys.Should().BeSubsetOf(EventHeaders.Append("Content-Type"), "an audit target gets the event headers only"); message.Headers.Keys.Should().NotContain(k => k.StartsWith("redbHttp.", StringComparison.OrdinalIgnoreCase)); foreach (var value in message.Headers.Values) { var text = value?.ToString() ?? string.Empty; text.Should().NotContain(secret); text.Should().NotContain(token); } message.Body.Should().NotContain(secret).And.NotContain(token); } private async Task<(Dictionary Headers, string Body)> WaitForAsync( Func<(Dictionary Headers, string Body), bool> match) { var deadline = DateTime.UtcNow.AddSeconds(15); while (DateTime.UtcNow < deadline) { await _fx.DeliverOutboxAsync(); foreach (var m in _fx.AuditTargetMessages) if (match(m)) return m; await Task.Delay(100); } throw new TimeoutException("the audit target did not receive the expected event"); } } Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditTargetOutboxTests.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/Audit/AuditTargetOutboxTests.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Contracts.Events; using redb.Identity.Core.Configuration; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Serialization; using Xunit; namespace redb.Identity.Tests.Audit; /// /// External audit targets go through the delivery outbox: a target that is down gets the event when it /// is back, a target removed from the configuration gets nothing and its rows end cancelled. /// [Collection("ProductionHttp")] public sealed class AuditTargetOutboxTests { private const string Target = "test-capture"; private readonly ProductionHttpFixture _fx; public AuditTargetOutboxTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task ATargetThatIsDown_IsRetried_AndGetsTheEventOnceItIsBack() { await _fx.DeliverOutboxAsync(); // clear what earlier tests left var group = await RaiseAsync(); var row = await WaitForRowAsync(group); // The same target name, its endpoint gone: the attempt fails and the row waits for its retry. var down = new WebhookDeliveryWorker(_fx.ServiceProvider, _fx.Context, new DeliveryOptions(), TimeProvider.System, NullLogger.Instance, auditTargets: [new AuditTarget { Name = Target, Enabled = true, Uri = "nosuchtransport:identity-test-audit-down", MaxAttempts = 5, RetryBackoffMs = 50 }]); await RunUntilAsync(down, async () => (await StateAsync(row)).Attempts >= 1); var afterFailure = await StateAsync(row); afterFailure.Status.Should().Be("pending"); afterFailure.LastError.Should().NotBeNullOrEmpty(); _fx.AuditTargetMessages.Should().NotContain(m => m.Body.Contains(group)); // Back: the fixture's own target. var deadline = DateTime.UtcNow.AddSeconds(15); while (!_fx.AuditTargetMessages.Any(m => m.Body.Contains(group)) && DateTime.UtcNow < deadline) { await _fx.DeliverOutboxAsync(); await Task.Delay(50); } _fx.AuditTargetMessages.Count(m => m.Body.Contains(group)).Should().Be(1); var delivered = await StateAsync(row); delivered.Status.Should().Be("delivered"); delivered.Attempts.Should().Be(2); } [Fact] public async Task ATargetRemovedFromTheConfiguration_GetsNothing_AndItsRowIsCancelled() { await _fx.DeliverOutboxAsync(); var group = await RaiseAsync(); var row = await WaitForRowAsync(group); var withoutTargets = new WebhookDeliveryWorker(_fx.ServiceProvider, _fx.Context, new DeliveryOptions(), TimeProvider.System, NullLogger.Instance, auditTargets: []); await RunUntilAsync(withoutTargets, async () => (await StateAsync(row)).Status != "pending"); (await StateAsync(row)).Status.Should().Be("cancelled"); await _fx.DeliverOutboxAsync(); _fx.AuditTargetMessages.Should().NotContain(m => m.Body.Contains(group)); } [Fact] public void TheMessage_IsWhatTheTargetsReceivedBeforeTheOutbox() { // Nested values are encoded differently in the body (camelCase) and in the details header (as // declared); both must reach the target exactly as the events route used to produce them. var evt = new IdentityEvent { EventType = "GroupCreated", UserId = "42", ClientId = null, IpAddress = "10.0.0.1", Details = new Dictionary { ["GroupId"] = 7L, ["Nested"] = new { InnerName = "x" }, ["Text"] = "\"q\" é" }, }; var message = AuditTargetMessage.Build(AuditTargetMessage.Payload(evt)); System.Text.Encoding.UTF8.GetString((byte[])message.Body!) .Should().Be(System.Text.Encoding.UTF8.GetString(new JsonMessageSerializer().Serialize(evt))); message.ContentType.Should().Be("application/json"); message.Headers["details"].Should().Be(JsonSerializer.Serialize(evt.Details)); message.Headers["event_id"].Should().Be(Guid.Parse(evt.EventId)); message.Headers["event_type"].Should().Be("GroupCreated"); message.Headers["event-type"].Should().Be("GroupCreated"); message.Headers["timestamp"].Should().Be(evt.Timestamp); message.Headers["user_id"].Should().Be("42"); message.Headers["client_id"].Should().Be(DBNull.Value); message.Headers["ip_address"].Should().Be("10.0.0.1"); message.Headers["user_agent"].Should().Be(DBNull.Value); } [Fact] public void AnEnabledTargetWithoutAName_OrTwoWithOneName_StopTheStart() { var unnamed = new IdentityAuditOptions { Targets = [new AuditTarget { Enabled = true, Uri = "kafka:audit?brokers=secret@host" }] }; var act = () => AuditTargetEnqueueProcessor.EnabledTargets(unnamed); act.Should().Throw() .WithMessage("*Identity:Audit:Targets:N:Name*") .Which.Message.Should().NotContain("secret", "only the scheme of the URI is named"); var twice = new IdentityAuditOptions { Targets = [ new AuditTarget { Name = "a", Enabled = true, Uri = "log:x" }, new AuditTarget { Name = "a", Enabled = true, Uri = "log:y" }, ], }; var dup = () => AuditTargetEnqueueProcessor.EnabledTargets(twice); dup.Should().Throw().WithMessage("*'a'*unique*"); // A disabled or unnamed-but-disabled target is not checked: it sends nothing. AuditTargetEnqueueProcessor.EnabledTargets(new IdentityAuditOptions { Targets = [new AuditTarget { Enabled = false, Uri = "log:z" }], }).Should().BeEmpty(); } private async Task RaiseAsync() { var name = "audit-outbox-" + Guid.NewGuid().ToString("N")[..12]; using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/groups") { Content = JsonContent.Create(new { name }) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); using var response = await _fx.Http.SendAsync(request); ((int)response.StatusCode).Should().BeInRange(200, 299, await response.Content.ReadAsStringAsync()); return name; } /// The events route runs on a wire tap: wait for the target's row of the event. private async Task WaitForRowAsync(string marker) { var deadline = DateTime.UtcNow.AddSeconds(10); while (true) { var ids = await _fx.UseRedbAsync(redb => redb.Context.QueryAsync( "SELECT id FROM identity_delivery_outbox WHERE kind = 'audit' AND destination = @p0 AND payload LIKE @p1", Target, "%" + marker + "%")); if (ids.Count > 0) return ids.Single().Id; if (DateTime.UtcNow > deadline) throw new TimeoutException("no audit outbox row for the event"); await Task.Delay(50); } } private async Task StateAsync(long id) => (await _fx.UseRedbAsync(redb => redb.Context.QueryAsync( "SELECT status, attempts, last_error FROM identity_delivery_outbox WHERE id = @p0", id))).Single(); private static async Task RunUntilAsync(WebhookDeliveryWorker worker, Func> done) { var deadline = DateTime.UtcNow.AddSeconds(10); while (!await done() && DateTime.UtcNow < deadline) { await worker.RunOnceAsync(); await worker.DrainAsync(); await Task.Delay(50); } } private sealed class IdRow { [System.Text.Json.Serialization.JsonPropertyName("id")] public long Id { get; set; } } private sealed class State { [System.Text.Json.Serialization.JsonPropertyName("status")] public string Status { get; set; } = ""; [System.Text.Json.Serialization.JsonPropertyName("attempts")] public int Attempts { get; set; } [System.Text.Json.Serialization.JsonPropertyName("last_error")] public string? LastError { get; set; } } } Path: redb-identity/tests/redb.Identity.Tests/Authorization/AdminEndpointAuthMatrixTests.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/Authorization/AdminEndpointAuthMatrixTests.cs ---- using System.Net; using System.Net.Http.Headers; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Authorization; /// /// G14 — endpoint-matrix smoke for management-API authorization. /// /// The HTTP facade routes management endpoints through /// ManagementBearerAuthProcessor which requires a bearer access token whose /// scopes intersect { identity:manage, identity:account, scim } (see /// ProductionHttpFixture.InitializeAsync wiring). This test asserts the /// invariant per endpoint: /// /// no token → 401 (cannot enumerate without an access token); /// token without the required scope → 403 (e.g. scim token on /// management routes, or identity:manage token on SCIM routes); /// token with the right scope → 2xx. /// /// /// /// Without this matrix, a refactor that drops ManagementBearerAuthProcessor /// from a single endpoint would silently expose admin operations to unauthenticated /// callers — exactly the IDOR-shaped regression that G14 / B8 aims to lock down. /// /// [Collection("ProductionHttp")] public sealed class AdminEndpointAuthMatrixTests { private readonly ProductionHttpFixture _fx; public AdminEndpointAuthMatrixTests(ProductionHttpFixture fx) => _fx = fx; /// Endpoints requiring identity:manage (or identity:account when self-scoped). public static IEnumerable ManagementEndpoints() => new[] { new object[] { "GET", "/api/v1/identity/users" }, new object[] { "GET", "/api/v1/identity/scopes" }, new object[] { "GET", "/api/v1/identity/sessions?userId=1" }, }; /// SCIM endpoints requiring the scim scope. public static IEnumerable ScimEndpoints() => new[] { new object[] { "GET", "/scim/v2/Users" }, new object[] { "GET", "/scim/v2/Groups" }, }; [Theory] [MemberData(nameof(ManagementEndpoints))] public async Task ManagementEndpoint_WithoutBearerToken_Returns401(string method, string path) { using var req = new HttpRequestMessage(new HttpMethod(method), path); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().Be(401, "{0} {1}: management API must reject anonymous calls — without this guard " + "every Manage* route would be open to the internet (G14 / B8).", method, path); } [Theory] [MemberData(nameof(ManagementEndpoints))] public async Task ManagementEndpoint_WithScimOnlyToken_Returns403(string method, string path) { using var req = new HttpRequestMessage(new HttpMethod(method), path); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ScimToken); var resp = await _fx.Http.SendAsync(req); // 403 (forbidden) is correct; 401 also acceptable if the validator strips // mismatched-scope tokens. The critical assertion is that the call is NOT // allowed (2xx) — that would be cross-scope privilege escalation. var code = (int)resp.StatusCode; (code == 401 || code == 403).Should().BeTrue( "{0} {1}: a SCIM-only token must NOT reach management endpoints (got {2}). " + "Allowing it would let a SCIM provisioner perform admin mutations.", method, path, code); } [Theory] [MemberData(nameof(ManagementEndpoints))] public async Task ManagementEndpoint_WithManagementToken_Returns2xx(string method, string path) { using var req = new HttpRequestMessage(new HttpMethod(method), path); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().BeInRange(200, 299, "{0} {1}: a token bearing identity:manage must be admitted. " + "Status: {2}", method, path, resp.StatusCode); } [Theory] [MemberData(nameof(ScimEndpoints))] public async Task ScimEndpoint_WithoutBearerToken_Returns401(string method, string path) { using var req = new HttpRequestMessage(new HttpMethod(method), path); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().Be(401, "{0} {1}: SCIM API must reject anonymous calls (RFC 7644 §2).", method, path); } [Theory] [MemberData(nameof(ScimEndpoints))] public async Task ScimEndpoint_WithManagementToken_IsRejected(string method, string path) { // Symmetry: a non-SCIM token must NOT pass the SCIM authorization gate. // Otherwise an admin could side-step provisioning audit by crossing scopes. using var req = new HttpRequestMessage(new HttpMethod(method), path); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); var resp = await _fx.Http.SendAsync(req); var code = (int)resp.StatusCode; (code == 401 || code == 403).Should().BeTrue( "{0} {1}: a management-only token must NOT pass the SCIM scope gate (got {2}). " + "Cross-scope acceptance is a privilege-boundary violation.", method, path, code); } [Theory] [MemberData(nameof(ScimEndpoints))] public async Task ScimEndpoint_WithScimToken_Returns2xx(string method, string path) { using var req = new HttpRequestMessage(new HttpMethod(method), path); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ScimToken); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().BeInRange(200, 299, "{0} {1}: a token bearing 'scim' must be admitted. Status: {2}", method, path, resp.StatusCode); } } Path: redb-identity/tests/redb.Identity.Tests/Authorization/PerUserEndpointAuthMatrixTests.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/Authorization/PerUserEndpointAuthMatrixTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Authorization; /// /// G14 — endpoint authorization matrix on per-user management endpoints. /// /// Extends with the three additional /// surface areas called out in the STATUS gap: MFA per-user endpoints, consents, /// and applications. For each, asserts the three-token matrix: /// /// no token → 401 (anonymous rejected); /// wrong-scope token (SCIM-only) → 401/403; /// management-scope token → 2xx. /// /// This is the HTTP-surface bookend of the unit-level /// — a regression that drops /// ManagementBearerAuthProcessor from one of these controllers would let /// anonymous callers mutate MFA / consents / applications. /// /// [Collection("ProductionHttp")] public sealed class PerUserEndpointAuthMatrixTests { private readonly ProductionHttpFixture _fx; public PerUserEndpointAuthMatrixTests(ProductionHttpFixture fx) => _fx = fx; // Endpoints that read/mutate per-user state and MUST be behind // ManagementBearerAuthProcessor (admin or account scope). public static IEnumerable PerUserEndpoints() { // Path + method + request body (null → no body) yield return new object?[] { "GET", "/api/v1/identity/mfa/status/1", null }; yield return new object?[] { "GET", "/api/v1/identity/consents?userId=1", null }; yield return new object?[] { "GET", "/api/v1/identity/applications", null }; yield return new object?[] { "GET", "/api/v1/identity/scopes", null }; yield return new object?[] { "GET", "/api/v1/identity/tokens?userId=1", null }; } [Theory] [MemberData(nameof(PerUserEndpoints))] public async Task Endpoint_WithoutBearerToken_Returns401(string method, string path, string? body) { using var req = BuildRequest(method, path, body, token: null); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().Be(401, "{0} {1}: per-user management endpoint MUST reject anonymous calls. " + "A regression here lets the internet read/mutate user state without credentials.", method, path); } [Theory] [MemberData(nameof(PerUserEndpoints))] public async Task Endpoint_WithScimOnlyToken_IsRejected(string method, string path, string? body) { using var req = BuildRequest(method, path, body, token: _fx.ScimToken); var resp = await _fx.Http.SendAsync(req); var code = (int)resp.StatusCode; (code == 401 || code == 403).Should().BeTrue( "{0} {1}: a SCIM-only token must NOT pass the management scope gate (got {2}). " + "Cross-scope admission is a privilege boundary violation.", method, path, code); } [Theory] [MemberData(nameof(PerUserEndpoints))] public async Task Endpoint_WithManagementToken_IsAdmitted(string method, string path, string? body) { using var req = BuildRequest(method, path, body, token: _fx.ManagementToken); var resp = await _fx.Http.SendAsync(req); // Admission ≠ business-layer success. We only assert the token passed the auth // gate: anything other than 401/403 is acceptable here (endpoint may return 404 // for a user with no MFA state, 400 for a malformed userId, 200 for an empty // list). The invariant under test is that the admin scope MUST be admitted. var code = (int)resp.StatusCode; code.Should().NotBe(401, "{0} {1}: admin-scoped token rejected as unauthenticated (401).", method, path); code.Should().NotBe(403, "{0} {1}: admin-scoped token rejected as forbidden (403).", method, path); } /// /// Pins the B8 IDOR contract at the HTTP layer: a caller holding only /// identity:account (self-scope) cannot mutate MFA for a user whose id /// differs from the token's sub claim. The unit-level coverage lives in /// ; this test exists to /// detect the regression where RequireSelfOrAdminProcessor is dropped /// from the direct-vm route wiring at /// (MfaManage block). /// [Fact] public async Task MfaSetup_WithScimToken_CannotCrossScopeMutate() { // We use ScimToken here as the stand-in for "a token that is NOT identity:manage // and NOT identity:account" — so this covers the same-scope defence as // AdminEndpointAuthMatrix plus the extra guarantee that the /mfa/totp/setup // surface specifically is refused. var body = JsonSerializer.Serialize(new { userId = 9999, username = "victim" }); using var req = new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/mfa/totp/setup") { Content = new StringContent(body, Encoding.UTF8, "application/json"), }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ScimToken); var resp = await _fx.Http.SendAsync(req); var code = (int)resp.StatusCode; (code == 401 || code == 403).Should().BeTrue( "MFA setup MUST NOT be reachable with a token that carries neither identity:manage " + "nor identity:account (got {0}). Dropping the auth processor from MfaManage is a " + "B8 IDOR regression.", code); } private static HttpRequestMessage BuildRequest(string method, string path, string? body, string? token) { var req = new HttpRequestMessage(new HttpMethod(method), path); if (body is not null) req.Content = new StringContent(body, Encoding.UTF8, "application/json"); if (token is not null) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); return req; } } Path: redb-identity/tests/redb.Identity.Tests/Bootstrap/BootstrapAdminEndpointTests.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/Bootstrap/BootstrapAdminEndpointTests.cs ---- using System.Net; using System.Net.Http.Json; using System.Text; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Endpoints; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Bootstrap; /// /// B1 — acceptance tests for the emergency-admin bootstrap endpoint /// (POST /internal/bootstrap-admin). Each test cleans the /// bootstrap_completed sentinel + the identity-web client and the /// identity-bootstrap-admins group from the shared production fixture /// so cases see pristine state regardless of execution order. /// [Collection("ProductionHttp")] public class BootstrapAdminEndpointTests : IAsyncLifetime { private const string FlagName = "bootstrap_completed"; private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; private static int _emailSeed; public BootstrapAdminEndpointTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } public Task InitializeAsync() => CleanupBootstrapStateAsync(); public Task DisposeAsync() => CleanupBootstrapStateAsync(); private async Task CleanupBootstrapStateAsync() { // 1. Clear the sentinel so IsBootstrapCompletedAsync returns false again. await _fx.UseRedbAsync(async redb => { var flag = await redb.Query() .WhereRedb(o => o.Name == FlagName) .FirstOrDefaultAsync(); if (flag is not null) await redb.DeleteAsync(flag.Id); var grp = await redb.Query() .WhereRedb(o => o.Name == ProductionHttpFixture.BootstrapAdminGroup) .FirstOrDefaultAsync(); if (grp is not null) await redb.DeleteAsync(grp.Id); }); // 2. Drop the OIDC client through the OpenIddict manager so its sub-rows // (authorizations / tokens) are cleaned up via the official path. using var scope = _fx.ServiceProvider.CreateScope(); var manager = scope.ServiceProvider.GetRequiredService(); var app = await manager.FindByClientIdAsync(ProductionHttpFixture.BootstrapWebClientId); if (app is not null) await manager.DeleteAsync(app); } private static string NextEmail() => $"bootstrap-admin-{Interlocked.Increment(ref _emailSeed)}-{Guid.NewGuid():N}@test.local"; private static BootstrapAdminRequest ValidRequest(string? email = null) => new() { Email = email ?? NextEmail(), Password = "BootstrapPass!2026", RedirectUri = "https://admin.example.com/callback", PostLogoutRedirectUri = "https://admin.example.com/signed-out", BackchannelLogoutUri = "https://admin.example.com/back-logout", }; private HttpRequestMessage NewBootstrapRequest( BootstrapAdminRequest body, string? secret = ProductionHttpFixture.BootstrapSecret) { var req = new HttpRequestMessage(HttpMethod.Post, "/internal/bootstrap-admin") { Content = JsonContent.Create(body), }; if (secret is not null) req.Headers.Add("X-Bootstrap-Secret", secret); return req; } // ── 1. Happy path ────────────────────────────────────────────────── [Fact] public async Task Bootstrap_Returns_201_OnFirstCall_With_ClientSecret() { var resp = await _http.SendAsync(NewBootstrapRequest(ValidRequest())); resp.StatusCode.Should().Be(HttpStatusCode.Created); var payload = await resp.Content.ReadFromJsonAsync(); payload.Should().NotBeNull(); payload!.UserId.Should().BeGreaterThan(0); payload.GroupId.Should().BeGreaterThan(0); payload.ApplicationId.Should().Be(ProductionHttpFixture.BootstrapWebClientId); payload.ClientSecret.Should().NotBeNullOrEmpty(); payload.ClientSecret!.Length.Should().BeGreaterThanOrEqualTo(40); payload.ScopeName.Should().Be(ProductionHttpFixture.BootstrapAdminScope); // Sentinel must be present after success. await _fx.UseRedbAsync(async redb => { var flag = await redb.Query() .WhereRedb(o => o.Name == FlagName) .FirstOrDefaultAsync(); flag.Should().NotBeNull(); flag!.ValueBool.Should().BeTrue(); flag.ValueString.Should().Be(ProductionHttpFixture.BootstrapWebClientId); }); } // ── 2. Sentinel: second call short-circuits with 410 Gone. ───────── [Fact] public async Task Bootstrap_Returns_410_OnSecondCall() { var first = await _http.SendAsync(NewBootstrapRequest(ValidRequest())); first.StatusCode.Should().Be(HttpStatusCode.Created); var second = await _http.SendAsync(NewBootstrapRequest(ValidRequest())); second.StatusCode.Should().Be(HttpStatusCode.Gone); } // ── 3. Wrong secret ──────────────────────────────────────────────── [Fact] public async Task Bootstrap_Returns_403_OnWrongSecret() { var resp = await _http.SendAsync( NewBootstrapRequest(ValidRequest(), secret: "definitely-not-the-right-secret")); resp.StatusCode.Should().Be(HttpStatusCode.Forbidden); } [Fact] public async Task Bootstrap_Returns_403_OnMissingSecret() { var resp = await _http.SendAsync(NewBootstrapRequest(ValidRequest(), secret: null)); resp.StatusCode.Should().Be(HttpStatusCode.Forbidden); } // ── 4. Disabled deployments → 404 (route is invisible). ─────────── [Fact] public async Task Bootstrap_Returns_404_When_Disabled() { var optsRef = _fx.ServiceProvider .GetRequiredService>().Value.Bootstrap; optsRef.Enabled = false; try { var resp = await _http.SendAsync(NewBootstrapRequest(ValidRequest())); resp.StatusCode.Should().Be(HttpStatusCode.NotFound); } finally { optsRef.Enabled = true; } } // ── 5. Atomicity: pre-existing identity-web client → 409 + flag stays unset. [Fact] public async Task Bootstrap_Is_Atomic_NoSentinel_When_OIDC_Client_Exists() { // Pre-create the canonical client to force a duplicate-collision on step 10. using (var scope = _fx.ServiceProvider.CreateScope()) { var manager = scope.ServiceProvider.GetRequiredService(); await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = ProductionHttpFixture.BootstrapWebClientId, ClientSecret = "preexisting-secret-1234567890", ClientType = OpenIddictConstants.ClientTypes.Confidential, }); } var resp = await _http.SendAsync(NewBootstrapRequest(ValidRequest())); resp.StatusCode.Should().Be(HttpStatusCode.Conflict); // The bootstrap_completed sentinel must NOT be set — atomic rollback. await _fx.UseRedbAsync(async redb => { var flag = await redb.Query() .WhereRedb(o => o.Name == FlagName) .FirstOrDefaultAsync(); flag.Should().BeNull(); }); } // ── 6. Idempotency — pre-existing scope/group is reused, not duplicated. [Fact] public async Task Bootstrap_Idempotent_When_Group_Or_Scope_Already_Exists() { // First successful bootstrap creates the scope + group. var first = await _http.SendAsync(NewBootstrapRequest(ValidRequest())); first.StatusCode.Should().Be(HttpStatusCode.Created); // Roll back ONLY the sentinel + the OIDC client so a second call can run; // leave the scope + group intact so the find-branches of the processor are hit. using (var scope = _fx.ServiceProvider.CreateScope()) { var manager = scope.ServiceProvider.GetRequiredService(); var app = await manager.FindByClientIdAsync(ProductionHttpFixture.BootstrapWebClientId); if (app is not null) await manager.DeleteAsync(app); } await _fx.UseRedbAsync(async redb => { var flag = await redb.Query() .WhereRedb(o => o.Name == FlagName).FirstOrDefaultAsync(); if (flag is not null) await redb.DeleteAsync(flag.Id); }); var second = await _http.SendAsync(NewBootstrapRequest(ValidRequest())); second.StatusCode.Should().Be(HttpStatusCode.Created); // Exactly one scope + one group row — no duplicates were created. await _fx.UseRedbAsync(async redb => { var scopeCount = (await redb.Query() .Where(p => p.ScopeName == ProductionHttpFixture.BootstrapAdminScope) .ToListAsync()).Count; scopeCount.Should().Be(1); var groupCount = (await redb.Query() .WhereRedb(o => o.Name == ProductionHttpFixture.BootstrapAdminGroup) .ToListAsync()).Count; groupCount.Should().Be(1); }); } // ── 7. Validation guard — bad payload returns 400. ──────────────── [Fact] public async Task Bootstrap_Returns_400_OnInvalidRequest() { var bad = new BootstrapAdminRequest { Email = "missing-everything-else@test.local", // Password missing → ValidateRequest fails. }; var resp = await _http.SendAsync(NewBootstrapRequest(bad)); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); } // ── 8. Race condition — two concurrent calls; exactly one wins. ─── [Fact] public async Task Bootstrap_RaceCondition_TwoConcurrentCalls_OnlyOneSucceeds() { var t1 = _http.SendAsync(NewBootstrapRequest(ValidRequest())); var t2 = _http.SendAsync(NewBootstrapRequest(ValidRequest())); var responses = await Task.WhenAll(t1, t2); var statuses = responses.Select(r => (int)r.StatusCode).OrderBy(x => x).ToArray(); // One must succeed, the other must be 410 (lost the race) or 409 (lost on the // OIDC-client unique constraint before the sentinel write committed). statuses[0].Should().Be(201); statuses[1].Should().BeOneOf(409, 410); } } Path: redb-identity/tests/redb.Identity.Tests/Bugs/FourScopesBugReproTest.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/Bugs/FourScopesBugReproTest.cs ---- using System.Security.Cryptography; using System.Text; using AwesomeAssertions; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Bugs; /// /// Reproduction test for the 4-scopes bug: /// "openid profile email phone" together → DbException. /// [Collection("ProductionBootstrap")] public class FourScopesBugReproTest { private readonly ProductionBootstrapFixture _fx; private readonly ITestOutputHelper _output; public FourScopesBugReproTest(ProductionBootstrapFixture fx, ITestOutputHelper output) { _fx = fx; _output = output; } [Fact] public async Task AuthCode_WithFourScopes_ShouldNotCrash() { // This is the exact scope combination that causes the DbException var scopes = "openid profile email phone"; try { var accessToken = await ObtainAccessToken(scopes); _output.WriteLine($"SUCCESS: Got access token with 4 scopes: {accessToken[..20]}..."); accessToken.Should().NotBeNullOrEmpty(); } catch (Exception ex) { // Log the FULL exception tree so we can see the root cause _output.WriteLine("=== EXCEPTION CAUGHT ==="); var current = ex; int depth = 0; while (current != null) { _output.WriteLine($"--- Exception depth {depth} ---"); _output.WriteLine($"Type: {current.GetType().FullName}"); _output.WriteLine($"Message: {current.Message}"); _output.WriteLine($"Stack: {current.StackTrace}"); current = current.InnerException; depth++; } throw; // Re-throw to fail the test } } [Fact] public async Task AuthCode_WithThreeScopes_ShouldWork() { // Baseline: 3 scopes works fine var accessToken = await ObtainAccessToken("openid profile email"); _output.WriteLine($"SUCCESS: Got access token with 3 scopes: {accessToken[..20]}..."); accessToken.Should().NotBeNullOrEmpty(); } private async Task ObtainAccessToken(string scopes) { var (codeVerifier, codeChallenge) = GeneratePkce(); var authorizeBody = new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionBootstrapFixture.TestClientIdPublic, ["redirect_uri"] = ProductionBootstrapFixture.TestRedirectUri, ["scope"] = scopes, ["code_challenge"] = codeChallenge, ["code_challenge_method"] = "S256" }; var authorizeResult = await _fx.RequestWithSession(IdentityEndpoints.Authorize, authorizeBody); var authorizeResponse = (Dictionary)authorizeResult!; _output.WriteLine($"Authorize response keys: [{string.Join(", ", authorizeResponse.Keys)}]"); foreach (var kv in authorizeResponse) _output.WriteLine($" {kv.Key} = {kv.Value}"); authorizeResponse.Should().ContainKey("code", $"Authorize failed. Response: {string.Join(", ", authorizeResponse.Select(kv => $"{kv.Key}={kv.Value}"))}"); var code = authorizeResponse["code"]!.ToString()!; var tokenBody = new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code, ["redirect_uri"] = ProductionBootstrapFixture.TestRedirectUri, ["client_id"] = ProductionBootstrapFixture.TestClientIdPublic, ["code_verifier"] = codeVerifier }; var tokenResult = await _fx.Request(IdentityEndpoints.Token, tokenBody); var tokenResponse = (Dictionary)tokenResult!; _output.WriteLine($"Token response keys: [{string.Join(", ", tokenResponse.Keys)}]"); foreach (var kv in tokenResponse) _output.WriteLine($" {kv.Key} = {kv.Value?.ToString()?[..Math.Min(kv.Value?.ToString()?.Length ?? 0, 80)]}"); tokenResponse.Should().ContainKey("access_token", $"Token exchange failed. Response: {string.Join(", ", tokenResponse.Select(kv => $"{kv.Key}={kv.Value}"))}"); return tokenResponse["access_token"]!.ToString()!; } private static (string codeVerifier, string codeChallenge) GeneratePkce() { var bytes = RandomNumberGenerator.GetBytes(32); var verifier = Convert.ToBase64String(bytes) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = SHA256.HashData(Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } } Path: redb-identity/tests/redb.Identity.Tests/Bugs/FourScopesEavTest.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/Bugs/FourScopesEavTest.cs ---- using AwesomeAssertions; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Bugs; /// /// Low-level reproduction: save/load AuthorizationProps with various scope counts. /// Bypass OpenIddict and route error handlers to see raw PROPS exceptions. /// [Collection("Postgres")] public class FourScopesPropsTest { private readonly PostgresFixture _fx; private readonly ITestOutputHelper _output; public FourScopesPropsTest(PostgresFixture fx, ITestOutputHelper output) { _fx = fx; _output = output; } [Theory] [InlineData(new[] { "openid" }, "1 scope")] [InlineData(new[] { "openid", "profile" }, "2 scopes")] [InlineData(new[] { "openid", "profile", "email" }, "3 scopes")] [InlineData(new[] { "openid", "profile", "email", "phone" }, "4 scopes")] [InlineData(new[] { "openid", "profile", "email", "phone", "offline_access" }, "5 scopes")] public async Task SaveAndLoad_AuthorizationWithScopes(string[] scopes, string label) { _output.WriteLine($"Testing {label}: [{string.Join(", ", scopes)}]"); // Create an authorization with the given scopes var auth = new RedbObject { key = 99999, // dummy user id Props = new AuthorizationProps { ApplicationObjectId = 1, Status = "valid", Type = "ad-hoc", Scopes = scopes, Properties = new Dictionary { ["creation_date"] = DateTimeOffset.UtcNow.ToString("O") } } }; try { // Save var id = await _fx.Redb.SaveAsync(auth); _output.WriteLine($" Saved with id={id}"); id.Should().BeGreaterThan(0); // Load var loaded = await _fx.Redb.LoadAsync(id); _output.WriteLine($" Loaded: Scopes=[{string.Join(", ", loaded?.Props.Scopes ?? [])}]"); loaded.Should().NotBeNull(); loaded!.Props.Scopes.Should().BeEquivalentTo(scopes); // Query var queried = await _fx.Redb.Query() .WhereRedb(o => o.Key == 99999) .Where(a => a.Status == "valid") .Where(a => a.Type == "ad-hoc") .ToListAsync(); _output.WriteLine($" Query returned {queried.Count} results"); queried.Should().Contain(a => a.id == id); // Cleanup await _fx.Redb.DeleteAsync(id); _output.WriteLine($" Cleaned up"); } catch (Exception ex) { _output.WriteLine($" FAILED: {ex.GetType().Name}: {ex.Message}"); var inner = ex.InnerException; while (inner != null) { _output.WriteLine($" Inner: {inner.GetType().Name}: {inner.Message}"); inner = inner.InnerException; } throw; } } [Fact] public async Task SaveAndLoad_AuthorizationWithFourScopes_NoProperties() { // Test whether Properties dict contributes to the problem var auth = new RedbObject { key = 99998, Props = new AuthorizationProps { ApplicationObjectId = 1, Status = "valid", Type = "ad-hoc", Scopes = new[] { "openid", "profile", "email", "phone" }, Properties = null // No properties } }; var id = await _fx.Redb.SaveAsync(auth); _output.WriteLine($"Saved 4 scopes (no properties) with id={id}"); var loaded = await _fx.Redb.LoadAsync(id); loaded.Should().NotBeNull(); loaded!.Props.Scopes.Should().BeEquivalentTo("openid", "profile", "email", "phone"); await _fx.Redb.DeleteAsync(id); } } Path: redb-identity/tests/redb.Identity.Tests/Bugs/FourScopesManagerTest.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/Bugs/FourScopesManagerTest.cs ---- using System.Collections.Immutable; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Bugs; /// /// Direct OpenIddict manager test to isolate the 4-scopes DbException. /// Uses the production bootstrap fixture's service provider to access managers directly. /// [Collection("ProductionBootstrap")] public class FourScopesManagerTest { private readonly ProductionBootstrapFixture _fx; private readonly ITestOutputHelper _output; public FourScopesManagerTest(ProductionBootstrapFixture fx, ITestOutputHelper output) { _fx = fx; _output = output; } [Theory] [InlineData("openid profile email", "3 scopes")] [InlineData("openid profile email phone", "4 scopes")] public async Task CreateAuthorization_ViaManager(string scopeStr, string label) { _output.WriteLine($"Testing {label}: {scopeStr}"); var scopes = scopeStr.Split(' '); var authManager = _fx.ServiceProvider.GetRequiredService(); var appManager = _fx.ServiceProvider.GetRequiredService(); // Find the test app var app = await appManager.FindByClientIdAsync(ProductionBootstrapFixture.TestClientIdPublic) ?? throw new Exception("Test app not found"); var appId = await appManager.GetIdAsync(app); _output.WriteLine($" App id: {appId}"); // Find test user — the OpenIddict subject is now the user's value_guid. var coreUser = await _fx.Redb.UserProvider.GetUserByLoginAsync(ProductionBootstrapFixture.TestUsername) ?? throw new Exception("Test user not found"); var oidcObj = await _fx.Redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync() ?? throw new Exception($"UserProps row missing for user {coreUser.Id} — bootstrap should seed value_guid"); if (oidcObj.value_guid is null || oidcObj.value_guid == Guid.Empty) throw new Exception("UserProps.value_guid not set — bootstrap must populate the per-user GUID"); var userId = oidcObj.value_guid.Value.ToString("D"); _output.WriteLine($" User id (bigint): {coreUser.Id}"); _output.WriteLine($" Subject (GUID): {userId}"); try { // Step 1: FindAsync (same as OpenIddict's ProcessSignIn) _output.WriteLine(" Step 1: FindAsync..."); var existing = new List(); await foreach (var auth in authManager.FindAsync( userId, appId, OpenIddictConstants.Statuses.Valid, OpenIddictConstants.AuthorizationTypes.Permanent, scopes.ToImmutableArray())) { existing.Add(auth); } _output.WriteLine($" FindAsync returned {existing.Count} results"); // Step 2: CreateAsync (same as OpenIddict's ProcessSignIn when no existing auth) _output.WriteLine(" Step 2: CreateAsync..."); var descriptor = new OpenIddictAuthorizationDescriptor { ApplicationId = appId, Subject = userId, Status = OpenIddictConstants.Statuses.Valid, Type = OpenIddictConstants.AuthorizationTypes.Permanent, }; foreach (var scope in scopes) descriptor.Scopes.Add(scope); var created = await authManager.CreateAsync(descriptor); var createdId = await authManager.GetIdAsync(created); _output.WriteLine($" Created authorization id={createdId}"); // Step 3: Load it back _output.WriteLine(" Step 3: FindByIdAsync..."); var loaded = await authManager.FindByIdAsync(createdId!); loaded.Should().NotBeNull(); _output.WriteLine($" Loaded successfully"); // Cleanup await authManager.DeleteAsync(created); _output.WriteLine($" Cleaned up"); } catch (Exception ex) { _output.WriteLine("=== EXCEPTION ==="); var current = ex; int depth = 0; while (current != null) { _output.WriteLine($"--- Depth {depth} ---"); _output.WriteLine($"Type: {current.GetType().FullName}"); _output.WriteLine($"Message: {current.Message}"); _output.WriteLine($"Stack:\n{current.StackTrace}"); current = current.InnerException; depth++; } throw; } } [Fact] public async Task CreateToken_WithFourScopeAuthorization() { _output.WriteLine("Testing: create token referencing 4-scope authorization"); var scopes = new[] { "openid", "profile", "email", "phone" }; var authManager = _fx.ServiceProvider.GetRequiredService(); var tokenManager = _fx.ServiceProvider.GetRequiredService(); var appManager = _fx.ServiceProvider.GetRequiredService(); var app = await appManager.FindByClientIdAsync(ProductionBootstrapFixture.TestClientIdPublic) ?? throw new Exception("Test app not found"); var appId = await appManager.GetIdAsync(app); var coreUser = await _fx.Redb.UserProvider.GetUserByLoginAsync(ProductionBootstrapFixture.TestUsername) ?? throw new Exception("Test user not found"); var oidcObj = await _fx.Redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync() ?? throw new Exception($"UserProps row missing for user {coreUser.Id}"); if (oidcObj.value_guid is null || oidcObj.value_guid == Guid.Empty) throw new Exception("UserProps.value_guid not set"); var userId = oidcObj.value_guid.Value.ToString("D"); object? auth = null; object? token = null; try { // Create authorization with 4 scopes _output.WriteLine(" Creating authorization with 4 scopes..."); var authDescriptor = new OpenIddictAuthorizationDescriptor { ApplicationId = appId, Subject = userId, Status = OpenIddictConstants.Statuses.Valid, Type = OpenIddictConstants.AuthorizationTypes.AdHoc, }; foreach (var scope in scopes) authDescriptor.Scopes.Add(scope); auth = await authManager.CreateAsync(authDescriptor); var authId = await authManager.GetIdAsync(auth); _output.WriteLine($" Authorization created: {authId}"); // Create token referencing this authorization _output.WriteLine(" Creating token..."); var tokenDescriptor = new OpenIddictTokenDescriptor { ApplicationId = appId, AuthorizationId = authId, Subject = userId, Status = OpenIddictConstants.Statuses.Valid, Type = OpenIddictConstants.TokenTypeIdentifiers.Private.AuthorizationCode, }; token = await tokenManager.CreateAsync(tokenDescriptor); var tokenId = await tokenManager.GetIdAsync(token); _output.WriteLine($" Token created: {tokenId}"); // Now try to find the token by authorization _output.WriteLine(" Finding tokens by authorization..."); var tokens = new List(); await foreach (var t in tokenManager.FindByAuthorizationIdAsync(authId!)) tokens.Add(t); _output.WriteLine($" Found {tokens.Count} tokens"); // Cleanup if (token != null) await tokenManager.DeleteAsync(token); if (auth != null) await authManager.DeleteAsync(auth); _output.WriteLine(" Cleaned up"); } catch (Exception ex) { _output.WriteLine("=== EXCEPTION ==="); var current = ex; while (current != null) { _output.WriteLine($"Type: {current.GetType().FullName}"); _output.WriteLine($"Message: {current.Message}"); _output.WriteLine($"Stack:\n{current.StackTrace}"); current = current.InnerException; } // Try cleanup even on failure try { if (token != null) await tokenManager.DeleteAsync(token); } catch { } try { if (auth != null) await authManager.DeleteAsync(auth); } catch { } throw; } } } Path: redb-identity/tests/redb.Identity.Tests/Bugs/FourScopesPipelineTest.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/Bugs/FourScopesPipelineTest.cs ---- using System.Collections.Immutable; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Server; using redb.Identity.Core.Models; using redb.Identity.Core.OpenIddict; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Bugs; /// /// Bypass the route's OnException handler and call the OpenIddict pipeline directly /// to get the raw DbException stack trace. /// [Collection("ProductionBootstrap")] public class FourScopesPipelineTest { private readonly ProductionBootstrapFixture _fx; private readonly ITestOutputHelper _output; public FourScopesPipelineTest(ProductionBootstrapFixture fx, ITestOutputHelper output) { _fx = fx; _output = output; } [Theory] [InlineData("openid profile email", "3 scopes")] [InlineData("openid profile email phone", "4 scopes")] public async Task AuthCode_ViaPipeline(string scopes, string label) { _output.WriteLine($"Testing {label}: {scopes}"); using var scope = _fx.ServiceProvider.CreateScope(); var handler = scope.ServiceProvider.GetRequiredService(); var body = new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionBootstrapFixture.TestClientIdPublic, ["redirect_uri"] = ProductionBootstrapFixture.TestRedirectUri, ["scope"] = scopes, ["code_challenge"] = "test-challenge-placeholder-that-is-at-least-43-chars-long-for-pkce", ["code_challenge_method"] = "S256" }; var exchange = new TestExchange { In = new TestMessage { Body = body }, Pattern = ExchangePattern.InOut }; exchange.In.Headers["session_user_id"] = _fx.TestUserId; exchange.In.Headers["session_username"] = ProductionBootstrapFixture.TestUsername; exchange.Out = new TestMessage(); try { await handler.ProcessAsync(exchange, OpenIddictServerEndpointType.Authorization); var response = exchange.Out?.Body; _output.WriteLine($"Response type: {response?.GetType().Name}"); if (response is IDictionary dict) { foreach (var kv in dict) _output.WriteLine($" {kv.Key} = {kv.Value?.ToString()?[..Math.Min(kv.Value?.ToString()?.Length ?? 0, 80)]}"); } else { _output.WriteLine($" Body: {response}"); } } catch (Exception ex) { _output.WriteLine("=== RAW EXCEPTION (no route masking) ==="); var current = ex; int depth = 0; while (current != null) { _output.WriteLine($"--- Depth {depth} ---"); _output.WriteLine($"Type: {current.GetType().FullName}"); _output.WriteLine($"Message: {current.Message}"); _output.WriteLine($"Stack:\n{current.StackTrace}"); current = current.InnerException; depth++; } throw; } } } Path: redb-identity/tests/redb.Identity.Tests/Bugs/PayloadNoteE2ETest.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/Bugs/PayloadNoteE2ETest.cs ---- using System.Security.Cryptography; using System.Text; using AwesomeAssertions; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Stores; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Bugs; /// /// Full-stack E2E: complete authorization_code flow with 4 scopes, /// then verify that token payload is stored in _objects.note (not PROPS _values._string). /// [Collection("ProductionBootstrap")] public class PayloadNoteE2ETest { private readonly ProductionBootstrapFixture _fx; private readonly ITestOutputHelper _output; public PayloadNoteE2ETest(ProductionBootstrapFixture fx, ITestOutputHelper output) { _fx = fx; _output = output; } [Fact] public async Task FourScopes_TokenPayload_StoredInNote() { // Snapshot existing token count var store = new RedbTokenStore(_fx.Redb); var beforeCount = await store.CountAsync(CancellationToken.None); var beforeTime = DateTimeOffset.UtcNow.AddSeconds(-2); // Full auth_code + PKCE flow with 4 scopes var (codeVerifier, codeChallenge) = GeneratePkce(); var authorizeBody = new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionBootstrapFixture.TestClientIdPublic, ["redirect_uri"] = ProductionBootstrapFixture.TestRedirectUri, ["scope"] = "openid profile email phone", ["code_challenge"] = codeChallenge, ["code_challenge_method"] = "S256" }; var authorizeResult = await _fx.RequestWithSession(IdentityEndpoints.Authorize, authorizeBody); var authorizeResponse = (Dictionary)authorizeResult!; authorizeResponse.Should().ContainKey("code"); var code = authorizeResponse["code"]!.ToString()!; _output.WriteLine($"Got authorization code: {code[..Math.Min(code.Length, 20)]}..."); var tokenBody = new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code, ["redirect_uri"] = ProductionBootstrapFixture.TestRedirectUri, ["client_id"] = ProductionBootstrapFixture.TestClientIdPublic, ["code_verifier"] = codeVerifier }; var tokenResult = await _fx.Request(IdentityEndpoints.Token, tokenBody); var tokenResponse = (Dictionary)tokenResult!; tokenResponse.Should().ContainKey("access_token"); _output.WriteLine("Token exchange succeeded with 4 scopes"); // Find tokens created AFTER our flow started (i.e. the new ones) var allTokens = new List>(); await foreach (var t in store.ListAsync(null, null, CancellationToken.None)) { if (t.date_create >= beforeTime) allTokens.Add(t); } _output.WriteLine($"New tokens created during this test: {allTokens.Count}"); // Authorization codes and reference tokens get payload stored. // Self-contained JWTs (access_token with DisableAccessTokenEncryption) // may NOT store payload (the JWT itself is the payload). // So we check: any token that does have note should have null Props.Payload foreach (var t in allTokens) { _output.WriteLine($" Token id={t.id}, type={t.Props.Type}, " + $"note={(!string.IsNullOrEmpty(t.note) ? $"{t.note.Length}b" : "null")}, " + $"Props.Payload={(t.Props.Payload != null ? "SET" : "null")}"); // The key invariant: Props.Payload is NEVER in PROPS (always null after load) t.Props.Payload.Should().BeNull( $"Token {t.id} ({t.Props.Type}): Payload should not be in PROPS — [RedbIgnore] excludes it"); } // There should be new tokens from the flow allTokens.Should().NotBeEmpty("the auth code flow should create at least one token"); } [Fact] public async Task TokenPayload_SurvivesUpdateCycle() { // Create a token with payload in note, update status, verify payload survives var store = new RedbTokenStore(_fx.Redb); var appStore = new RedbApplicationStore(_fx.Redb); var authStore = new RedbAuthorizationStore(_fx.Redb); // Create supporting entities var app = new RedbObject { name = $"payload-e2e-{Guid.NewGuid():N}", Props = new ApplicationProps { ClientId = $"pe2e-{Guid.NewGuid():N}", ClientType = "confidential" } }; await appStore.CreateAsync(app, CancellationToken.None); var auth = new RedbObject { key = 1, Props = new AuthorizationProps { ApplicationObjectId = app.id, Status = "valid", Type = "permanent" } }; await authStore.CreateAsync(auth, CancellationToken.None); // Create token with large payload in note var largePayload = new string('J', 5000); var token = new RedbObject { key = 1, value_long = app.id, value_string = $"ref-{Guid.NewGuid():N}", note = largePayload, Props = new TokenProps { AuthorizationObjectId = auth.id, Status = "valid", Type = "access_token" } }; await store.CreateAsync(token, CancellationToken.None); _output.WriteLine($"Created token id={token.id} with {largePayload.Length}b payload in note"); // Update status var loaded = (await store.FindByIdAsync(token.id.ToString(), CancellationToken.None))!; loaded.Props.Status = "revoked"; await store.UpdateAsync(loaded, CancellationToken.None); // Reload and verify payload survived var reloaded = (await store.FindByIdAsync(token.id.ToString(), CancellationToken.None))!; reloaded.note.Should().Be(largePayload, "payload in note should survive status update"); reloaded.Props.Status.Should().Be("revoked"); _output.WriteLine("Payload survived update cycle"); } private static (string codeVerifier, string codeChallenge) GeneratePkce() { var bytes = RandomNumberGenerator.GetBytes(32); var verifier = Convert.ToBase64String(bytes) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = SHA256.HashData(Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } } Path: redb-identity/tests/redb.Identity.Tests/Bugs/PayloadNoteStorageTest.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/Bugs/PayloadNoteStorageTest.cs ---- using AwesomeAssertions; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Stores; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Bugs; /// /// Tests that token Payload is stored in root _objects.note field /// instead of PROPS _values._string, avoiding btree index size limits. /// [Collection("Postgres")] public class PayloadNoteStorageTest { private readonly PostgresFixture _fx; private readonly RedbTokenStore _store; private readonly RedbApplicationStore _appStore; private readonly RedbAuthorizationStore _authStore; private readonly ITestOutputHelper _output; public PayloadNoteStorageTest(PostgresFixture fx, ITestOutputHelper output) { _fx = fx; _output = output; _store = new RedbTokenStore(fx.Redb); _appStore = new RedbApplicationStore(fx.Redb); _authStore = new RedbAuthorizationStore(fx.Redb); } private async Task<(long appId, long authId)> CreateTestInfraAsync() { var app = new RedbObject { name = $"payload-test-{Guid.NewGuid():N}", Props = new ApplicationProps { ClientId = $"pay-{Guid.NewGuid():N}", ClientType = "confidential" } }; await _appStore.CreateAsync(app, CancellationToken.None); var auth = new RedbObject { key = 1, Props = new AuthorizationProps { ApplicationObjectId = app.id, Status = "valid", Type = "permanent" } }; await _authStore.CreateAsync(auth, CancellationToken.None); return (app.id, auth.id); } // ────────── Unit-level: SetPayload writes to note, GetPayload reads from note ────────── [Fact] public async Task SetPayloadAsync_WritesToNoteField() { var token = await _store.InstantiateAsync(CancellationToken.None); await _store.SetPayloadAsync(token, "test-payload", CancellationToken.None); token.note.Should().Be("test-payload"); } [Fact] public async Task GetPayloadAsync_ReadsFromNoteField() { var token = await _store.InstantiateAsync(CancellationToken.None); token.note = "note-payload"; var result = await _store.GetPayloadAsync(token, CancellationToken.None); result.Should().Be("note-payload"); } [Fact] public async Task PayloadRoundtrip_ViaSetGet() { var token = await _store.InstantiateAsync(CancellationToken.None); const string payload = "{\"sub\":\"test\",\"scope\":\"openid profile\"}"; await _store.SetPayloadAsync(token, payload, CancellationToken.None); var result = await _store.GetPayloadAsync(token, CancellationToken.None); result.Should().Be(payload); } [Fact] public async Task SetPayloadAsync_NullValue_SetsNoteNull() { var token = await _store.InstantiateAsync(CancellationToken.None); token.note = "something"; await _store.SetPayloadAsync(token, null, CancellationToken.None); token.note.Should().BeNull(); } [Fact] public async Task PayloadIgnoredByProps_PropsPayloadStaysNull() { // [RedbIgnore] means Props.Payload is not saved to PROPS. // After save+reload, Props.Payload should be null/default, // while note field should hold the actual payload. var (appId, authId) = await CreateTestInfraAsync(); var token = new RedbObject { key = 1, value_long = appId, value_string = $"ref-{Guid.NewGuid():N}", note = "{\"aud\":\"test\"}", Props = new TokenProps { AuthorizationObjectId = authId, Status = "valid", Type = "access_token" } }; await _store.CreateAsync(token, CancellationToken.None); var loaded = await _store.FindByIdAsync(token.id.ToString(), CancellationToken.None); loaded.Should().NotBeNull(); // note field should be persisted loaded!.note.Should().Be("{\"aud\":\"test\"}"); // Props.Payload should be null — it's [RedbIgnore], not stored in PROPS loaded.Props.Payload.Should().BeNull(); } // ────────── Integration: Large payloads that would crash btree ────────── [Fact] public async Task LargePayload_SavedInNote_NoBtreeOverflow() { var (appId, authId) = await CreateTestInfraAsync(); // Generate a payload larger than the 2704-byte btree limit var largePayload = new string('x', 4000); _output.WriteLine($"Payload size: {largePayload.Length} bytes"); var token = new RedbObject { key = 1, value_long = appId, value_string = $"ref-{Guid.NewGuid():N}", note = largePayload, Props = new TokenProps { AuthorizationObjectId = authId, Status = "valid", Type = "access_token" } }; // Should NOT throw — note is TEXT without btree index await _store.CreateAsync(token, CancellationToken.None); token.id.Should().BeGreaterThan(0); _output.WriteLine($"Token saved with id={token.id}"); // Reload and verify var loaded = await _store.FindByIdAsync(token.id.ToString(), CancellationToken.None); loaded.Should().NotBeNull(); loaded!.note.Should().Be(largePayload); } [Fact] public async Task RealisticJwtPayload_5000Bytes_Roundtrips() { var (appId, authId) = await CreateTestInfraAsync(); // Simulate a realistic JWT payload with 4 scopes + claims var realisticPayload = """ {"sub":"12345","name":"Test User","email":"test@example.com", "email_verified":true,"phone_number":"+1234567890", "phone_number_verified":false,"preferred_username":"testuser", "given_name":"Test","family_name":"User","locale":"en", "iss":"https://identity.example.com/","aud":"my-app", "exp":1749657600,"iat":1749654000,"nbf":1749654000, "scope":"openid profile email phone", "azp":"my-app","at_hash":"abc123","c_hash":"def456", "nonce":"random-nonce-value","auth_time":1749654000, "acr":"urn:mace:incommon:iap:silver", "amr":["pwd","mfa"],"jti":"unique-token-id-12345", "custom_claim_1":"value1","custom_claim_2":"value2", "custom_claim_3":"value3","custom_claim_4":"value4", "roles":["admin","user","moderator","editor"], "permissions":["read","write","delete","manage"], "org_id":"org-123","tenant_id":"tenant-456", "session_id":"sess-789","device_id":"dev-012"} """; // Pad to ~5000 bytes realisticPayload += new string(' ', 5000 - realisticPayload.Length); _output.WriteLine($"Realistic payload size: {realisticPayload.Length} bytes"); var token = new RedbObject { key = 1, value_long = appId, value_string = $"ref-{Guid.NewGuid():N}", note = realisticPayload, Props = new TokenProps { AuthorizationObjectId = authId, Status = "valid", Type = "access_token" } }; await _store.CreateAsync(token, CancellationToken.None); _output.WriteLine($"Saved token id={token.id}"); var loaded = await _store.FindByIdAsync(token.id.ToString(), CancellationToken.None); loaded!.note.Should().Be(realisticPayload); } [Fact] public async Task UpdatePayload_ViaNote_Roundtrips() { var (appId, authId) = await CreateTestInfraAsync(); var token = new RedbObject { key = 1, value_long = appId, value_string = $"ref-{Guid.NewGuid():N}", note = "original-payload", Props = new TokenProps { AuthorizationObjectId = authId, Status = "valid", Type = "access_token" } }; await _store.CreateAsync(token, CancellationToken.None); // Reload, update payload via SetPayloadAsync, save again var loaded = (await _store.FindByIdAsync(token.id.ToString(), CancellationToken.None))!; await _store.SetPayloadAsync(loaded, "updated-payload", CancellationToken.None); await _store.UpdateAsync(loaded, CancellationToken.None); // Reload and verify var reloaded = (await _store.FindByIdAsync(token.id.ToString(), CancellationToken.None))!; reloaded.note.Should().Be("updated-payload"); (await _store.GetPayloadAsync(reloaded, CancellationToken.None)).Should().Be("updated-payload"); } [Fact] public async Task PropsFieldsUnaffected_WhenPayloadInNote() { var (appId, authId) = await CreateTestInfraAsync(); var referenceId = $"ref-id-{Guid.NewGuid():N}"; var token = new RedbObject { key = 42, value_long = appId, value_string = $"ref-{Guid.NewGuid():N}", note = "jwt-body-here", Props = new TokenProps { AuthorizationObjectId = authId, Status = "valid", Type = "refresh_token", // Unique per run: ReferenceId is a [RedbUnique] key since V4, and a persistent PG/MSSQL // database keeps the previous run's token — a fixed value collides on the second run. ReferenceId = referenceId } }; await _store.CreateAsync(token, CancellationToken.None); var loaded = (await _store.FindByIdAsync(token.id.ToString(), CancellationToken.None))!; // PROPS fields are intact loaded.Props.Status.Should().Be("valid"); loaded.Props.Type.Should().Be("refresh_token"); loaded.Props.ReferenceId.Should().Be(referenceId); loaded.Props.AuthorizationObjectId.Should().Be(authId); // Payload is in note, not in PROPS loaded.note.Should().Be("jwt-body-here"); loaded.Props.Payload.Should().BeNull(); } } Path: redb-identity/tests/redb.Identity.Tests/ClaimMappers/ClaimMappersIntegrationTests.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/ClaimMappers/ClaimMappersIntegrationTests.cs ---- using System.Data.Common; using System.Security.Claims; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Npgsql; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Models.Entities; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Identity.Contracts.ClaimMappers; using redb.Identity.Contracts.Common; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using Xunit; using static OpenIddict.Abstractions.OpenIddictConstants; using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.ClaimMappers; /// /// H5 (v1.0 DoD §5): integration tests for declarative claim mapper resolution. /// Covers global mappers, per-application overlay, Client Scope assignment, /// scope filtering, last-write-wins precedence and Required-failure rejection. /// public class ClaimMappersIntegrationTests : IAsyncLifetime { private const string PgConnString = "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true"; private ServiceProvider _sp = null!; private IRedbService _redb = null!; private RouteContext _ctx = null!; private ClaimMappersResolver _resolver = null!; public async Task InitializeAsync() { DbProviderFactories.RegisterFactory("Npgsql", NpgsqlFactory.Instance); var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var cs = config.GetPostgresConnectionString() ?? PgConnString; var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var idOpts = new RedbIdentityOptions { Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true, TokenThrottleMaxPerPeriod = 1000, }; services.AddSingleton(Options.Create(idOpts)); services.AddSingleton(Options.Create(new IdentityAuditOptions { Enabled = false })); services.AddRedbIdentityServer(idOpts); _sp = services.BuildServiceProvider(); _redb = _sp.GetRequiredService(); try { await _redb.InitializeAsync(ensureCreated: true); } catch { await _redb.InitializeAsync(); } await _redb.SyncSchemeAsync(); await _redb.SyncSchemeAsync(); await _redb.SyncSchemeAsync(); await _redb.SyncSchemeAsync(); await _redb.SyncSchemeAsync(); await _redb.SyncSchemeAsync(); await _redb.InitializeTypeRegistryAsync(); await PurgeClaimSchemesAsync(); _resolver = new ClaimMappersResolver(_redb); _ctx = new RouteContext(_sp, "claim-mappers-integration-test"); _ctx.AddRoutes(new IdentityCoreRouteBuilder( _sp, Options.Create(idOpts), Options.Create(new IdentityAuditOptions { Enabled = false }))); await _ctx.Start(); } public async Task DisposeAsync() { // Purge before tearing down so a Required global mapper (e.g. "must-have") // created by the last test in this class does not survive into other // collections that share the same physical DB and call EnrichPrincipal. if (_redb != null) await PurgeClaimSchemesAsync(); if (_ctx != null) await _ctx.Stop(); if (_sp != null) await _sp.DisposeAsync(); } // Provider-agnostic purge: delete every claim-mapper / claim-scope object via // the redb service so it hits whatever provider REDB_PROVIDER selected. The // previous raw-Npgsql version always cleaned Postgres, so under an MSSQL run it // silently no-oped — leaked Required global mappers then poisoned EnrichPrincipal // for the whole suite ("Required claim mapper ... resolved to empty value"). private async Task PurgeClaimSchemesAsync() { await PurgeSchemeAsync(); await PurgeSchemeAsync(); await PurgeSchemeAsync(); } private async Task PurgeSchemeAsync() where T : class, new() { try { var objs = await _redb.Query().ToListAsync(); if (objs.Count > 0) await _redb.DeleteAsync(objs.Select(o => o.Id)); } catch { /* scheme not yet materialised — nothing to purge */ } } // ── helpers ── private async Task CreateUser(string subject, string givenName, Dictionary? customClaims = null) { // Synthetic userId — in production set by UserManagementProcessor (oidcObj.key = coreUser.Id). // For these tests we just need a stable Key the resolver can query against. var userId = DateTimeOffset.UtcNow.Ticks + Random.Shared.Next(1000, 9999); var user = new RedbObject(new UserProps { GivenName = givenName, EmailVerified = true, CustomClaims = customClaims, }); user.Name = subject; user.key = userId; await _redb.SaveAsync(user); return userId; } private async Task CreateApp(string clientId) { var app = new RedbObject(new ApplicationProps { ClientId = clientId, ClientType = "confidential", }); app.Name = clientId; app.value_string = clientId; await _redb.SaveAsync(app); return app.Id; } private async Task CreateMapper( long? parentId, string claimType, string sourceKind, string? sourcePath = null, string? constantValue = null, string[]? requiredScopes = null, bool required = false, int order = 0, string[]? destinations = null) { var m = new RedbObject(new ClaimMapperProps { ClaimType = claimType, SourceKind = sourceKind, SourcePath = sourcePath, ConstantValue = constantValue, RequiredScopes = requiredScopes, Required = required, Order = order, Enabled = true, Destinations = destinations, }); m.Name = $"{sourceKind}->{claimType}"; if (parentId.HasValue) m.ParentId = parentId.Value; await _redb.SaveAsync(m); return m.Id; } private static ClaimsPrincipal MakePrincipal(string subject) { var identity = new ClaimsIdentity(authenticationType: "Test"); identity.AddClaim(new Claim(Claims.Subject, subject)); return new ClaimsPrincipal(identity); } // ── tests ── [Fact] public async Task GlobalMapper_Constant_AddsClaimToBothDestinations() { var userId = await CreateUser("u-global-" + Guid.NewGuid().ToString("N")[..6], "global@test.local"); await CreateMapper(parentId: null, "tenant", "Constant", constantValue: "acme"); var principal = MakePrincipal(userId.ToString()); await _resolver.EnrichPrincipalAsync(principal, userId, applicationId: null, requestedScopes: ["openid"], CancellationToken.None); var claim = principal.FindFirst("tenant"); claim.Should().NotBeNull(); claim!.Value.Should().Be("acme"); claim.GetDestinations().Should().Contain(Destinations.AccessToken) .And.Contain(Destinations.IdentityToken); } [Fact] public async Task GlobalMapper_UserPropsPath_ExtractsGivenName() { var subject = "u-given-" + Guid.NewGuid().ToString("N")[..6]; var userId = await CreateUser(subject, "Alice"); await CreateMapper(parentId: null, Claims.GivenName, "UserProps", sourcePath: "GivenName"); var principal = MakePrincipal(userId.ToString()); await _resolver.EnrichPrincipalAsync(principal, userId, applicationId: null, requestedScopes: ["openid", "profile"], CancellationToken.None); principal.FindFirst(Claims.GivenName)!.Value.Should().Be("Alice"); } [Fact] public async Task CustomClaim_Source_ResolvedFromUserPropsBag() { var subject = "u-custom-" + Guid.NewGuid().ToString("N")[..6]; var userId = await CreateUser(subject, "u@test.local", customClaims: new Dictionary { ["department"] = "engineering" }); await CreateMapper(parentId: null, "department", "CustomClaim", sourcePath: "department"); var principal = MakePrincipal(userId.ToString()); await _resolver.EnrichPrincipalAsync(principal, userId, applicationId: null, requestedScopes: [], CancellationToken.None); principal.FindFirst("department")!.Value.Should().Be("engineering"); } [Fact] public async Task AppOverlay_OverridesGlobalForSameClaimType() { var userId = await CreateUser("u-ovr-" + Guid.NewGuid().ToString("N")[..6], "ovr@test.local"); var appId = await CreateApp("client-" + Guid.NewGuid().ToString("N")[..6]); await CreateMapper(parentId: null, "tier", "Constant", constantValue: "free"); // global await CreateMapper(parentId: appId, "tier", "Constant", constantValue: "enterprise"); // overlay var principal = MakePrincipal(userId.ToString()); await _resolver.EnrichPrincipalAsync(principal, userId, applicationId: appId, requestedScopes: [], CancellationToken.None); principal.FindFirst("tier")!.Value.Should().Be("enterprise"); } [Fact] public async Task ScopeFiltering_OnlyEmittedWhenRequiredScopePresent() { var userId = await CreateUser("u-scope-" + Guid.NewGuid().ToString("N")[..6], "scope@test.local", customClaims: new Dictionary { ["roles"] = "admin,user" }); await CreateMapper(parentId: null, "roles", "CustomClaim", sourcePath: "roles", requiredScopes: ["roles"]); // Without "roles" scope: must NOT be emitted var p1 = MakePrincipal(userId.ToString()); await _resolver.EnrichPrincipalAsync(p1, userId, applicationId: null, requestedScopes: ["openid"], CancellationToken.None); p1.FindFirst("roles").Should().BeNull(); // With "roles" scope: emitted var p2 = MakePrincipal(userId.ToString()); await _resolver.EnrichPrincipalAsync(p2, userId, applicationId: null, requestedScopes: ["openid", "roles"], CancellationToken.None); p2.FindFirst("roles")!.Value.Should().Be("admin,user"); } [Fact] public async Task AssignedClientScope_EmitsItsMappers() { var userId = await CreateUser("u-csa-" + Guid.NewGuid().ToString("N")[..6], "csa@test.local"); var appId = await CreateApp("client-csa-" + Guid.NewGuid().ToString("N")[..6]); // Create a Client Scope object var scope = new RedbObject(new ClaimScopeProps { ScopeName = "tenant-info", Enabled = true, }); scope.Name = "tenant-info"; scope.value_string = "tenant-info"; await _redb.SaveAsync(scope); // Mapper under the scope await CreateMapper(parentId: scope.Id, "scope_marker", "Constant", constantValue: "from-client-scope"); // Without assignment — must NOT appear var p1 = MakePrincipal(userId.ToString()); await _resolver.EnrichPrincipalAsync(p1, userId, applicationId: appId, requestedScopes: [], CancellationToken.None); p1.FindFirst("scope_marker").Should().BeNull(); // Assign and re-resolve var assignment = new RedbObject(new ClaimScopeAssignmentProps { ApplicationId = appId, ScopeId = scope.Id, AssignedAt = DateTimeOffset.UtcNow, }); assignment.Name = $"{appId}::{scope.Id}"; assignment.key = appId; await _redb.SaveAsync(assignment); var p2 = MakePrincipal(userId.ToString()); await _resolver.EnrichPrincipalAsync(p2, userId, applicationId: appId, requestedScopes: [], CancellationToken.None); p2.FindFirst("scope_marker")!.Value.Should().Be("from-client-scope"); } [Fact] public async Task RequiredMapper_WithEmptyValue_Throws() { var userId = await CreateUser("u-req-" + Guid.NewGuid().ToString("N")[..6], "req@test.local"); // No "missing-claim" key in CustomClaims → resolves to null await CreateMapper(parentId: null, "must-have", "CustomClaim", sourcePath: "missing-claim", required: true); var principal = MakePrincipal(userId.ToString()); var act = async () => await _resolver.EnrichPrincipalAsync(principal, userId, applicationId: null, requestedScopes: [], CancellationToken.None); await act.Should().ThrowAsync() .WithMessage("*must-have*"); } [Fact] public async Task DisabledScope_IsIgnored() { var userId = await CreateUser("u-dis-" + Guid.NewGuid().ToString("N")[..6], "dis@test.local"); var appId = await CreateApp("client-dis-" + Guid.NewGuid().ToString("N")[..6]); var scope = new RedbObject(new ClaimScopeProps { ScopeName = "disabled-scope", Enabled = false, }); scope.Name = "disabled-scope"; scope.value_string = "disabled-scope"; await _redb.SaveAsync(scope); await CreateMapper(parentId: scope.Id, "ignored", "Constant", constantValue: "should-not-appear"); var assignment = new RedbObject(new ClaimScopeAssignmentProps { ApplicationId = appId, ScopeId = scope.Id, AssignedAt = DateTimeOffset.UtcNow, }); assignment.Name = $"{appId}::{scope.Id}"; assignment.key = appId; await _redb.SaveAsync(assignment); var principal = MakePrincipal(userId.ToString()); await _resolver.EnrichPrincipalAsync(principal, userId, applicationId: appId, requestedScopes: [], CancellationToken.None); principal.FindFirst("ignored").Should().BeNull(); } // ── processor / route smoke tests ── [Fact] public async Task ClaimMapperProcessor_CreateReadList_RoundTrip() { var endpoint = _ctx.GetEndpoint(IdentityEndpoints.ManageClaimMappers); var createReq = new CreateClaimMapperRequest { ClaimType = "smoke-claim", SourceKind = "Constant", ConstantValue = "smoke-value", Owner = "global", }; var createMsg = new Message { Body = createReq }; createMsg.Headers["operation"] = "create"; var ex = new Exchange(createMsg) { Pattern = ExchangePattern.InOut }; ManagementCallerContext.Apply(ex, ManagementCaller.Admin); await endpoint.CreateProducer().Process(ex); ex.Exception.Should().BeNull(); // Camel canon: read response from Out ?? In. The route is // [tx, idempPre, business, idempCapture, WireTap]; PipelineProcessor merges Out into // In on every intermediate step, so the final WireTap leaves the response on In. var resp = (ex.Out ?? ex.In).Body as ClaimMapperResponse; resp.Should().NotBeNull(); resp!.ClaimType.Should().Be("smoke-claim"); resp.Owner.Should().Be("global"); // List var listMsg = new Message { Body = new ListRequest { Count = 50 } }; listMsg.Headers["operation"] = "list"; var lex = new Exchange(listMsg) { Pattern = ExchangePattern.InOut }; ManagementCallerContext.Apply(lex, ManagementCaller.Admin); await endpoint.CreateProducer().Process(lex); lex.Exception.Should().BeNull(); var page = (lex.Out ?? lex.In).Body as PagedResult; page.Should().NotBeNull(); page!.Items.Should().Contain(i => i.Id == resp.Id); } [Fact(Skip = "PG hang on _sp.DisposeAsync(): NpgsqlOperationInProgressException for an in-flight " + "pvt_cte SELECT that the test's processor chain spawned but never awaited (most likely a fire-" + "and-forget WireTap audit task or an inner async not awaited inside ClaimScopeProcessor). The 3-minute " + "test-host inactivity timer fires; the rest of the suite never runs. Skipped to keep the run completable; " + "the bug is in the test code (or the processor's async hygiene), NOT in the Postgres provider — " + "a `MapRow` loud-throw attempt (commit 30f9172b, reverted in 21e945d7) demonstrated the same hang for the same root cause. " + "Re-enable by tracking the leaking pvt_cte through ClaimScopeProcessor / IdempotencyProcessor / WireTap chain.")] public async Task ClaimScopeProcessor_AssignUnassignIdempotent() { var appId = await CreateApp("client-route-" + Guid.NewGuid().ToString("N")[..6]); var endpoint = _ctx.GetEndpoint(IdentityEndpoints.ManageClaimScopes); // create scope via processor var c = new Message { Body = new CreateClaimScopeRequest { Name = "route-scope-" + Guid.NewGuid().ToString("N")[..6], Enabled = true } }; c.Headers["operation"] = "create"; var cex = new Exchange(c) { Pattern = ExchangePattern.InOut }; ManagementCallerContext.Apply(cex, ManagementCaller.Admin); await endpoint.CreateProducer().Process(cex); cex.Exception.Should().BeNull(); var scope = (cex.Out ?? cex.In).Body as ClaimScopeResponse; scope.Should().NotBeNull(); // assign twice — second must return existing (no duplicate row) async Task Assign() { var m = new Message { Body = new AssignClaimScopeRequest { ApplicationId = appId.ToString(), ScopeId = scope!.Id } }; m.Headers["operation"] = "assign"; var e = new Exchange(m) { Pattern = ExchangePattern.InOut }; ManagementCallerContext.Apply(e, ManagementCaller.Admin); await endpoint.CreateProducer().Process(e); e.Exception.Should().BeNull(); return (e.Out ?? e.In).Body as ClaimScopeAssignmentResponse; } var a1 = await Assign(); var a2 = await Assign(); a1.Should().NotBeNull(); a2.Should().NotBeNull(); a2!.Id.Should().Be(a1!.Id); // unassign var u = new Message { Body = new Dictionary { ["applicationId"] = appId, ["scopeId"] = long.Parse(scope!.Id), } }; u.Headers["operation"] = "unassign"; var uex = new Exchange(u) { Pattern = ExchangePattern.InOut }; ManagementCallerContext.Apply(uex, ManagementCaller.Admin); await endpoint.CreateProducer().Process(uex); uex.Exception.Should().BeNull(); } } Path: redb-identity/tests/redb.Identity.Tests/Cleanup/IdempotencyRecordCleanupTests.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/Cleanup/IdempotencyRecordCleanupTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Common; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Cleanup; /// /// The cleanup of expired idempotency records against the database of the fixture (SQLite, PostgreSQL or SQL Server /// by REDB_PROVIDER): records past their time to live go, live ones stay, a run goes batch after batch, a dry run /// counts and removes nothing, and a record stored the old way with a secret in its body goes once it expires. /// [Collection("ProductionHttp")] public class IdempotencyRecordCleanupTests { private readonly ProductionHttpFixture _fx; public IdempotencyRecordCleanupTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Expired_records_go_batch_after_batch_and_live_ones_stay() { var tag = Guid.NewGuid().ToString("N")[..10]; var expired = Enumerable.Range(0, 5).Select(i => $"{tag}-expired-{i}").ToList(); var live = Enumerable.Range(0, 2).Select(i => $"{tag}-live-{i}").ToList(); foreach (var key in expired) await StoreAsync(key, TimeSpan.FromMinutes(-5), """{"success":true}"""); foreach (var key in live) await StoreAsync(key, TimeSpan.FromHours(1), """{"success":true}"""); var result = await RunAsync(batchSize: 2, dryRun: false); result.Should().BeOfType().Subject.PrunedIdempotencyRecords .Should().BeGreaterThanOrEqualTo(5, "five expired records of this test, in three batches of two"); (await KeysLeftAsync(tag)).Should().BeEquivalentTo(live); } [Fact] public async Task A_dry_run_counts_the_expired_records_and_removes_nothing() { var tag = Guid.NewGuid().ToString("N")[..10]; await StoreAsync($"{tag}-expired-0", TimeSpan.FromMinutes(-5), """{"success":true}"""); await StoreAsync($"{tag}-expired-1", TimeSpan.FromMinutes(-5), """{"success":true}"""); var preview = (await RunAsync(batchSize: 500, dryRun: true)).Should().BeOfType().Subject; preview.DryRun.Should().BeTrue(); preview.WouldPruneIdempotencyRecords.Should().BeGreaterThanOrEqualTo(2); (await KeysLeftAsync(tag)).Should().HaveCount(2, "a dry run changes nothing"); await RunAsync(batchSize: 500, dryRun: false); } [Fact] public async Task A_record_stored_the_old_way_with_a_secret_goes_once_it_expires() { var tag = Guid.NewGuid().ToString("N")[..10]; var key = $"{tag}-old"; await StoreAsync(key, TimeSpan.FromMinutes(1), """{"id":1,"hmacSecret":"old-way-secret"}"""); await RunAsync(batchSize: 500, dryRun: false); (await KeysLeftAsync(tag)).Should().ContainSingle("the record is still inside its time to live"); await ExpireAsync(key); await RunAsync(batchSize: 500, dryRun: false); (await KeysLeftAsync(tag)).Should().BeEmpty("once expired, the record and the secret in it are gone"); } private Task StoreAsync(string key, TimeSpan ttl, string body) => _fx.UseRedbAsync(async redb => { var name = $"idem:cleanup-test:create:anon:{key}"; await redb.SaveAsync(new RedbObject { name = name, ValueUnique = IdempotencyKeyHash.Sha256Hex(name), date_complete = DateTimeOffset.UtcNow.Add(ttl), Props = new IdempotencyRecordProps { Scope = "cleanup-test", Operation = "create", CallerSubject = "anon", IdempotencyKey = key, StatusCode = 200, ResponseBody = body, }, }); }); private Task ExpireAsync(string key) => _fx.UseRedbAsync(async redb => { var record = (await redb.Query().Where(r => r.IdempotencyKey == key).ToListAsync()).Single(); record.date_complete = DateTimeOffset.UtcNow.AddMinutes(-1); await redb.SaveAsync(record); }); private Task> KeysLeftAsync(string tag) => _fx.UseRedbAsync(async redb => (await redb.Query().Where(r => r.Scope == "cleanup-test").ToListAsync()) .Select(r => r.Props.IdempotencyKey!) .Where(k => k.StartsWith(tag, StringComparison.Ordinal)) .ToList()); private Task RunAsync(int batchSize, bool dryRun) => _fx.UseRedbAsync(async redb => { var processor = new IdempotencyRecordCleanupProcessor( MockRouteContext.Create(redb), Options.Create(new RedbIdentityOptions { IdempotencyCleanupBatchSize = batchSize })); var exchange = new TestExchange(); if (dryRun) exchange.In.Body = new Dictionary { ["dryRun"] = true }; await processor.Process(exchange); return exchange.Out!.Body; }); } Path: redb-identity/tests/redb.Identity.Tests/Cleanup/SessionCleanupTests.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/Cleanup/SessionCleanupTests.cs ---- using redb.Identity.Contracts.Sessions; using AwesomeAssertions; using Microsoft.Extensions.Options; using NSubstitute; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Services; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Cleanup; public class SessionCleanupTests { private readonly IRedbService _redb = Substitute.For(); private readonly IBackgroundDeletionService _bgDeletion = Substitute.For(); private readonly IRedbSecurityContext _secCtx = Substitute.For(); public SessionCleanupTests() { var systemUser = new RedbUser { Id = 0, Login = "sys", Name = "System" }; _secCtx.GetEffectiveUser().Returns(systemUser); _redb.SecurityContext.Returns(_secCtx); _bgDeletion.DeleteAsync(Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(ci => new DeletionMark(999, ci.Arg>().Count())); } private static RedbObject CreateSession(long id, string status, int daysOld) { var session = MockRedbQuery.CreateObject(id, $"session-{id}", new SessionProps { Status = status }); session.DateCreate = DateTimeOffset.UtcNow.AddDays(-daysOld); return session; } private SessionCleanupProcessor CreateProcessor(IBackgroundDeletionService? bgDeletion) { var options = Options.Create(new RedbIdentityOptions { SessionRetentionDays = 30 }); var context = MockRouteContext.Create(_redb); return new SessionCleanupProcessor(context, options, backgroundDeletion: bgDeletion); } [Fact] public async Task Prune_MarksThroughTheCallerService_NotTheBackgroundConnection() { var sessions = new List> { CreateSession(1, "revoked", daysOld: 60), CreateSession(2, "revoked", daysOld: 31), CreateSession(3, "active", daysOld: 60) // active → not pruned }; MockRedbQuery.Setup(_redb, sessions); var processor = CreateProcessor(_bgDeletion); var exchange = new TestExchange(); await processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.PrunedSessions.Should().Be(2); exchange.Properties["identity-event-type"].Should().Be("SessionsPruned"); // The mark is written by the CALLER's service so it joins whatever transaction the // caller is in. IBackgroundDeletionService.DeleteAsync would mark on a second // connection of its own — which deadlocks against a route transaction on SQLite and // commits outside it on PostgreSQL / MSSQL. The service still purges: it finds the // trash container by polling, nothing is handed to it. await _redb.Received(1).SoftDeleteAsync( Arg.Is>(ids => ids.Count() == 2 && ids.Contains(1L) && ids.Contains(2L)), Arg.Any(), Arg.Any(), Arg.Any()); await _bgDeletion.DidNotReceive().DeleteAsync( Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()); await _redb.DidNotReceive().DeleteAsync(Arg.Any>()); } [Fact] public async Task Prune_WithoutBackgroundDeletion_StillMarks_ButNothingWillPurge() { var sessions = new List> { CreateSession(10, "revoked", daysOld: 60), CreateSession(11, "revoked", daysOld: 45) }; MockRedbQuery.Setup(_redb, sessions); _redb.SoftDeleteAsync(Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(new DeletionMark(0, 2)); var processor = CreateProcessor(bgDeletion: null); var exchange = new TestExchange(); await processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.PrunedSessions.Should().Be(2); await _redb.Received(1).SoftDeleteAsync( Arg.Is>(ids => ids.Count() == 2 && ids.Contains(10L) && ids.Contains(11L)), Arg.Any(), Arg.Any(), Arg.Any()); await _redb.DidNotReceive().DeleteAsync(Arg.Any>()); await _bgDeletion.DidNotReceive().DeleteAsync( Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] public async Task Prune_SkipsSessionsWithinRetention() { var sessions = new List> { CreateSession(1, "revoked", daysOld: 10), // within 30 days CreateSession(2, "revoked", daysOld: 5) }; MockRedbQuery.Setup(_redb, sessions); var processor = CreateProcessor(_bgDeletion); var exchange = new TestExchange(); await processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.PrunedSessions.Should().Be(0); // Assert on the path that actually marks. The background service is no longer called // at all, so an assertion only on it would hold even if a session HAD been deleted. await _redb.DidNotReceive().SoftDeleteAsync( Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] public async Task Prune_EmptyDB_ReturnsZero() { MockRedbQuery.Setup(_redb, new List>()); var processor = CreateProcessor(_bgDeletion); var exchange = new TestExchange(); await processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.PrunedSessions.Should().Be(0); } } Path: redb-identity/tests/redb.Identity.Tests/Cleanup/TokenCleanupTests.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/Cleanup/TokenCleanupTests.cs ---- using redb.Identity.Contracts.Tokens; using AwesomeAssertions; using Microsoft.Extensions.Options; using NSubstitute; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Services; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; using static OpenIddict.Abstractions.OpenIddictConstants; namespace redb.Identity.Tests.Cleanup; public class TokenCleanupTests { private readonly IRedbService _redb = Substitute.For(); private readonly IBackgroundDeletionService _bgDeletion = Substitute.For(); private readonly IRedbSecurityContext _secCtx = Substitute.For(); private readonly TokenCleanupProcessor _processor; public TokenCleanupTests() { var options = Options.Create(new RedbIdentityOptions { TokenRetentionDays = 30 }); var systemUser = new RedbUser { Id = 0, Login = "sys", Name = "System" }; _secCtx.GetEffectiveUser().Returns(systemUser); _redb.SecurityContext.Returns(_secCtx); _bgDeletion.DeleteAsync(Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()) .Returns(ci => new DeletionMark(999, ci.Arg>().Count())); var context = MockRouteContext.Create(_redb); _processor = new TokenCleanupProcessor(context, options, backgroundDeletion: _bgDeletion); } private static RedbObject CreateToken(long id, string status, int daysOld, DateTimeOffset? dateComplete = null) { var token = MockRedbQuery.CreateObject(id, $"token-{id}", new TokenProps { Status = status, Type = "access_token" }); token.DateCreate = DateTimeOffset.UtcNow.AddDays(-daysOld); if (dateComplete.HasValue) token.DateComplete = dateComplete; return token; } [Fact] public async Task Prune_DeletesRevokedTokensOlderThanRetention() { var tokens = new List> { CreateToken(1, Statuses.Revoked, daysOld: 60), CreateToken(2, Statuses.Revoked, daysOld: 31), CreateToken(3, Statuses.Valid, daysOld: 60) // valid → not pruned by step 1 }; MockRedbQuery.Setup(_redb, tokens); MockRedbQuery.Setup(_redb, new List>()); var exchange = new TestExchange(); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.PrunedTokens.Should().Be(2); exchange.Properties["identity-event-type"].Should().Be("TokensPruned"); // Marked through the CALLER's service so the mark joins the caller's transaction. // IBackgroundDeletionService.DeleteAsync would mark on a second connection of its // own; it is left to purge, which it does by polling for the trash container. await _redb.Received(1).SoftDeleteAsync( Arg.Is>(ids => ids.Count() == 2), Arg.Any(), Arg.Any(), Arg.Any()); await _bgDeletion.DidNotReceive().DeleteAsync( Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] public async Task Prune_SkipsTokensWithinRetention() { var tokens = new List> { CreateToken(1, Statuses.Revoked, daysOld: 10), // within 30 days CreateToken(2, Statuses.Revoked, daysOld: 5) // within 30 days }; MockRedbQuery.Setup(_redb, tokens); MockRedbQuery.Setup(_redb, new List>()); var exchange = new TestExchange(); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.PrunedTokens.Should().Be(0); // Assert on the path that actually marks. The background service is no longer called // at all, so an assertion only on it would hold even if a token HAD been deleted. await _redb.DidNotReceive().SoftDeleteAsync( Arg.Any>(), Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] public async Task Prune_DeletesExpiredValidTokens() { var expired = DateTimeOffset.UtcNow.AddDays(-1); // expired yesterday var tokens = new List> { CreateToken(1, Statuses.Valid, daysOld: 60, dateComplete: expired) }; MockRedbQuery.Setup(_redb, tokens); MockRedbQuery.Setup(_redb, new List>()); var exchange = new TestExchange(); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.PrunedTokens.Should().Be(1); } [Fact] public async Task Prune_EmptyDB_ReturnsZero() { MockRedbQuery.Setup(_redb, new List>()); MockRedbQuery.Setup(_redb, new List>()); var exchange = new TestExchange(); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.PrunedTokens.Should().Be(0); body.PrunedAuthorizations.Should().Be(0); } [Fact] public async Task Prune_PrunesOrphanedAuthorizations() { MockRedbQuery.Setup(_redb, new List>()); var auths = new List> { MockRedbQuery.CreateObject(100, "auth-1", new AuthorizationProps { Status = Statuses.Revoked }) }; auths[0].DateCreate = DateTimeOffset.UtcNow.AddDays(-60); MockRedbQuery.Setup(_redb, auths); // No tokens reference this authorization → orphaned var exchange = new TestExchange(); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.PrunedAuthorizations.Should().Be(1); await _redb.Received().SoftDeleteAsync( Arg.Is>(ids => ids.Contains(100L)), Arg.Any(), Arg.Any(), Arg.Any()); } [Fact] public async Task Prune_KeepsAuthorizationsWithTokens() { // Token referencing authorization 100 var tokens = new List> { CreateToken(1, Statuses.Valid, daysOld: 5) }; tokens[0].Props.AuthorizationObjectId = 100; MockRedbQuery.Setup(_redb, tokens); var auths = new List> { MockRedbQuery.CreateObject(100, "auth-1", new AuthorizationProps { Status = Statuses.Revoked }) }; auths[0].DateCreate = DateTimeOffset.UtcNow.AddDays(-60); MockRedbQuery.Setup(_redb, auths); var exchange = new TestExchange(); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.PrunedAuthorizations.Should().Be(0); } } Path: redb-identity/tests/redb.Identity.Tests/Cluster/ClusteredRouteMarkingTests.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/Cluster/ClusteredRouteMarkingTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NSubstitute; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Definitions; using Xunit; using static OpenIddict.Server.OpenIddictServerEvents; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Cluster; /// /// G13 / A5 — clustered cleanup route marking. /// /// Verifies that identity-token-cleanup and identity-session-cleanup timer /// routes carry the Cluster(true) flag on their , /// which is the mechanism that makes them leader-only in a clustered deployment. /// In standalone mode the flag is silently ignored by the router, so the registration /// itself is the only production-observable contract we can exercise here. /// /// /// Multi-host leader/failover behaviour is asserted in the redb.Route cluster /// test suite; here we only lock down the marking so that a refactor which accidentally /// drops .Cluster(true) from a cleanup route is caught immediately. /// /// public sealed class ClusteredRouteMarkingTests { private readonly IdentityCoreRouteBuilder _builder; public ClusteredRouteMarkingTests() { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); services.AddSingleton(Options.Create(new RedbIdentityOptions())); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddOpenIddict() .AddServer(options => { options.EnableDegradedMode(); options.SetIssuer(new Uri("https://identity.test.local/")); options.SetTokenEndpointUris("/connect/token"); options.AllowClientCredentialsFlow(); options.AddEphemeralEncryptionKey(); options.AddEphemeralSigningKey(); options.DisableAccessTokenEncryption(); options.UseRedbRoute(); options.AddEventHandler(builder => builder.UseInlineHandler(_ => default) .SetOrder(int.MaxValue - 100_000).Build()); }); var sp = services.BuildServiceProvider(); _builder = new IdentityCoreRouteBuilder(sp, sp.GetRequiredService>()); ((IRouteBuilder)_builder).Configure(null!); } [Theory] [InlineData("identity-token-cleanup")] [InlineData("identity-session-cleanup")] [InlineData("identity-mfa-otp-cleanup")] [InlineData("identity-revoked-sids-cleanup")] // The webhook delivery timer: leader-only too; its rows are also leased, see WebhookDeliveryWorker. [InlineData("identity-webhook-delivery")] [InlineData("identity-delivery-cleanup")] [InlineData("identity-idempotency-cleanup")] public void CleanupRoute_IsMarkedClustered(string routeId) { var route = _builder.Definitions.FirstOrDefault(d => d.GetRouteId() == routeId); route.Should().NotBeNull( "cleanup route '{0}' must be registered unconditionally (cleanup intervals default to non-zero)", routeId); route!.GetCluster().Should().BeTrue( "cleanup route '{0}' must carry .Cluster(true) so that in a clustered deployment " + "only the leader runs it (A5); dropping this flag would cause every replica to " + "race on cleanup and risks duplicate soft-deletes / double work", routeId); } [Fact] public void NonCleanupRoutes_AreNotMarkedClustered() { // Protocol/business routes must NOT be cluster-gated — they have to run on // every replica to serve traffic. If somebody accidentally bolted Cluster(true) // onto e.g. a token-issuance route, the non-leader replicas would stop // answering /connect/token and the deployment would brown-out. var clusteredIds = _builder.Definitions .Where(d => d.GetCluster()) .Select(d => d.GetRouteId()) .ToList(); clusteredIds.Should().OnlyContain( id => id == "identity-token-cleanup" || id == "identity-session-cleanup" || id == "identity-mfa-otp-cleanup" || id == "identity-revoked-sids-cleanup" || id == "identity-webhook-delivery" || id == "identity-delivery-cleanup" || id == "identity-idempotency-cleanup", "only periodic background routes (cleanup, webhook delivery) may be marked Clustered; request-handling routes " + "must run on every replica. Offending routes: [{0}]", string.Join(", ", clusteredIds)); } } Path: redb-identity/tests/redb.Identity.Tests/Configuration/IdentityCodecProfilesTests.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/Configuration/IdentityCodecProfilesTests.cs ---- using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; using AwesomeAssertions; using redb.Identity.Core.Serialization; using Xunit; namespace redb.Identity.Tests.Configuration; /// /// Pin-tests for . These intentionally fail loudly /// if anyone "tunes" the profile constants — that would silently break SCIM / OAuth / /// OIDC wire-level compatibility with external clients. /// /// Rationale lives on each option's XML doc (RFC anchors). These tests are the automated /// guardrail; the XML doc is the explanation. /// /// public class IdentityCodecProfilesTests { [Fact] public void ScimOptions_MatchesRfc7643_AndRfc8259() { var opts = IdentityCodecProfiles.ScimOptions; // RFC 7643 §7: attribute names are specified verbatim by the schema opts.PropertyNamingPolicy.Should().BeNull( "SCIM attribute names are defined by RFC 7643 and must not be remapped by a naming policy"); // RFC 7644 §3.8: unset attributes are omitted opts.DefaultIgnoreCondition.Should().Be(JsonIgnoreCondition.WhenWritingNull); // RFC 8259 §8.1: UTF-8 wire format (no \uXXXX escaping of ASCII/Cyrillic/etc.) opts.Encoder.Should().BeSameAs(JavaScriptEncoder.UnsafeRelaxedJsonEscaping); opts.WriteIndented.Should().BeFalse("production responses must not add whitespace"); } [Fact] public void ProblemOptions_MatchesRfc9457() { var opts = IdentityCodecProfiles.ProblemOptions; // RFC 9457 §3.1: standard members are lowercase (type, title, status, detail, instance) opts.PropertyNamingPolicy.Should().Be(JsonNamingPolicy.CamelCase); opts.DefaultIgnoreCondition.Should().Be(JsonIgnoreCondition.WhenWritingNull); opts.Encoder.Should().BeSameAs(JavaScriptEncoder.UnsafeRelaxedJsonEscaping); } [Fact] public void OAuthOptions_MatchesRfc6749_AndRfc7591() { var opts = IdentityCodecProfiles.OAuthOptions; // RFC 6749 §5.1 / RFC 7591 §3.2: parameter names are snake_case per spec; // DTOs carry [JsonPropertyName] — a naming policy would double-transform them. opts.PropertyNamingPolicy.Should().BeNull(); opts.DefaultIgnoreCondition.Should().Be(JsonIgnoreCondition.WhenWritingNull); opts.Encoder.Should().BeSameAs(JavaScriptEncoder.UnsafeRelaxedJsonEscaping); } [Fact] public void AllProfiles_AreSealed_AndCannotBeMutatedAtRuntime() { // System.Text.Json freezes JsonSerializerOptions after first use; assert the seal // is in effect by attempting to mutate and expecting InvalidOperationException. Action mutateScim = () => IdentityCodecProfiles.ScimOptions.WriteIndented = true; Action mutateProblem = () => IdentityCodecProfiles.ProblemOptions.WriteIndented = true; Action mutateOAuth = () => IdentityCodecProfiles.OAuthOptions.WriteIndented = true; mutateScim.Should().Throw(); mutateProblem.Should().Throw(); mutateOAuth.Should().Throw(); } [Fact] public void ScimOptions_EmitsUnicodeLiterals_NotEscapeSequences() { // Regression guard for the \u0022 / \u0410 escape artefacts that prompted the // migration to locked profiles. UTF-8 wire per RFC 8259 §8.1. var json = JsonSerializer.Serialize(new { name = "Café \"world\"" }, IdentityCodecProfiles.ScimOptions); json.Should().Contain("Café"); json.Should().NotContain("\\u00e9"); // accented "e" — must stay a UTF-8 literal json.Should().NotContain("\\u0022"); // ASCII quote } } Path: redb-identity/tests/redb.Identity.Tests/Configuration/IdentityWebAuthnOptionsTests.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/Configuration/IdentityWebAuthnOptionsTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Configuration; using Xunit; namespace redb.Identity.Tests.Configuration; /// /// MFA-3 fail-fast unit tests for . The /// validator is invoked from RedbIdentityServiceExtensions.AddRedbIdentity when /// is true; the goal of these tests /// is to guarantee a misconfigured deployment never reaches the first-credential /// registration with broken settings (since changing RpId after credentials exist /// invalidates them all). /// public sealed class IdentityWebAuthnOptionsTests { private static IdentityWebAuthnOptions Valid() => new() { Enabled = true, RpId = "auth.example.com", Origins = { "https://auth.example.com" }, }; [Fact] public void Validate_PassesForMinimalValidConfig() { var act = () => Valid().Validate(); act.Should().NotThrow(); } [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public void Validate_ThrowsOnBlankRpId(string? rpId) { var o = Valid(); o.RpId = rpId; var act = () => o.Validate(); act.Should().Throw().WithMessage("*RpId is required*"); } [Theory] [InlineData("https://auth.example.com")] // includes scheme [InlineData("auth.example.com/path")] // includes path public void Validate_ThrowsOnRpIdWithSchemeOrPath(string rpId) { var o = Valid(); o.RpId = rpId; var act = () => o.Validate(); act.Should().Throw().WithMessage("*bare host name*"); } [Fact] public void Validate_ThrowsOnEmptyOrigins() { var o = Valid(); o.Origins.Clear(); var act = () => o.Validate(); act.Should().Throw().WithMessage("*Origins*at least one*"); } [Theory] [InlineData("auth.example.com")] // missing scheme [InlineData("ftp://auth.example.com")] // wrong scheme [InlineData("http://auth.example.com")] // http on non-localhost rejected public void Validate_ThrowsOnInvalidOrigin(string origin) { var o = Valid(); o.Origins.Clear(); o.Origins.Add(origin); var act = () => o.Validate(); act.Should().Throw().WithMessage("*absolute https*"); } [Fact] public void Validate_AcceptsHttpLocalhost() { var o = Valid(); o.Origins.Add("http://localhost:5000"); var act = () => o.Validate(); act.Should().NotThrow(); } [Fact] public void Validate_ThrowsOnNonPositiveTimeout() { var o = Valid(); o.TimeoutMs = 0; var act = () => o.Validate(); act.Should().Throw().WithMessage("*TimeoutMs*"); } [Fact] public void Validate_ThrowsOnChallengeTtlShorterThanTimeout() { var o = Valid(); o.TimeoutMs = 60_000; o.ChallengeTtlSeconds = 30; // < 60 var act = () => o.Validate(); act.Should().Throw().WithMessage("*ChallengeTtlSeconds*"); } [Theory] [InlineData("optional")] [InlineData("never")] [InlineData("REQUIRED")] public void Validate_ThrowsOnInvalidUserVerification(string uv) { var o = Valid(); o.UserVerification = uv; var act = () => o.Validate(); act.Should().Throw().WithMessage("*UserVerification*"); } [Fact] public void Validate_ThrowsOnInvalidAttestation() { var o = Valid(); o.Attestation = "magic"; var act = () => o.Validate(); act.Should().Throw().WithMessage("*Attestation*"); } [Fact] public void Validate_ThrowsOnInvalidAaguidGuid() { var o = Valid(); o.AaguidBlocklist = new List { "not-a-guid" }; var act = () => o.Validate(); act.Should().Throw().WithMessage("*AaguidBlocklist*not a valid GUID*"); } [Fact] public void Validate_AcceptsValidAaguidGuid() { var o = Valid(); o.AaguidBlocklist = new List { Guid.NewGuid().ToString() }; var act = () => o.Validate(); act.Should().NotThrow(); } } Path: redb-identity/tests/redb.Identity.Tests/Configuration/JwksHttpContractTests.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/Configuration/JwksHttpContractTests.cs ---- using System.Net; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Configuration; /// /// G12 — JWKS endpoint HTTP-surface guarantees. /// /// sets /// Cache-Control: public, max-age=3600 on every JWKS response. Relying parties /// MUST cache JWKS (OIDC Core §10.1.1) but too-long a TTL delays detection of a /// newly-rotated key. The 1-hour ceiling mirrors Microsoft / Google / Auth0 and sits /// inside the typical 24–72h overlap window. /// /// /// A regression that dropped the header would push RPs onto their own heuristics /// (some cache forever, some never cache) and either (a) miss key rotations or /// (b) hammer the JWKS endpoint on every token verify. /// /// [Collection("ProductionHttp")] public sealed class JwksHttpContractTests { private readonly ProductionHttpFixture _fx; public JwksHttpContractTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Jwks_EmitsCacheControlHeader() { var resp = await _fx.Http.GetAsync("/.well-known/jwks"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var cacheControl = resp.Headers.CacheControl?.ToString() ?? (resp.Content.Headers.TryGetValues("Cache-Control", out var v) ? string.Join(",", v) : null); cacheControl.Should().NotBeNullOrEmpty( "/.well-known/jwks MUST set Cache-Control. Without it RPs default to their own " + "heuristics — some cache forever (missing rotations), some never cache " + "(hammering the endpoint on every token verify)."); cacheControl!.ToLowerInvariant().Should().Contain("public"); cacheControl.ToLowerInvariant().Should().Contain("max-age=3600", "D2 pins JWKS max-age to 3600 — the RP-side refresh cadence. Tightening or " + "loosening without an RFC / spec reason is a silent protocol change."); } [Fact] public async Task Discovery_EmitsCacheControlHeader() { // Parallel guard for the discovery doc: D1/D2 sets max-age=300 (5 min) — small // enough to roll forward a config push, large enough to cut cold-start volume. var resp = await _fx.Http.GetAsync("/.well-known/openid-configuration"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var cacheControl = resp.Headers.CacheControl?.ToString() ?? (resp.Content.Headers.TryGetValues("Cache-Control", out var v) ? string.Join(",", v) : null); cacheControl.Should().NotBeNullOrEmpty(); cacheControl!.ToLowerInvariant().Should().Contain("max-age=300", "discovery doc is pinned at max-age=300 (D1/D2). Any deviation silently " + "changes RP cache behaviour."); } [Fact] public async Task Jwks_ResponseContainsKeysArray() { // Smoke: the endpoint returns a valid JWKS document (RFC 7517 §5: JSON object // with a "keys" array). Without this the Cache-Control is noise. var resp = await _fx.Http.GetAsync("/.well-known/jwks"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var body = await resp.Content.ReadAsStringAsync(); body.Should().Contain("\"keys\"", "RFC 7517 §5: JWKS document MUST have a top-level 'keys' array. A regression " + "that returned an empty object / error envelope here would silently break " + "every RP's token-verify path."); } } Path: redb-identity/tests/redb.Identity.Tests/Configuration/MultiReplicaBootstrapTests.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/Configuration/MultiReplicaBootstrapTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Postgres.Pro.Extensions; using Xunit;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Configuration; /// /// G12 / A6 — idempotent bootstrap of Identity against a shared PostgreSQL backend. /// /// In a clustered deployment several Identity replicas come up in parallel and all /// run the same schema-sync + unique-index creation path /// (, /// ). /// Any non-idempotent write in that path — CREATE TABLE without /// IF NOT EXISTS, CREATE UNIQUE INDEX without guards, a seed row /// inserted twice — would either crash the second replica or leave the DB in an /// inconsistent state. /// /// /// This test exercises exactly that contract by running two independent Identity /// service-provider bootstraps back-to-back against the same connection string and /// re-invoking InitializeAsync + SyncSchemeAsync on both. The second /// replica must succeed with no schema changes. /// /// public sealed class MultiReplicaBootstrapTests { [Fact] public async Task TwoSequentialReplicas_ShareSchema_Idempotent() { var cs = LoadConnectionString(); // Replica A — first to come up, creates schema + indexes. await using var spA = BuildReplicaSp(cs); var redbA = spA.GetRequiredService(); try { await redbA.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await redbA.InitializeAsync(); } await SyncIdentitySchemasAsync(redbA); // Replica B — second to come up against the same DB. MUST NOT throw and MUST // NOT partially re-create anything. This is the core A6 contract: in a // clustered deployment the second-to-start replica cannot be forced to crash // because the first already claimed the schema. await using var spB = BuildReplicaSp(cs); var redbB = spB.GetRequiredService(); var act = async () => { try { await redbB.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await redbB.InitializeAsync(); } await SyncIdentitySchemasAsync(redbB); }; await act.Should().NotThrowAsync( "A6: parallel / sequential replicas running the same Identity bootstrap MUST " + "be idempotent. A regression here crashes the second node of every two-node " + "cluster."); } [Fact] public async Task SameReplica_RerunInitialize_Idempotent() { // Single-replica restart guard: Identity runs the same init path on every // process start. A non-idempotent DDL / seed would fail after the first // deployment unless operators manually truncate the schema between releases. var cs = LoadConnectionString(); await using var sp = BuildReplicaSp(cs); var redb = sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await redb.InitializeAsync(); } await SyncIdentitySchemasAsync(redb); var act = async () => { try { await redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await redb.InitializeAsync(); } await SyncIdentitySchemasAsync(redb); }; await act.Should().NotThrowAsync( "A single replica's restart loop must be idempotent — every process start " + "re-runs InitializeAsync + SyncSchemeAsync. Non-idempotency here means every " + "redeploy is a schema breakage."); } private static string LoadConnectionString() => new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build() .GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); private static ServiceProvider BuildReplicaSp(string cs) { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddRedbIdentityServer(new RedbIdentityOptions { AllowEphemeralKeys = true, DisableAccessTokenEncryption = true, }); return services.BuildServiceProvider(); } private static async Task SyncIdentitySchemasAsync(IRedbService redb) { // Mirror the subset of schemas pinned by ProductionHttpFixture so the test // exercises every Identity scheme's sync path, not just the base redb tables. await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); } } Path: redb-identity/tests/redb.Identity.Tests/Configuration/SigningKeyInitListenerTests.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/Configuration/SigningKeyInitListenerTests.cs ---- using System.Collections.Immutable; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NSubstitute; using redb.Identity.Core.Configuration; using redb.Identity.Core.Keys; using redb.Identity.Core.Module; using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Configuration; /// /// What the props signing-key store is seeded with at context start. OpenIddict encrypts authorization /// codes, refresh tokens, device and user codes and its own state tokens whatever /// says (that option leaves only access /// tokens as plain JWS) and refuses to build its options without an encryption credential. A store seeded /// with a signing key and no encryption key is therefore a server that cannot start, so the listener seeds /// both kinds unconditionally. /// public sealed class SigningKeyInitListenerTests { [Fact] public async Task Seeds_the_encryption_key_even_when_access_token_encryption_is_disabled() { var store = Substitute.For(); store.GetAllAsync(Arg.Any()).Returns(ImmutableArray.Empty); var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Options.Create(new RedbIdentityOptions { UsePropsSigningKeyStore = true, DisableAccessTokenEncryption = true, })); services.AddSingleton(store); await using var sp = services.BuildServiceProvider(); await new SigningKeyInitListener(sp).OnContextStarting(Substitute.For(), CancellationToken.None); await store.Received(1).EnsureBootstrappedAsync("signing", Arg.Any()); await store.Received(1).EnsureBootstrappedAsync("encryption", Arg.Any()); } [Fact] public async Task Does_nothing_when_the_props_store_is_off() { var store = Substitute.For(); var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Options.Create(new RedbIdentityOptions { UsePropsSigningKeyStore = false })); services.AddSingleton(store); await using var sp = services.BuildServiceProvider(); await new SigningKeyInitListener(sp).OnContextStarting(Substitute.For(), CancellationToken.None); await store.DidNotReceive().EnsureBootstrappedAsync(Arg.Any(), Arg.Any()); } } Path: redb-identity/tests/redb.Identity.Tests/Configuration/SigningKeyPostConfigureTests.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/Configuration/SigningKeyPostConfigureTests.cs ---- using System.Collections.Immutable; using System.Security.Cryptography; using AwesomeAssertions; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using NSubstitute; using OpenIddict.Server; using redb.Identity.Core.Configuration; using redb.Identity.Core.Keys; using Xunit; namespace redb.Identity.Tests.Configuration; /// /// What the store-backed post-configure hands OpenIddict, tested on the component alone. /// /// The component built two pools: keys inside their window went into the credentials, and a broader /// "validation pool" of every persisted key past NotBefore — retired ones included — was written /// into TokenValidationParameters.IssuerSigningKeys, so that, the comments said, tokens signed by /// retired keys would keep validating "during the grace window". Retirement sets NotAfter to now, /// so that pool kept a retired key for as long as its row existed. In the shipped wiring the list never /// reached a token: OpenIddict's own post-configure runs after this one and rebuilds the validation keys /// from the credentials. That was luck of registration order, and this component is not allowed to rely on /// it: run in isolation, as here, it must produce lists a validator could trust directly. /// /// /// There is no validation pool of retired keys. A rotated key validates until its own NotAfter — /// that is the handover window; a retired key's NotAfter is the moment of retirement, and trust ends /// there. Whatever OpenIddict reads, the credentials and the validation parameters say the same thing. /// /// public sealed class SigningKeyPostConfigureTests { private static readonly DateTimeOffset Now = DateTimeOffset.UtcNow; private static SigningKeyMaterial Key(string kid, string kind, DateTimeOffset notBefore, DateTimeOffset notAfter, bool active) => new(kid, kind, kind == "signing" ? "RS256" : "RSA-OAEP", new RsaSecurityKey(RSA.Create(2048)), notBefore, notAfter, active); private static readonly SigningKeyMaterial Active = Key("k_active", "signing", Now.AddDays(-1), Now.AddDays(89), active: true); private static readonly SigningKeyMaterial Demoted = Key("k_demoted", "signing", Now.AddDays(-30), Now.AddDays(60), active: false); private static readonly SigningKeyMaterial Retired = Key("k_retired", "signing", Now.AddDays(-60), Now.AddMinutes(-1), active: false); private static readonly SigningKeyMaterial Encryption = Key("k_enc", "encryption", Now.AddDays(-1), Now.AddDays(89), active: true); private static readonly SigningKeyMaterial RetiredEncryption = Key("k_enc_retired", "encryption", Now.AddDays(-60), Now.AddMinutes(-1), active: false); /// The store as it really answers: the working set is the in-window subset of the full list. private static ISigningKeyStore Store() { var all = ImmutableArray.Create(Active, Demoted, Retired, Encryption, RetiredEncryption); var store = Substitute.For(); store.ListAllIncludingRetiredAsync(Arg.Any()).Returns(all); store.GetAllAsync(Arg.Any()).Returns(all.Where(k => k.NotAfter > Now).ToImmutableArray()); return store; } private static OpenIddictServerOptions Configure( ISigningKeyStore store, OpenIddictServerOptions? options = null, MintingKeySource? minting = null) { options ??= new OpenIddictServerOptions(); var sut = new PropsSigningKeyStoreOpenIddictPostConfigure( store, Options.Create(new RedbIdentityOptions { UsePropsSigningKeyStore = true, MintingKeySource = minting }), NullLogger.Instance); sut.PostConfigure(null, options); return options; } private static string Fingerprint(SecurityKey key) => Convert.ToHexString(((RsaSecurityKey)key).Rsa!.ExportParameters(false).Modulus!); [Fact] public void Keys_inside_their_window_are_credentials_active_first() { var options = Configure(Store()); // The active key must win OpenIddict's first-compatible-credential pick for minting; the demoted one // stays behind it so tokens it signed keep validating until its own NotAfter. options.SigningCredentials.Select(c => c.Key.KeyId).Should().Equal("k_active", "k_demoted"); options.EncryptionCredentials.Select(c => c.Key.KeyId).Should().Equal("k_enc"); } [Fact] public void A_retired_key_is_in_no_list_at_all() { var options = Configure(Store()); options.SigningCredentials.Select(c => Fingerprint(c.Key)).Should().NotContain(Fingerprint(Retired.SecurityKey)); options.TokenValidationParameters.IssuerSigningKeys.Select(Fingerprint).Should().NotContain(Fingerprint(Retired.SecurityKey), "retirement is the moment trust ends; a validation list that keeps the key defeats it, and whether " + "OpenIddict happens to overwrite this list is not this component's to lean on"); options.TokenValidationParameters.TokenDecryptionKeys.Select(Fingerprint).Should().NotContain(Fingerprint(RetiredEncryption.SecurityKey)); } [Fact] public void The_validation_parameters_say_exactly_what_the_credentials_say() { var options = Configure(Store()); options.TokenValidationParameters.IssuerSigningKeys.Select(Fingerprint) .Should().BeEquivalentTo(options.SigningCredentials.Select(c => Fingerprint(c.Key)), "one set of trusted keys, not two that can disagree"); options.TokenValidationParameters.TokenDecryptionKeys.Select(Fingerprint) .Should().BeEquivalentTo(options.EncryptionCredentials.Select(c => Fingerprint(c.Key))); } [Fact] public void A_credential_another_configurer_added_is_kept_and_trusted() { // The file's own rule: re-run on every options refresh, so be additive and never clear the lists. // Assigning the validation parameters from the store's keys alone broke that rule for everyone // else's credentials; they must stay in the credentials AND be trusted for validation. var hostKey = new RsaSecurityKey(RSA.Create(2048)) { KeyId = "k_host" }; var options = new OpenIddictServerOptions(); options.SigningCredentials.Add(new SigningCredentials(hostKey, SecurityAlgorithms.RsaSha256)); Configure(Store(), options); options.SigningCredentials.Select(c => c.Key.KeyId).Should().Contain("k_host"); options.TokenValidationParameters.IssuerSigningKeys.Select(Fingerprint).Should().Contain(Fingerprint(hostKey)); } // Who mints when the operator's own credentials and the store are both present is the operator's choice, // not the order two registrations happen to run in. OpenIddict mints with the first compatible entry, so // the choice is the position of the store's keys relative to the configured ones; both sets stay // trusted and published whichever comes first. [Fact] public void Configured_minting_source_keeps_the_operators_credential_first_and_the_store_behind_it() { var hostKey = new RsaSecurityKey(RSA.Create(2048)) { KeyId = "k_host" }; var hostEncryption = new RsaSecurityKey(RSA.Create(2048)) { KeyId = "k_host_enc" }; var options = new OpenIddictServerOptions(); options.SigningCredentials.Add(new SigningCredentials(hostKey, SecurityAlgorithms.RsaSha256)); options.EncryptionCredentials.Add(new EncryptingCredentials(hostEncryption, SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512)); Configure(Store(), options, MintingKeySource.Configured); options.SigningCredentials.Select(c => c.Key.KeyId).Should().Equal("k_host", "k_active", "k_demoted"); options.EncryptionCredentials.Select(c => c.Key.KeyId).Should().Equal("k_host_enc", "k_enc"); options.TokenValidationParameters.IssuerSigningKeys.Select(Fingerprint) .Should().BeEquivalentTo(options.SigningCredentials.Select(c => Fingerprint(c.Key)), "both sources validate"); } [Fact] public void Store_minting_source_puts_the_stores_active_key_first_and_the_operators_credential_behind_it() { var hostKey = new RsaSecurityKey(RSA.Create(2048)) { KeyId = "k_host" }; var options = new OpenIddictServerOptions(); options.SigningCredentials.Add(new SigningCredentials(hostKey, SecurityAlgorithms.RsaSha256)); Configure(Store(), options, MintingKeySource.Store); options.SigningCredentials.Select(c => c.Key.KeyId).Should().Equal("k_active", "k_demoted", "k_host"); options.TokenValidationParameters.IssuerSigningKeys.Select(Fingerprint).Should().Contain(Fingerprint(hostKey)); } } Path: redb-identity/tests/redb.Identity.Tests/Configuration/SigningKeysBootstrapTests.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/Configuration/SigningKeysBootstrapTests.cs ---- using System.Security.Cryptography; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using OpenIddict.Server; using redb.Core.Models.Configuration; using redb.Identity.Core; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Identity.Core.Configuration; using redb.Postgres.Pro.Extensions; using Xunit;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Configuration; /// /// G12 / A3 — production-mode signing-keys guard. /// /// Verifies the bootstrap-time contract enforced in /// RedbIdentityServiceExtensions.AddRedbIdentityServer: /// /// If no signing credentials are configured AND /// is false, /// building the OpenIddict server options MUST throw — ephemeral keys split /// the JWKS across cluster replicas and invalidate every live token on /// restart, which is unacceptable in production. /// The same configuration with AllowEphemeralKeys = true must succeed /// (Development / test scenarios opt in explicitly). /// Persistent always /// succeed irrespective of the flag. /// /// /// /// We resolve for /// because the OpenIddict configuration delegate /// (which contains the throw) runs lazily at first options resolution, not at DI /// container construction time. /// /// public sealed class SigningKeysBootstrapTests { [Fact] public void NoSigningCreds_AllowEphemeralFalse_ThrowsAtBootstrap() { // The signing-keys throw fires inside the OpenIddict server-options builder // delegate, which OpenIddict invokes synchronously inside AddServer(...) — so // the exception surfaces at AddRedbIdentityServer call time (eager), not at // first IOptions resolution. We therefore wrap BuildIdentitySp itself. var act = () => BuildIdentitySp(new RedbIdentityOptions { AllowEphemeralKeys = false, DisableAccessTokenEncryption = true, // skip the parallel encryption-keys throw // SigningCredentials intentionally empty }); act.Should().Throw() .WithMessage("*ephemeral*", "production-mode bootstrap with no persistent signing credentials must " + "fail loudly per A3 — silently falling back to ephemeral keys would " + "split JWKS across cluster replicas (different kid per node)."); } [Fact] public void NoSigningCreds_AllowEphemeralTrue_BootstrapSucceeds() { var sp = BuildIdentitySp(new RedbIdentityOptions { AllowEphemeralKeys = true, // explicit dev opt-in DisableAccessTokenEncryption = true, }); var act = () => sp.GetRequiredService>().CurrentValue; act.Should().NotThrow( "explicit AllowEphemeralKeys=true is the documented Development / test " + "opt-in and must succeed without persistent keys."); var opts = sp.GetRequiredService>().CurrentValue; opts.SigningCredentials.Should().NotBeEmpty( "ephemeral keys must still produce at least one signing credential so " + "the server can issue tokens in dev mode."); } [Fact] public void NoSigningCreds_EncryptionRequired_NoEphemeral_AlsoThrows() { // Symmetric guard: when access-token encryption is on AND no encryption creds // are configured AND ephemeral is disallowed, bootstrap must also fail rather // than silently degrading. Same eager-throw site as the signing variant. var act = () => BuildIdentitySp(new RedbIdentityOptions { AllowEphemeralKeys = false, DisableAccessTokenEncryption = false, // encryption required }); act.Should().Throw( "production-mode access-token encryption without persistent encryption " + "credentials must fail at bootstrap (A3 symmetric guard)."); } [Fact] public void EphemeralKeys_And_PropsStore_Together_AreRefused() { // Ephemeral keys stand in for keys that persist; the props store is the keys that persist. With both // flags the ephemeral key is registered first and stays in the credential lists beside the store's // keys: in this replica's JWKS only, trusted for validation, and the encryption key until the store // has one. That is the per-process failure the store exists to remove, so the pair is a contradiction // the registration must refuse rather than resolve by list order. var act = () => BuildIdentitySp(new RedbIdentityOptions { AllowEphemeralKeys = true, UsePropsSigningKeyStore = true, }); act.Should().Throw() .WithMessage("*AllowEphemeralKeys*UsePropsSigningKeyStore*"); } [Fact] public void NoEncryptionCreds_AccessTokenEncryptionDisabled_NoEphemeral_StillThrows() { // DisableAccessTokenEncryption leaves only access tokens as plain JWS. Authorization codes, refresh // tokens, device and user codes and OpenIddict's state tokens are encrypted whatever it says, and // OpenIddict refuses to build its options without an encryption credential. The registration has to // say so itself, with the operator's options in hand, not let the first options build fail inside // OpenIddict with a message about a setting the operator never saw. var act = () => BuildIdentitySp(new RedbIdentityOptions { AllowEphemeralKeys = false, DisableAccessTokenEncryption = true, SigningCredentials = { new SigningCredentials(new RsaSecurityKey(RSA.Create(2048)), SecurityAlgorithms.RsaSha256) }, // Keep the at-rest gate out of the way: its own message mentions RequireAtRestEncryption and // would satisfy a loose match for the wrong reason. DataProtection = new DataProtectionOptions { RequireAtRestEncryption = false }, }); act.Should().Throw() .WithMessage("*no encryption credentials*"); } // Configured credentials together with the props store are a migration state; both sources validate // and are published, and MintingKeySource says which one signs new tokens. Neither an unspoken choice // nor a choice with nothing to choose from is accepted. [Fact] public void ConfiguredCredentials_And_PropsStore_WithoutMintingKeySource_AreRefused() { var act = () => BuildIdentitySp(new RedbIdentityOptions { AllowEphemeralKeys = false, UsePropsSigningKeyStore = true, SigningCredentials = { new SigningCredentials(new RsaSecurityKey(RSA.Create(2048)), SecurityAlgorithms.RsaSha256) }, DataProtection = new DataProtectionOptions { RequireAtRestEncryption = false }, }); act.Should().Throw() .WithMessage("*MintingKeySource is not set*"); } [Fact] public void ConfiguredCredentials_And_PropsStore_WithMintingKeySource_AreAccepted() { var act = () => BuildIdentitySp(new RedbIdentityOptions { AllowEphemeralKeys = false, UsePropsSigningKeyStore = true, MintingKeySource = MintingKeySource.Configured, SigningCredentials = { new SigningCredentials(new RsaSecurityKey(RSA.Create(2048)), SecurityAlgorithms.RsaSha256) }, DataProtection = new DataProtectionOptions { RequireAtRestEncryption = false }, }); act.Should().NotThrow("with the choice made, the pair is a supported migration state"); } [Fact] public void MintingKeySource_WithASingleKeySource_IsRefused() { var act = () => BuildIdentitySp(new RedbIdentityOptions { AllowEphemeralKeys = true, MintingKeySource = MintingKeySource.Store, DisableAccessTokenEncryption = true, }); act.Should().Throw() .WithMessage("*only one key source*"); } private static ServiceProvider BuildIdentitySp(RedbIdentityOptions opts) { var services = new ServiceCollection(); services.AddLogging(); // Identity bootstrap requires a redb backend. Use Postgres but with a fake // CS — we never resolve IRedbService in these tests, only OpenIddict server // options, so no DB connection is opened. services.AddRedbForTests("Host=127.0.0.1;Port=1;Database=fake;Username=fake;Password=fake"); services.AddRedbIdentityServer(opts); return services.BuildServiceProvider(); } } Path: redb-identity/tests/redb.Identity.Tests/Consent/ConsentIntegrationTests.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/Consent/ConsentIntegrationTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Consent; /// /// Production integration tests for consent tracking through the full OpenIddict pipeline. /// Uses real PostgreSQL + real OpenIddict pipeline + direct-vm:// endpoints. /// [Collection("ProductionBootstrap")] public class ConsentIntegrationTests { private readonly ProductionBootstrapFixture _fx; public ConsentIntegrationTests(ProductionBootstrapFixture fx) => _fx = fx; [Fact] public async Task AuthCode_ExplicitConsent_RequiresConsentThenSucceeds() { // Switch test client to explicit consent. Direct DB reads/writes are wrapped in // _fx.WithRedb(...) because this test calls _fx.Request(...) which fires Worker-side // WireTap audit pipeline INSERTs — sharing _fx.Redb's root-scoped NpgsqlConnection // with that concurrent writer surfaces as // "A command is already in progress: INSERT INTO identity_audit_log". var app = await _fx.WithRedb(redb => redb.Query() .Where(p => p.ClientId == ProductionBootstrapFixture.TestClientId) .FirstOrDefaultAsync()); app.Should().NotBeNull(); app!.Props.ConsentType = "explicit"; await _fx.WithRedb(redb => redb.SaveAsync(app)); try { // First authorize — should get consent_required error (no existing consent) var firstResult = await AuthorizeAsync(ProductionBootstrapFixture.TestClientId, "openid profile", ProductionBootstrapFixture.TestClientSecret); firstResult.Should().BeNull("explicit consent without prior grant should not return a code"); // Grant consent via ConsentGrant endpoint var coreUser = await _fx.WithRedb(async redb => await redb.UserProvider.GetUserByLoginAsync(ProductionBootstrapFixture.TestUsername) ?? throw new Exception("Test user not found")); var grantBody = new Dictionary { ["userId"] = coreUser.Id, ["clientId"] = ProductionBootstrapFixture.TestClientId, ["scopes"] = "openid profile" }; var grantResult = await _fx.Request(IdentityEndpoints.ConsentGrant, grantBody); var grantResponse = grantResult.Should().BeOfType>().Subject; grantResponse.Should().ContainKey("success"); grantResponse["success"].Should().Be(true); // Retry authorize — should now succeed with consent recorded var code = await AuthorizeAsync(ProductionBootstrapFixture.TestClientId, "openid profile", ProductionBootstrapFixture.TestClientSecret); code.Should().NotBeNullOrEmpty("authorize should succeed after consent granted"); // Verify consent was recorded — own scope, owns its NpgsqlConnection for the query. var consent = await _fx.WithRedb(async redb => { var svc = new ConsentService(redb); return await svc.CheckAsync(coreUser.Id, app.id, ["openid", "profile"]); }); consent.Should().NotBeNull("explicit consent should have been recorded via ConsentGrant"); consent!.Props.Scopes.Should().Contain("openid"); consent.Props.Scopes.Should().Contain("profile"); } finally { // Restore to implicit consent app.Props.ConsentType = "implicit"; await _fx.WithRedb(redb => redb.SaveAsync(app)); } } [Fact] public async Task AuthCode_ImplicitConsent_NoConsentRecord() { // Direct DB reads via _fx.WithRedb to avoid sharing NpgsqlConnection with the // Worker's WireTap audit pipeline (see comment on AuthCode_ExplicitConsent_*). var app = await _fx.WithRedb(redb => redb.Query() .Where(p => p.ClientId == ProductionBootstrapFixture.TestClientIdPublic) .FirstOrDefaultAsync()); app.Should().NotBeNull(); app!.Props.ConsentType.Should().BeOneOf("implicit", null); // Authorize var code = await AuthorizeAsync(ProductionBootstrapFixture.TestClientIdPublic, "openid profile"); code.Should().NotBeNullOrEmpty(); // For implicit consent, no permanent authorization should exist for this flow execution. await _fx.WithRedb(async redb => { var consentService = new ConsentService(redb); var coreUser = await redb.UserProvider.GetUserByLoginAsync(ProductionBootstrapFixture.TestUsername) ?? throw new Exception("Test user not found"); // (OpenIddict may create ad-hoc ones, but our ConsentService only returns permanent ones) var consent = await consentService.CheckAsync(coreUser.Id, app.id, ["openid", "profile"]); // This might or might not be null depending on whether OpenIddict creates permanent auths // The key assertion is that our ConsentService.GrantAsync was NOT called for implicit // We verify this by checking that no permanent auth was created AFTER our specific flow }); } [Fact] public async Task ConsentManagement_ListAndRevoke_ViaDirectVm() { // Bootstrap reads via per-call scope (see AuthCode_ExplicitConsent comment). var (app, coreUser) = await _fx.WithRedb(async redb => { var a = await redb.Query() .Where(p => p.ClientId == ProductionBootstrapFixture.TestClientId) .FirstOrDefaultAsync(); var u = await redb.UserProvider.GetUserByLoginAsync(ProductionBootstrapFixture.TestUsername) ?? throw new Exception("Test user not found"); return (a, u); }); await _fx.WithRedb(redb => new ConsentService(redb).GrantAsync(coreUser.Id, app!.id, ["openid", "profile"])); // List via direct-vm var listExchange = await _fx.RequestWithHeaders( IdentityEndpoints.ManageConsents, new Dictionary { ["userId"] = coreUser.Id }, new Dictionary { ["operation"] = "list" }); var listBody = listExchange.Out?.Body; listBody.Should().NotBeNull(); // Revoke via direct-vm var revokeExchange = await _fx.RequestWithHeaders( IdentityEndpoints.ManageConsents, new Dictionary { ["userId"] = coreUser.Id, ["applicationId"] = app.id }, new Dictionary { ["operation"] = "revoke" }); // Verify consent is revoked var afterRevoke = await _fx.WithRedb(redb => new ConsentService(redb).CheckAsync(coreUser.Id, app.id, ["openid"])); afterRevoke.Should().BeNull("consent should be revoked"); } [Fact] public async Task ConsentManagement_RevokeAll_ViaDirectVm() { // Bootstrap: read apps + user via WithRedb (see explicit-consent comment for rationale). var (app1, app2, coreUser) = await _fx.WithRedb(async redb => { var a1 = await redb.Query() .Where(p => p.ClientId == ProductionBootstrapFixture.TestClientId) .FirstOrDefaultAsync(); var a2 = await redb.Query() .Where(p => p.ClientId == ProductionBootstrapFixture.TestClientIdPublic) .FirstOrDefaultAsync(); var u = await redb.UserProvider.GetUserByLoginAsync(ProductionBootstrapFixture.TestUsername) ?? throw new Exception("Test user not found"); return (a1, a2, u); }); // GrantAsync writes via the same scoped redb — own scope per call to avoid sharing // the captive Redb's NpgsqlConnection with the Worker's WireTap audit writer. await _fx.WithRedb(redb => new ConsentService(redb).GrantAsync(coreUser.Id, app1!.id, ["openid"])); await _fx.WithRedb(redb => new ConsentService(redb).GrantAsync(coreUser.Id, app2!.id, ["openid", "profile"])); // Revoke all var exchange = await _fx.RequestWithHeaders( IdentityEndpoints.ManageConsents, new Dictionary { ["userId"] = coreUser.Id }, new Dictionary { ["operation"] = "revoke-all" }); // Verify all revoked var list = await _fx.WithRedb(redb => new ConsentService(redb).ListAsync(coreUser.Id)); list.Should().BeEmpty("all consents should be revoked"); } private async Task AuthorizeAsync(string clientId, string scopes, string? clientSecret = null) { var (verifier, challenge) = GeneratePkce(); var body = new Dictionary { ["response_type"] = "code", ["client_id"] = clientId, ["redirect_uri"] = ProductionBootstrapFixture.TestRedirectUri, ["scope"] = scopes, ["code_challenge"] = challenge, ["code_challenge_method"] = "S256" }; if (clientSecret is not null) body["client_secret"] = clientSecret; var result = await _fx.RequestWithSession(IdentityEndpoints.Authorize, body); var response = result as Dictionary; return response?.TryGetValue("code", out var code) == true ? code?.ToString() : null; } private static (string verifier, string challenge) GeneratePkce() { var bytes = System.Security.Cryptography.RandomNumberGenerator.GetBytes(32); var verifier = Convert.ToBase64String(bytes) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = System.Security.Cryptography.SHA256.HashData( System.Text.Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } } Path: redb-identity/tests/redb.Identity.Tests/Consent/ConsentServiceTests.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/Consent/ConsentServiceTests.cs ---- using AwesomeAssertions; using OpenIddict.Abstractions; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Consent; [Collection("Postgres")] public class ConsentServiceTests { private readonly ConsentService _consent; private readonly PostgresFixture _fixture; public ConsentServiceTests(PostgresFixture fixture) { _fixture = fixture; _consent = new ConsentService(fixture.Redb); } private async Task> CreateTestAppAsync(string? consentType = null) { var app = new RedbObject { name = $"consent-test-app-{Guid.NewGuid():N}", Props = new ApplicationProps { ClientId = $"consent-app-{Guid.NewGuid():N}", ClientType = "confidential", ConsentType = consentType ?? "explicit" } }; app.value_string = app.Props.ClientId; app.id = await _fixture.Redb.SaveAsync(app); return app; } private async Task CreateTestUserAsync() { var login = $"consent-user-{Guid.NewGuid():N}"; var coreUser = await _fixture.Redb.UserProvider.CreateUserAsync( new redb.Core.Models.Users.CreateUserRequest { Login = login, Password = "Test1234!", Name = login, Enabled = true }); return coreUser.Id; } [Fact] public async Task CheckAsync_NoConsent_ReturnsNull() { var app = await CreateTestAppAsync(); var userId = await CreateTestUserAsync(); var result = await _consent.CheckAsync(userId, app.id, ["openid", "profile"]); result.Should().BeNull(); } [Fact] public async Task GrantAsync_CreatesNewConsent() { var app = await CreateTestAppAsync(); var userId = await CreateTestUserAsync(); var consent = await _consent.GrantAsync(userId, app.id, ["openid", "profile"]); consent.Should().NotBeNull(); consent.id.Should().BeGreaterThan(0); consent.Props.Status.Should().Be(OpenIddictConstants.Statuses.Valid); consent.Props.Type.Should().Be(OpenIddictConstants.AuthorizationTypes.Permanent); consent.Props.Scopes.Should().BeEquivalentTo(["openid", "profile"]); consent.key.Should().Be(userId); consent.Props.ApplicationObjectId.Should().Be(app.id); } [Fact] public async Task CheckAsync_AfterGrant_ReturnsConsent() { var app = await CreateTestAppAsync(); var userId = await CreateTestUserAsync(); await _consent.GrantAsync(userId, app.id, ["openid", "profile", "email"]); // Check with subset of scopes — should match var result = await _consent.CheckAsync(userId, app.id, ["openid", "profile"]); result.Should().NotBeNull(); result!.Props.Scopes.Should().Contain("openid"); result.Props.Scopes.Should().Contain("profile"); result.Props.Scopes.Should().Contain("email"); } [Fact] public async Task CheckAsync_InsufficientScopes_ReturnsNull() { var app = await CreateTestAppAsync(); var userId = await CreateTestUserAsync(); await _consent.GrantAsync(userId, app.id, ["openid"]); // Require more scopes than granted var result = await _consent.CheckAsync(userId, app.id, ["openid", "profile"]); result.Should().BeNull(); } [Fact] public async Task GrantAsync_ExistingConsent_MergesScopes() { var app = await CreateTestAppAsync(); var userId = await CreateTestUserAsync(); var first = await _consent.GrantAsync(userId, app.id, ["openid", "profile"]); var second = await _consent.GrantAsync(userId, app.id, ["openid", "email"]); // Should be the same record (merged), not a new one second.id.Should().Be(first.id); second.Props.Scopes.Should().BeEquivalentTo(["openid", "profile", "email"]); } [Fact] public async Task RevokeAsync_RevokesConsent() { var app = await CreateTestAppAsync(); var userId = await CreateTestUserAsync(); await _consent.GrantAsync(userId, app.id, ["openid", "profile"]); var revoked = await _consent.RevokeAsync(userId, app.id); revoked.Should().Be(1); // Check should return null after revocation var result = await _consent.CheckAsync(userId, app.id, ["openid"]); result.Should().BeNull(); } [Fact] public async Task RevokeAsync_NoConsent_ReturnsZero() { var app = await CreateTestAppAsync(); var userId = await CreateTestUserAsync(); var revoked = await _consent.RevokeAsync(userId, app.id); revoked.Should().Be(0); } [Fact] public async Task RevokeAllAsync_RevokesAllConsents() { var app1 = await CreateTestAppAsync(); var app2 = await CreateTestAppAsync(); var userId = await CreateTestUserAsync(); await _consent.GrantAsync(userId, app1.id, ["openid"]); await _consent.GrantAsync(userId, app2.id, ["openid", "profile"]); var revoked = await _consent.RevokeAllAsync(userId); revoked.Should().Be(2); var result1 = await _consent.CheckAsync(userId, app1.id, ["openid"]); var result2 = await _consent.CheckAsync(userId, app2.id, ["openid"]); result1.Should().BeNull(); result2.Should().BeNull(); } [Fact] public async Task ListAsync_ReturnsActiveConsents() { var app = await CreateTestAppAsync(); var userId = await CreateTestUserAsync(); await _consent.GrantAsync(userId, app.id, ["openid", "profile"]); var list = await _consent.ListAsync(userId); list.Should().ContainSingle(c => c.ApplicationId == app.id); var consent = list.First(c => c.ApplicationId == app.id); consent.ClientId.Should().Be(app.Props.ClientId); consent.Scopes.Should().BeEquivalentTo(["openid", "profile"]); consent.UserId.Should().Be(userId); } [Fact] public async Task ListAsync_ExcludesRevokedConsents() { var app = await CreateTestAppAsync(); var userId = await CreateTestUserAsync(); await _consent.GrantAsync(userId, app.id, ["openid"]); await _consent.RevokeAsync(userId, app.id); var list = await _consent.ListAsync(userId); list.Should().NotContain(c => c.ApplicationId == app.id); } [Fact] public async Task FindApplicationIdAsync_ReturnsAppId() { var app = await CreateTestAppAsync(); var result = await _consent.FindApplicationIdAsync(app.Props.ClientId!); result.Should().Be(app.id); } [Fact] public async Task FindApplicationIdAsync_UnknownClient_ReturnsNull() { var result = await _consent.FindApplicationIdAsync("nonexistent-client-id"); result.Should().BeNull(); } } Path: redb-identity/tests/redb.Identity.Tests/Cookies/CookieDefaultsTests.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/Cookies/CookieDefaultsTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Configuration; using redb.Identity.Http.Processors; using Xunit; using redb.Identity.Contracts.Configuration; namespace redb.Identity.Tests.Cookies; /// /// G9 — cookie-flag matrix on . /// /// Every identity cookie (session, mfa_state, federation binding) flows through this /// single formatter (C9). Any regression here silently drops one of the three flags /// that keep browser cookies safe — HttpOnly (no JS theft), Secure (no /// plaintext leakage), SameSite (CSRF). The tests pin the exact emitted /// string to catch the usual footguns: /// /// __Host- prefix only applied when secure=true (RFC 6265bis §4.1.3.2 /// — the prefix REQUIRES Secure, browsers silently drop otherwise); /// HttpOnly is always emitted (no opt-out); /// Path=/ is always emitted (required by __Host-); /// Max-Age=0 produces a clearing cookie (logout contract); /// SameSite=None forces Secure for modern browsers (cookie is /// cross-site; None+not-Secure is rejected). /// /// /// public sealed class CookieDefaultsTests { [Fact] public void Build_SecureTrue_HostPrefixTrue_AppliesHostPrefix() { var s = IdentityCookieFormatter.Build( "redb.identity.session", "VALUE", maxAgeSeconds: 3600, secure: true, sameSite: CookieSameSiteMode.Lax, useHostPrefix: true); s.Should().StartWith("__Host-redb.identity.session=VALUE", "the __Host- prefix MUST be applied when secure=true and useHostPrefix=true. " + "Without it, the server advertises ambient-scope cookies (subdomain-shareable, " + "path-overridable) which break the same-origin assumption the session lease " + "is built on."); s.Should().Contain("; Path=/"); s.Should().Contain("; Max-Age=3600"); s.Should().Contain("; HttpOnly"); s.Should().Contain("; Secure"); s.Should().Contain("; SameSite=Lax"); } [Fact] public void Build_SecureFalse_HostPrefixDropped() { // Over plain http, emitting a __Host- cookie would be silently dropped by the // browser (RFC 6265bis §4.1.3.2 requires Secure). The formatter must fall back // to the bare name rather than pretending — otherwise the user appears // perpetually logged out in local dev / behind TLS-terminating proxies that // advertise http upstream. var s = IdentityCookieFormatter.Build( "redb.identity.session", "VALUE", maxAgeSeconds: 3600, secure: false, sameSite: CookieSameSiteMode.Lax, useHostPrefix: true); s.Should().StartWith("redb.identity.session=VALUE"); s.Should().NotStartWith("__Host-"); s.Should().NotContain("; Secure"); s.Should().Contain("; HttpOnly", "HttpOnly is unconditional — C9 forbids any code path that emits a JS-readable " + "session cookie."); } [Theory] [InlineData(CookieSameSiteMode.Strict, "Strict")] [InlineData(CookieSameSiteMode.Lax, "Lax")] [InlineData(CookieSameSiteMode.None, "None")] public void Build_EmitsCanonicalSameSiteToken(CookieSameSiteMode mode, string expected) { var s = IdentityCookieFormatter.Build( "c", "v", maxAgeSeconds: 60, secure: true, sameSite: mode, useHostPrefix: false); s.Should().Contain($"; SameSite={expected}", "SameSite token must be the RFC-precise casing; lowercase / misspelled tokens " + "are accepted by some browsers but rejected by Safari — producing silent " + "session drop in cross-browser tests."); } [Fact] public void Build_MaxAgeZero_EmitsClearingCookie() { // Logout / ClearSessionCookie / ClearMfaStateCookieOnSuccess all route through // Build with maxAgeSeconds=0. The header MUST include Max-Age=0 so browsers // treat this as a delete directive (RFC 6265 §5.2.2). var s = IdentityCookieFormatter.Build( "c", "", maxAgeSeconds: 0, secure: true, sameSite: CookieSameSiteMode.Lax, useHostPrefix: false); s.Should().Contain("; Max-Age=0", "logout path emits maxAgeSeconds=0 which must surface as Max-Age=0 — the " + "browser relies on this to evict the session cookie. A regression that " + "omits Max-Age entirely would leave the cookie in the jar past logout."); } [Fact] public void Build_EmptyName_Throws() { // Defensive: a bug in a caller that supplies an empty cookie name would produce // an invalid Set-Cookie header ("=value; …") which Kestrel would silently swallow. // The formatter rejects it at the seam. var act = () => IdentityCookieFormatter.Build( "", "v", 60, secure: true, sameSite: CookieSameSiteMode.Lax); act.Should().Throw(); } [Fact] public void Candidates_ReturnsPrefixedAndBareForReaderMatching() { var (prefixed, bare) = IdentityCookieFormatter.Candidates("redb.identity.session"); prefixed.Should().Be("__Host-redb.identity.session"); bare.Should().Be("redb.identity.session"); // Readers consult Candidates so an in-progress rollout (http behind TLS proxy // still emitting bare, https-direct now emitting __Host-) continues to verify // both forms. A regression that returns only one breaks zero-downtime rollout. } } Path: redb-identity/tests/redb.Identity.Tests/Cookies/SessionCookieRotationTests.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/Cookies/SessionCookieRotationTests.cs ---- using System.Net; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Cookies; /// /// G10 / C7 — session-fixation defence via per-login cookie value rotation. /// /// In redb.Identity the session cookie is an encrypted DataProtection ticket built /// by SessionTicketService.Protect(userId, sessionId, username) where /// sessionId is freshly generated by SessionService.CreateAsync on every /// successful login (see LoginProcessor.Process) and again on every successful /// MFA verify (see MfaVerifyProcessor.Process). DataProtection adds a random /// nonce to the ciphertext, so even if userId+sessionId were identical the cookie /// value would differ — but they are not identical, because each login produces a /// new SessionProps row. /// /// /// The C7 spec calls for "session-id rotation" — in this implementation that means /// the entire opaque cookie value MUST change between two successive logins from /// the same client. These tests assert exactly that: an attacker pre-seeding a /// cookie value cannot have it survive across a login. /// /// [Collection("ProductionHttp")] public sealed class SessionCookieRotationTests { private readonly ProductionHttpFixture _fx; public SessionCookieRotationTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Login_IssuesFreshSessionCookie_OnEachSuccessfulLogin() { var first = await DoLoginAndExtractSessionCookieAsync(); var second = await DoLoginAndExtractSessionCookieAsync(); first.Should().NotBeNullOrEmpty("login response must Set-Cookie the session ticket"); second.Should().NotBeNullOrEmpty(); second.Should().NotBe(first, "C7 / session-fixation: each successful /login must emit a new opaque " + "session cookie value. The encrypted ticket binds a freshly-created " + "SessionProps row (new sessionId), so two logins back-to-back must " + "produce two distinct cookies — otherwise an attacker could pre-fix " + "the cookie on the victim and ride the post-login session."); } [Fact] public async Task Login_OverridesPreSeededAttackerCookie() { // Simulate session-fixation: attacker plants a cookie value on the victim // BEFORE login; after login the value MUST be a fresh server-issued one, // not the attacker's seed. const string attackerCookieValue = "ATTACKER-FIXED-COOKIE-DOES-NOT-DECRYPT"; var cookies = new CookieContainer(); cookies.Add(new Uri(_fx.BaseUrl), new Cookie( "redb.identity.session", attackerCookieValue) { Path = "/" }); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true, }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; var resp = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); resp.IsSuccessStatusCode.Should().BeTrue(); var setCookie = ExtractSessionSetCookie(resp); setCookie.Should().NotBeNullOrEmpty("login must Set-Cookie a fresh session ticket"); setCookie.Should().NotContain(attackerCookieValue, "session-fixation: server-issued cookie must NOT echo the attacker's seed"); // Independently verify by walking the CookieContainer: post-login the // stored cookie value must not equal the seed. var stored = cookies.GetCookies(new Uri(_fx.BaseUrl))["redb.identity.session"]; stored.Should().NotBeNull(); stored!.Value.Should().NotBe(attackerCookieValue, "the cookie jar after login must hold the new server-issued ticket"); } [Fact] public async Task Logout_ClearsSessionCookie() { var cookies = new CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true, }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); // Pre-condition: session cookie present and non-empty var preLogout = cookies.GetCookies(new Uri(_fx.BaseUrl))["redb.identity.session"]; preLogout.Should().NotBeNull(); preLogout!.Value.Should().NotBeNullOrEmpty(); // No id_token_hint: the OP asks the browser to confirm first; LogoutFlow posts the page's state back. var logoutResp = await LogoutFlow.ConfirmAsync(client, await client.PostAsync("/connect/logout", new FormUrlEncodedContent([]))); // The Set-Cookie on the logout response must clear the session cookie. // CookieContainer treats Max-Age=0 / Expires in past as deletion; check // that the cookie value is now empty (server explicitly cleared) OR the // CookieContainer no longer holds it. var rawSetCookies = string.Join("; ", logoutResp.Headers.TryGetValues("Set-Cookie", out var sc) ? sc : []); rawSetCookies.Should().Contain("redb.identity.session", "logout must emit Set-Cookie targeting the session cookie name"); rawSetCookies.Should().MatchRegex("(?i)(max-age=0|expires=)", "logout must clear the cookie via Max-Age=0 or a past Expires date"); } // ─────────────── helpers ─────────────── private async Task DoLoginAndExtractSessionCookieAsync() { using var handler = new HttpClientHandler { AllowAutoRedirect = false, UseCookies = false }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; var resp = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); resp.IsSuccessStatusCode.Should().BeTrue(); return ExtractSessionSetCookie(resp); } private static string? ExtractSessionSetCookie(HttpResponseMessage resp) { if (!resp.Headers.TryGetValues("Set-Cookie", out var values)) return null; foreach (var v in values) { // Header format: "redb.identity.session=; Path=/; ...". var idx = v.IndexOf("redb.identity.session=", StringComparison.Ordinal); if (idx < 0) continue; var tail = v[(idx + "redb.identity.session=".Length)..]; var semi = tail.IndexOf(';'); return semi >= 0 ? tail[..semi] : tail; } return null; } } Path: redb-identity/tests/redb.Identity.Tests/DataProtection/DataProtectionAtRestTests.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/DataProtection/DataProtectionAtRestTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.AspNetCore.DataProtection.Repositories; using Microsoft.AspNetCore.DataProtection.XmlEncryption; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using redb.Identity.Core; using redb.Identity.Core.DataProtection; using redb.Identity.DataProtection; using System.Xml.Linq; using Xunit; using DataProtectionOptions = redb.Identity.Core.Configuration.DataProtectionOptions; using DataProtectionCertificateOptions = redb.Identity.Core.Configuration.DataProtectionCertificateOptions; using RedbIdentityOptions = redb.Identity.Core.Configuration.RedbIdentityOptions; namespace redb.Identity.Tests.DataProtection; /// /// C10 — at-rest encryption for the DataProtection key-ring. /// public class DataProtectionAtRestTests { private static byte[] NewKey() => System.Security.Cryptography.RandomNumberGenerator.GetBytes(32); // ── AES-GCM master-key encryptor ── [Fact] public void AesGcmEncryptor_RoundTrips_Plaintext() { var keyProvider = new RedbMasterKeyProvider(NewKey()); var encryptor = new RedbAesGcmXmlEncryptor(keyProvider); var original = new XElement("key", new XAttribute("id", "abc"), new XElement("descriptor", "secret-payload")); var encrypted = encryptor.Encrypt(original); encrypted.DecryptorType.Should().Be(typeof(RedbAesGcmXmlDecryptor)); encrypted.EncryptedElement.Element("encryptionAlgorithm")!.Value .Should().Be(RedbAesGcmXmlEncryptor.AlgorithmId); // Roundtrip via the decryptor (resolved from a tiny DI graph). var sp = new ServiceCollection().AddSingleton(keyProvider).BuildServiceProvider(); var decryptor = new RedbAesGcmXmlDecryptor(sp); var roundtripped = decryptor.Decrypt(encrypted.EncryptedElement); XNode.DeepEquals(roundtripped, original).Should().BeTrue(); } [Fact] public void AesGcmEncryptor_CiphertextDoesNotContainPlaintext() { var encryptor = new RedbAesGcmXmlEncryptor(new RedbMasterKeyProvider(NewKey())); var element = new XElement("key", "very-secret-marker"); var encrypted = encryptor.Encrypt(element); encrypted.EncryptedElement.ToString(SaveOptions.DisableFormatting) .Should().NotContain("very-secret-marker"); } [Fact] public void AesGcmDecryptor_RejectsTamperedCiphertext() { var keyProvider = new RedbMasterKeyProvider(NewKey()); var encryptor = new RedbAesGcmXmlEncryptor(keyProvider); var encrypted = encryptor.Encrypt(new XElement("key", "data")); // Flip a bit inside the ciphertext blob — AES-GCM tag check must reject. var valueElement = encrypted.EncryptedElement.Element("value")!; var blob = Convert.FromBase64String(valueElement.Value); blob[blob.Length - 1] ^= 0x01; valueElement.Value = Convert.ToBase64String(blob); var sp = new ServiceCollection().AddSingleton(keyProvider).BuildServiceProvider(); var decryptor = new RedbAesGcmXmlDecryptor(sp); var act = () => decryptor.Decrypt(encrypted.EncryptedElement); act.Should().Throw(); } [Fact] public void AesGcmDecryptor_RejectsWrongAlgorithm() { var keyProvider = new RedbMasterKeyProvider(NewKey()); var sp = new ServiceCollection().AddSingleton(keyProvider).BuildServiceProvider(); var decryptor = new RedbAesGcmXmlDecryptor(sp); var bogus = new XElement("encryptedKey", new XElement("encryptionAlgorithm", "rot13"), new XElement("value", Convert.ToBase64String(new byte[64]))); var act = () => decryptor.Decrypt(bogus); act.Should().Throw().WithMessage("*Unsupported algorithm*"); } [Fact] public void MasterKeyProvider_RejectsWrongLength() { var act = () => new RedbMasterKeyProvider(new byte[16]); act.Should().Throw().WithMessage("*32 bytes*"); } // ── ProtectKeysWithRedbIdentity wiring ── [Fact] public void ProtectKeys_MasterKey_RegistersAesGcmEncryptor() { var key = Convert.ToBase64String(NewKey()); var options = new RedbIdentityOptions { DataProtection = new DataProtectionOptions { MasterKey = key } }; var sp = BuildDataProtectionGraph(options); var kmo = sp.GetRequiredService>().Value; kmo.XmlEncryptor.Should().BeOfType(); sp.GetService().Should().NotBeNull(); } [Fact] public void ProtectKeys_CustomEncryptorFactory_TakesPrecedence() { var fakeEncryptor = new FakeXmlEncryptor(); var options = new RedbIdentityOptions { DataProtection = new DataProtectionOptions { MasterKey = Convert.ToBase64String(NewKey()), // would otherwise win CustomEncryptorFactory = _ => fakeEncryptor } }; var sp = BuildDataProtectionGraph(options); var kmo = sp.GetRequiredService>().Value; kmo.XmlEncryptor.Should().BeSameAs(fakeEncryptor); } [Fact] public void ProtectKeys_NoEncryptor_ProductionGate_Throws() { var options = new RedbIdentityOptions { AllowEphemeralKeys = false, DataProtection = new DataProtectionOptions { RequireAtRestEncryption = true } }; var act = () => BuildDataProtectionGraph(options); act.Should().Throw() .WithMessage("*key-ring is unprotected at rest*"); } [Fact] public void ProtectKeys_NoEncryptor_DevMode_AllowedWhenEphemeralKeysAllowed() { var options = new RedbIdentityOptions { AllowEphemeralKeys = true, DataProtection = new DataProtectionOptions { RequireAtRestEncryption = true } }; var sp = BuildDataProtectionGraph(options); var kmo = sp.GetRequiredService>().Value; kmo.XmlEncryptor.Should().BeNull(); } [Fact] public void ProtectKeys_NoEncryptor_GateOff_Allowed() { var options = new RedbIdentityOptions { AllowEphemeralKeys = false, DataProtection = new DataProtectionOptions { RequireAtRestEncryption = false } }; var sp = BuildDataProtectionGraph(options); var kmo = sp.GetRequiredService>().Value; kmo.XmlEncryptor.Should().BeNull(); } [Fact] public void ProtectKeys_MasterKey_RejectsWrongLength() { var options = new RedbIdentityOptions { DataProtection = new DataProtectionOptions { MasterKey = Convert.ToBase64String(new byte[16]) // 128-bit, not 256 } }; var act = () => BuildDataProtectionGraph(options); act.Should().Throw().WithMessage("*32 bytes*"); } [Fact] public void ProtectKeys_MasterKey_RejectsBadBase64() { var options = new RedbIdentityOptions { DataProtection = new DataProtectionOptions { MasterKey = "%not-base64%" } }; var act = () => BuildDataProtectionGraph(options); act.Should().Throw().WithMessage("*base64*"); } [Fact] public void ProtectKeys_Cert_PfxPathMissing_Throws() { var options = new RedbIdentityOptions { DataProtection = new DataProtectionOptions { Certificate = new DataProtectionCertificateOptions { PfxPath = "C:/this/path/does/not/exist.pfx" } } }; var act = () => BuildDataProtectionGraph(options); act.Should().Throw().WithMessage("*does not exist*"); } // ── DataProtectionOptions.HasEncryptorConfigured ── [Theory] [InlineData(false, null, null, null, false)] // nothing [InlineData(true, "AAAA", null, null, true)] // master key [InlineData(false, null, "thumb", null, true)] // cert thumbprint [InlineData(false, null, null, "/p.pfx", true)] // cert pfx public void HasEncryptorConfigured_ReflectsAllSources( bool useFactory, string? masterKey, string? thumbprint, string? pfxPath, bool expected) { var dp = new DataProtectionOptions { MasterKey = masterKey, Certificate = new DataProtectionCertificateOptions { Thumbprint = thumbprint, PfxPath = pfxPath } }; if (useFactory) dp.CustomEncryptorFactory = _ => new FakeXmlEncryptor(); dp.HasEncryptorConfigured.Should().Be(expected || useFactory); } // ── helpers ── /// /// Builds a tiny DI graph that mirrors what AddRedbIdentityServer does for /// DataProtection — just enough to inspect the resulting . /// private static IServiceProvider BuildDataProtectionGraph(RedbIdentityOptions options) { var services = new ServiceCollection(); services.AddDataProtection() .PersistKeysToRedb() .ProtectKeysWithRedbIdentity(options); // PersistKeysToRedb registers RedbXmlRepository which depends on IServiceScopeFactory — // ServiceCollection provides one out of the box, so no extra registration needed. return services.BuildServiceProvider(); } private sealed class FakeXmlEncryptor : IXmlEncryptor { public EncryptedXmlInfo Encrypt(XElement plaintextElement) => new(new XElement("fake"), typeof(FakeXmlEncryptor)); } } Path: redb-identity/tests/redb.Identity.Tests/DataProtection/FileKeyRingImportTests.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/DataProtection/FileKeyRingImportTests.cs ---- using System.Xml.Linq; using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Services; using redb.Identity.DataProtection; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.DataProtection; /// /// Up to 4.3 PersistKeysToRedb registered the repository in DI only, the key manager ignored it and /// kept the key ring in the file system of the process user. These tests replay the upgrade: a "4.3 /// process" protects data with a file key ring, a "4.4 process" imports that ring into redb and reads the /// data; later starts need no files at all. /// public sealed class FileKeyRingImportTests : IAsyncLifetime { // Same application name and purposes as the Identity module (IdentityModuleHost, PropsSigningKeyStore). private const string ApplicationName = "redb.identity"; private const string SigningKeyPurpose = "redb.identity.signing-keys.v1"; private readonly string _fileRing = Path.Combine(Path.GetTempPath(), "redb-dp-import-" + Guid.NewGuid().ToString("N")); private string _pgCs = ""; public Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); _pgCs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); Directory.CreateDirectory(_fileRing); return Task.CompletedTask; } public Task DisposeAsync() { try { Directory.Delete(_fileRing, recursive: true); } catch { /* best effort */ } return Task.CompletedTask; } [Fact] public async Task Upgrade_imports_the_file_ring_once_and_data_stays_readable_without_files() { // 4.3: the key ring lives in files; a TOTP secret and a signing key are protected with it. string protectedTotp, protectedSigningKey; using (var legacy = BuildLegacyProcess()) { var dp = legacy.GetRequiredService(); protectedTotp = new MfaSecretProtector(dp).Protect("JBSWY3DPEHPK3PXP"); protectedSigningKey = dp.CreateProtector(SigningKeyPurpose).Protect("-----BEGIN PRIVATE KEY-----test"); } AgeFileRing(); var fileKeyIds = Directory.EnumerateFiles(_fileRing, "key-*.xml") .Select(f => XElement.Load(f).Attribute("id")!.Value).ToList(); fileKeyIds.Should().NotBeEmpty("the 4.3 process must have written its key ring to the files"); // (a) 4.4, first start: the file ring is imported into redb and the data is readable. await using (var upgraded = await StartProcessAsync(importFrom: _fileRing)) { upgraded.Imported.Should().Be(fileKeyIds.Count); upgraded.Read(protectedTotp, protectedSigningKey); (await KeyIdsInRedbAsync(upgraded.Services)).Should().Contain(fileKeyIds); } // Another program sharing the directory (the Tsak worker, dashboard, Identity Web) writes a key of // its own after the move: it is not Identity's and must not be imported. using (var other = BuildLegacyProcess()) other.GetRequiredService().CreateNewKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(90)); // (c) 4.4, next start with the same files: nothing is imported a second time. await using (var restarted = await StartProcessAsync(importFrom: _fileRing)) { restarted.Imported.Should().Be(0); restarted.Read(protectedTotp, protectedSigningKey); } // (b) recreated container without the file volume: the ring comes from redb alone. Directory.Delete(_fileRing, recursive: true); await using (var recreated = await StartProcessAsync(importFrom: _fileRing)) { recreated.Imported.Should().Be(0); recreated.Read(protectedTotp, protectedSigningKey); } } [Fact] public async Task New_keys_are_written_to_redb_not_to_the_file_system() { // (d) the key manager uses redb as its repository; a key it creates lands in redb. await using var process = await StartProcessAsync(importFrom: null); process.Services.GetRequiredService>().Value.XmlRepository .Should().BeOfType(); var keyManager = process.Services.GetRequiredService(); var key = keyManager.CreateNewKey(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(90)); (await KeyIdsInRedbAsync(process.Services)).Should().Contain(key.KeyId.ToString()); process.Services.GetRequiredService().GetAllElements() .Should().Contain(e => e.Attribute("id")!.Value == key.KeyId.ToString()); } [Fact] public async Task Duplicate_rows_of_one_key_do_not_break_the_ring() { // Two nodes importing the same file key at once leave two rows; the key manager refuses a ring // with a duplicate key id, so the snapshot keeps one. string protectedTotp; using (var legacy = BuildLegacyProcess()) protectedTotp = new MfaSecretProtector(legacy.GetRequiredService()).Protect("SECRET"); AgeFileRing(); var file = Directory.EnumerateFiles(_fileRing, "key-*.xml").Single(); await using var process = await StartProcessAsync(importFrom: _fileRing); using (var scope = process.Services.CreateScope()) { var redb = scope.ServiceProvider.GetRequiredService(); await redb.SaveAsync(new RedbObject { name = Path.GetFileNameWithoutExtension(file), Props = new DataProtectionKeyProps { FriendlyName = Path.GetFileNameWithoutExtension(file), XmlContent = XElement.Load(file).ToString(SaveOptions.DisableFormatting) } }); await process.Services.GetRequiredService().ReloadAsync(redb); } var id = XElement.Load(file).Attribute("id")!.Value; process.Services.GetRequiredService().GetAllElements() .Count(e => e.Attribute("id")?.Value == id).Should().Be(1); new MfaSecretProtector(process.Services.GetRequiredService()) .Unprotect(protectedTotp).Should().Be("SECRET"); } // ── helpers ── /// /// Dates the file keys back to 2020: a ring written by 4.3 predates the move of the ring into redb. /// The import keeps only elements older than that move, and on a shared test database the move may /// have been recorded by an earlier run. /// private void AgeFileRing() { foreach (var file in Directory.EnumerateFiles(_fileRing, "key-*.xml")) { var key = XElement.Load(file); key.Element("creationDate")!.Value = "2020-01-01T00:00:00Z"; key.Save(file); } } private ServiceProvider BuildLegacyProcess() { var services = new ServiceCollection(); services.AddLogging(); services.AddDataProtection() .SetApplicationName(ApplicationName) .PersistKeysToFileSystem(new DirectoryInfo(_fileRing)); return services.BuildServiceProvider(); } /// A 4.4 process start: what the Identity init listener does before the first request. private async Task StartProcessAsync(string? importFrom) { var services = new ServiceCollection(); services.AddLogging(); services.AddRedbForTests(_pgCs); services.AddDataProtection() .SetApplicationName(ApplicationName) .PersistKeysToRedb(); var sp = services.BuildServiceProvider(); using var scope = sp.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); await redb.InitializeAsync(ensureCreated: true); var imported = await RedbXmlRepository.ImportFileKeyRingsAsync( redb, importFrom is null ? [] : [importFrom], NullLogger.Instance); await sp.GetRequiredService().ReloadAsync(redb); return new UpgradedProcess(sp, imported); } private static async Task> KeyIdsInRedbAsync(IServiceProvider sp) { using var scope = sp.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); var rows = await redb.Query().ToListAsync(); return rows .Select(r => r.Props.XmlContent is { Length: > 0 } xml ? XElement.Parse(xml).Attribute("id")?.Value : null) .Where(id => id is not null) .Select(id => id!) .ToList(); } private sealed class UpgradedProcess(ServiceProvider services, int imported) : IAsyncDisposable { public ServiceProvider Services { get; } = services; public int Imported { get; } = imported; public void Read(string protectedTotp, string protectedSigningKey) { var dp = Services.GetRequiredService(); new MfaSecretProtector(dp).Unprotect(protectedTotp).Should().Be("JBSWY3DPEHPK3PXP"); dp.CreateProtector(SigningKeyPurpose).Unprotect(protectedSigningKey) .Should().Be("-----BEGIN PRIVATE KEY-----test"); } public ValueTask DisposeAsync() => Services.DisposeAsync(); } } Path: redb-identity/tests/redb.Identity.Tests/DataProtection/MultiReplicaKeyRingTests.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/DataProtection/MultiReplicaKeyRingTests.cs ---- using System.Collections.Immutable; using System.Xml.Linq; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Identity.Core.DataProtection; using redb.Identity.DataProtection; using redb.Identity.Core.Models; using redb.Postgres.Pro.Extensions; using Xunit;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.DataProtection; /// /// G1 — multi-replica DataProtection key-ring sanity. /// /// Two independent instances (= two replicas in the same cluster) /// share one PostgreSQL DataProtectionKeyProps PROPS store. The test verifies the /// contract underpinning A1: keeps an in-process snapshot /// and the periodic refresh (emulated here inline, same query/replace logic as /// ) pulls keys authored by the other replica so /// that cookies/tokens encrypted on one node are decryptable on the other. /// /// public class MultiReplicaKeyRingTests : IAsyncLifetime { private ServiceProvider _replicaA = null!; private ServiceProvider _replicaB = null!; private RedbXmlRepository _repoA = null!; private RedbXmlRepository _repoB = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var pgCs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); // When running under SQLite (the default test provider) we need BOTH // replicas to point at the same physical file so the second instance // sees what the first wrote. AddRedbForTests builds a fresh per-call // SQLite path by default — pin the env var to a single scratch file // for the duration of this test so both calls converge. var sqliteScratch = TestRedbSetup.SelectedProvider == TestRedbSetup.Provider.Sqlite ? TestRedbSetup.CreateSqliteScratchPath() : null; if (sqliteScratch is not null) Environment.SetEnvironmentVariable("REDB_SQLITE_CS", TestRedbSetup.BuildSqliteConnectionString(sqliteScratch)); try { _replicaA = BuildReplica(pgCs); _replicaB = BuildReplica(pgCs); } finally { // The pinned env var is process-wide; clear it as soon as both // service providers have captured their connection string. if (sqliteScratch is not null) Environment.SetEnvironmentVariable("REDB_SQLITE_CS", null); } // Replica A bootstraps the schema once. Replica B reuses the same physical DB. var redbA = _replicaA.GetRequiredService(); try { await redbA.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await redbA.InitializeAsync(); } await redbA.SyncSchemeAsync(); await redbA.InitializeTypeRegistryAsync(); var redbB = _replicaB.GetRequiredService(); await redbB.InitializeAsync(); await redbB.InitializeTypeRegistryAsync(); _repoA = new RedbXmlRepository(_replicaA.GetRequiredService()); _repoB = new RedbXmlRepository(_replicaB.GetRequiredService()); // Seed both snapshots from DB (what RedbXmlRepositoryInitListener does at startup). await RefreshAsync(_replicaA, _repoA); await RefreshAsync(_replicaB, _repoB); } public async Task DisposeAsync() { await _replicaA.DisposeAsync(); await _replicaB.DisposeAsync(); } private static ServiceProvider BuildReplica(string cs) { var sc = new ServiceCollection(); sc.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); sc.AddRedbForTests(cs); return sc.BuildServiceProvider(); } /// /// Mirrors — pulls all persisted keys /// and overwrites the in-process snapshot. Keeping this identical to production logic /// means any change there must also update this helper (guarded by the test itself). /// private static async Task RefreshAsync(IServiceProvider sp, RedbXmlRepository repo) { await using var scope = sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var keys = await redb.Query().ToListAsync(); var builder = ImmutableArray.CreateBuilder(keys.Count); foreach (var k in keys) if (!string.IsNullOrEmpty(k.Props.XmlContent)) builder.Add(XElement.Parse(k.Props.XmlContent)); repo.ReplaceSnapshot(builder.ToImmutable()); } [Fact] public async Task KeyWrittenOnReplicaA_VisibleOnReplicaB_AfterRefresh() { var keyId = $"g1-xprocess-{Guid.NewGuid()}"; var element = new XElement("key", new XAttribute("id", keyId), new XElement("descriptor", "written-by-replica-A")); // Pre-refresh: B must not see a key that hasn't been written yet. _repoB.GetAllElements().Should().NotContain( e => HasId(e, keyId), "B's snapshot was seeded before A wrote the new key"); _repoA.StoreElement(element, $"friendly-{keyId}"); // Without refresh B still sees its stale snapshot. _repoB.GetAllElements().Should().NotContain( e => HasId(e, keyId), "B is a separate replica with its own snapshot — it must not learn about A's write until it refreshes"); // After refresh B picks up the key authored by A. This is the cross-replica contract. await RefreshAsync(_replicaB, _repoB); _repoB.GetAllElements().Should().Contain( e => HasId(e, keyId), "after a refresh tick the PROPS-backed snapshot must include keys authored by peers"); } [Fact] public async Task KeyRotation_OldAndNewCoexist_OnBothReplicas() { // "Old" key on A — simulates the previous active key. var oldId = $"g1-old-{Guid.NewGuid()}"; _repoA.StoreElement( new XElement("key", new XAttribute("id", oldId), new XElement("descriptor", "old")), $"old-{oldId}"); // Fan out to B (initial propagation). await RefreshAsync(_replicaB, _repoB); _repoB.GetAllElements().Should().Contain(e => HasId(e, oldId)); // "New" key rotated in on B — simulates a different replica winning the rotation race. var newId = $"g1-new-{Guid.NewGuid()}"; _repoB.StoreElement( new XElement("key", new XAttribute("id", newId), new XElement("descriptor", "new")), $"new-{newId}"); // Refresh A: both keys must be visible simultaneously. This is the overlap window // where tokens encrypted with the old key are still decryptable by the new replica // while new tokens are minted with the rotated key. await RefreshAsync(_replicaA, _repoA); var snapA = _repoA.GetAllElements(); snapA.Should().Contain(e => HasId(e, oldId), "old key stays in snapshot during overlap window"); snapA.Should().Contain(e => HasId(e, newId), "new key authored by peer must be pulled in"); var snapB = _repoB.GetAllElements(); snapB.Should().Contain(e => HasId(e, oldId)); snapB.Should().Contain(e => HasId(e, newId), "B's own write is reflected in its snapshot immediately (ImmutableInterlocked.Update)"); } // Expression-tree-safe helper: AwesomeAssertions' Contain/NotContain accepts Expression>, // which forbids null-conditional operators (CS8072). Keep the null-check explicit. private static bool HasId(XElement e, string id) { var attr = e.Attribute("id"); return attr != null && attr.Value == id; } } Path: redb-identity/tests/redb.Identity.Tests/Dpop/DpopConfirmationPassThroughTests.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/Dpop/DpopConfirmationPassThroughTests.cs ---- using System.Security.Claims; using AwesomeAssertions; using redb.Identity.Core.OpenIddict.Handlers; using Xunit; namespace redb.Identity.Tests.Dpop; /// /// Which tokens skip OpenIddict 7's proof-of-possession check (it knows only mTLS and throws on a DPoP /// jkt): DPoP-only confirmations do, certificate-bound and plain bearer tokens do not. /// public sealed class DpopConfirmationPassThroughTests { [Theory] [InlineData("{\"jkt\":\"0ZcOCORZNYy-DWpqq30jZyJGHTN0d2HglBV3uiguA4I\"}", true)] [InlineData("{\"x5t#S256\":\"bwcK0esc3ACC3DB2Y5_lESsXE8o9ltc05O89jdN-dg2\"}", false)] [InlineData("{\"jkt\":\"a\",\"x5t#S256\":\"b\"}", false)] [InlineData("not json", false)] public void Recognises_dpop_only_confirmations(string cnf, bool expected) { var principal = new ClaimsPrincipal(new ClaimsIdentity( [new Claim("cnf", cnf, "JSON")], "test")); DpopConfirmationPassThrough.IsDpopOnly(principal).Should().Be(expected); } [Fact] public void A_bearer_token_without_cnf_is_left_alone() { var principal = new ClaimsPrincipal(new ClaimsIdentity([new Claim("sub", "u1")], "test")); DpopConfirmationPassThrough.IsDpopOnly(principal).Should().BeFalse(); DpopConfirmationPassThrough.IsDpopOnly(null).Should().BeFalse(); } } Path: redb-identity/tests/redb.Identity.Tests/Dpop/DpopReplayStoreAtomicityTests.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/Dpop/DpopReplayStoreAtomicityTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using redb.Core; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Dpop; /// /// RFC 9449 §11.1: a DPoP proof is consumed at most once, and "at most once" has to hold when /// the same proof is presented twice at the same instant — that is what a replay is. /// /// used to decide by lookup-then-insert with nothing unique on /// the row: two presentations racing past the lookup both inserted and both were told "reserved". /// The reservation now carries a unique key (SHA-256 of jkt|jti in ValueUnique), /// so the index decides and the loser is refused. These tests pin the three faces of that /// contract on every provider of the matrix: the race, the plain second presentation, and the /// expired reservation that must be refreshed in place rather than inserted a second time. /// /// [Collection("Postgres")] public sealed class DpopReplayStoreAtomicityTests : IAsyncLifetime { private readonly PostgresFixture _fx; private RedbDpopReplayStore _store = null!; public DpopReplayStoreAtomicityTests(PostgresFixture fx) => _fx = fx; public async Task InitializeAsync() { // The shared fixture syncs the OpenIddict schemes only; the replay marker is ours to sync. await _fx.Redb.SyncSchemeAsync(); _store = new RedbDpopReplayStore( _fx.Services.GetRequiredService(), NullLogger.Instance); } public Task DisposeAsync() => Task.CompletedTask; private static string NewJkt() => "jkt-" + Guid.NewGuid().ToString("N"); private static string NewJti() => Guid.NewGuid().ToString("N"); private async Task RowsForAsync(string jkt, string jti) => (await _fx.Redb.Query() .Where(o => o.Jkt == jkt && o.Jti == jti) .ToListAsync()).Count; [Fact] public async Task ConcurrentPresentations_ExactlyOneIsReserved() { var jkt = NewJkt(); var jti = NewJti(); const int parallelism = 16; var results = await Task.WhenAll(Enumerable.Range(0, parallelism) .Select(_ => Task.Run(() => _store.TryReserveAsync(jkt, jti, TimeSpan.FromMinutes(5))))); results.Count(r => r).Should().Be(1, "the same proof presented {0} times at once is a replay {1} times over; only the " + "database index can make the lookup-then-insert decide once", parallelism, parallelism - 1); (await RowsForAsync(jkt, jti)).Should().Be(1, "every extra row is a presentation that was wrongly accepted"); } [Fact] public async Task SecondPresentation_IsRefused() { var jkt = NewJkt(); var jti = NewJti(); var ttl = TimeSpan.FromMinutes(5); (await _store.TryReserveAsync(jkt, jti, ttl)).Should().BeTrue("first presentation reserves"); (await _store.TryReserveAsync(jkt, jti, ttl)).Should().BeFalse("the same jti again is a replay"); (await _store.TryReserveAsync(jkt, NewJti(), ttl)).Should().BeTrue( "a different jti under the same key is a different proof"); } [Fact] public async Task ExpiredReservation_IsRefreshedInPlace_NotDuplicated() { var jkt = NewJkt(); var jti = NewJti(); (await _store.TryReserveAsync(jkt, jti, TimeSpan.FromMilliseconds(1))).Should().BeTrue(); await Task.Delay(50); (await _store.TryReserveAsync(jkt, jti, TimeSpan.FromMinutes(5))).Should().BeTrue( "an expired reservation may be taken again — cleanup simply has not run yet"); (await RowsForAsync(jkt, jti)).Should().Be(1, "the expired row is refreshed, not joined by a second one that the unique key would " + "then misreport as a replay"); (await _store.TryReserveAsync(jkt, jti, TimeSpan.FromMinutes(5))).Should().BeFalse( "the refreshed reservation is live again"); } } Path: redb-identity/tests/redb.Identity.Tests/Dpop/DpopResourceTokenValidatorTests.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/Dpop/DpopResourceTokenValidatorTests.cs ---- using System.Security.Claims; using System.Security.Cryptography; using System.Text; using AwesomeAssertions; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using redb.Identity.Core.Configuration; using redb.Identity.Core.Services; using redb.Identity.Resource.Dpop; using Xunit; namespace redb.Identity.Tests.Dpop; /// /// Z4 P2.3 (RFC 9449 §7): unit tests for the Resource-Server side DPoP-bound access token validator. /// public class DpopResourceTokenValidatorTests { private const string ResourceUrl = "https://api.test/protected"; [Fact] public async Task Valid_Proof_With_Matching_Cnf_Jkt_And_Ath_Validates() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); var jkt = ComputeJkt(ec); var accessToken = BuildAccessToken(cnfJkt: jkt); var ath = DpopResourceTokenValidator.ComputeAth(accessToken); var proof = BuildProof(ec, "GET", ResourceUrl, ath: ath); var sut = BuildSut(); var result = await sut.ValidateAsync(accessToken, proof, "GET", ResourceUrl); result.IsValid.Should().BeTrue("proof's jkt matches cnf.jkt and ath matches the token hash"); result.Jkt.Should().Be(jkt); } [Fact] public async Task Mismatching_Jkt_Fails_With_InvalidToken() { using var keyForToken = ECDsa.Create(ECCurve.NamedCurves.nistP256); using var keyForProof = ECDsa.Create(ECCurve.NamedCurves.nistP256); var accessToken = BuildAccessToken(cnfJkt: ComputeJkt(keyForToken)); var ath = DpopResourceTokenValidator.ComputeAth(accessToken); var proof = BuildProof(keyForProof, "GET", ResourceUrl, ath: ath); var sut = BuildSut(); var result = await sut.ValidateAsync(accessToken, proof, "GET", ResourceUrl); result.IsValid.Should().BeFalse(); result.Error.Should().Be("invalid_token"); result.ErrorDescription.Should().Contain("cnf.jkt"); } [Fact] public async Task Wrong_Ath_Fails_With_InvalidDpopProof() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); var accessToken = BuildAccessToken(cnfJkt: ComputeJkt(ec)); var proof = BuildProof(ec, "GET", ResourceUrl, ath: "wrong-ath-value-not-the-real-hash-aaaaaa"); var sut = BuildSut(); var result = await sut.ValidateAsync(accessToken, proof, "GET", ResourceUrl); result.IsValid.Should().BeFalse(); result.Error.Should().Be("invalid_dpop_proof"); } [Fact] public async Task AccessToken_Without_Cnf_Claim_Fails() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); var accessToken = BuildAccessToken(cnfJkt: null); var ath = DpopResourceTokenValidator.ComputeAth(accessToken); var proof = BuildProof(ec, "GET", ResourceUrl, ath: ath); var sut = BuildSut(); var result = await sut.ValidateAsync(accessToken, proof, "GET", ResourceUrl); result.IsValid.Should().BeFalse(); result.Error.Should().Be("invalid_token"); result.ErrorDescription.Should().Contain("cnf.jkt"); } [Fact] public void BuildChallengeHeader_Produces_Valid_Format() { var header = DpopResourceTokenValidator.BuildChallengeHeader( error: "invalid_token", errorDescription: "missing proof", allowedAlgs: "ES256 RS256", nonce: "abc123"); header.Should().StartWith("DPoP "); header.Should().Contain("error=\"invalid_token\""); header.Should().Contain("error_description=\"missing proof\""); header.Should().Contain("algs=\"ES256 RS256\""); header.Should().Contain("nonce=\"abc123\""); } [Fact] public void ComputeAth_Matches_Rfc_9449_Spec() { // Sample from RFC 9449 §4.2 example. var token = "Kz~8mXK1EalYznwH-LC-1fBAo.4Ljp~zsPE_NeO.gxU"; var hash = SHA256.HashData(Encoding.ASCII.GetBytes(token)); var expected = Base64UrlEncoder.Encode(hash); DpopResourceTokenValidator.ComputeAth(token).Should().Be(expected); } // ─── helpers ─── private static DpopResourceTokenValidator BuildSut() { var opts = Microsoft.Extensions.Options.Options.Create(new RedbIdentityOptions { Issuer = new Uri("https://identity.test/"), Dpop = new DpopOptions { Enabled = true, IatToleranceSeconds = 60, } }); var replayStore = new MemoryDpopReplayStore(TimeProvider.System, null); var validator = new DpopProofValidator( replayStore, opts, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); return new DpopResourceTokenValidator(validator); } /// /// Builds an unsigned-but-readable JWT (alg=none) suitable for the validator's /// payload-only inspection (it does not re-validate signature on access token). /// private static string BuildAccessToken(string? cnfJkt) { var header = "{\"alg\":\"none\",\"typ\":\"at+jwt\"}"; string payload; if (cnfJkt is not null) payload = $"{{\"sub\":\"alice\",\"cnf\":{{\"jkt\":\"{cnfJkt}\"}},\"iat\":{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}}}"; else payload = $"{{\"sub\":\"alice\",\"iat\":{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}}}"; var headerB64 = Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(header)); var payloadB64 = Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(payload)); return $"{headerB64}.{payloadB64}."; } private static string BuildProof(ECDsa ec, string method, string url, string? ath = null) { var pubParams = ec.ExportParameters(includePrivateParameters: false); var x = Base64UrlEncoder.Encode(pubParams.Q.X!); var y = Base64UrlEncoder.Encode(pubParams.Q.Y!); var jwk = $"{{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"{x}\",\"y\":\"{y}\"}}"; var header = $"{{\"typ\":\"dpop+jwt\",\"alg\":\"ES256\",\"jwk\":{jwk}}}"; var iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var jti = Guid.NewGuid().ToString("N"); string payload; if (ath is not null) payload = $"{{\"htm\":\"{method}\",\"htu\":\"{url}\",\"iat\":{iat},\"jti\":\"{jti}\",\"ath\":\"{ath}\"}}"; else payload = $"{{\"htm\":\"{method}\",\"htu\":\"{url}\",\"iat\":{iat},\"jti\":\"{jti}\"}}"; var hB64 = Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(header)); var pB64 = Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(payload)); var signingInput = $"{hB64}.{pB64}"; var sig = ec.SignData(Encoding.ASCII.GetBytes(signingInput), HashAlgorithmName.SHA256); return $"{signingInput}.{Base64UrlEncoder.Encode(sig)}"; } private static string ComputeJkt(ECDsa ec) { var p = ec.ExportParameters(false); var x = Base64UrlEncoder.Encode(p.Q.X!); var y = Base64UrlEncoder.Encode(p.Q.Y!); var canonical = $"{{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"{x}\",\"y\":\"{y}\"}}"; return Base64UrlEncoder.Encode(SHA256.HashData(Encoding.UTF8.GetBytes(canonical))); } } Path: redb-identity/tests/redb.Identity.Tests/Dpop/HmacDpopNonceProviderTests.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/Dpop/HmacDpopNonceProviderTests.cs ---- using System.Security.Cryptography; using System.Text; using AwesomeAssertions; using Microsoft.Extensions.Options; using Microsoft.Extensions.Time.Testing; using Microsoft.IdentityModel.Tokens; using redb.Identity.Core.Configuration; using redb.Identity.Core.Services; using redb.Identity.Resource.Dpop; using Xunit; namespace redb.Identity.Tests.Dpop; /// /// Z4 P2 (RFC 9449 §8): unit tests for the stateless HMAC nonce provider used to sign /// DPoP-Nonce challenges. /// public class HmacDpopNonceProviderTests { private static (HmacDpopNonceProvider provider, FakeTimeProvider time) BuildSut(TimeSpan? lifetime = null) { var time = new FakeTimeProvider(DateTimeOffset.UtcNow); var opts = Options.Create(new RedbIdentityOptions { Issuer = new Uri("https://identity.test/"), Dpop = new DpopOptions { Enabled = true, NonceLifetime = lifetime ?? TimeSpan.FromMinutes(5), NonceSigningSecret = "test-secret-fixed-for-determinism" } }); return (new HmacDpopNonceProvider(opts, time), time); } [Fact] public void IssueNonce_Round_Trip_Validates_True() { var (sut, _) = BuildSut(); var nonce = sut.IssueNonce(); nonce.Should().NotBeNullOrEmpty(); sut.ValidateNonce(nonce).Should().BeTrue("a freshly issued nonce must validate"); } [Fact] public void ValidateNonce_After_Lifetime_Expires_Returns_False() { var (sut, time) = BuildSut(lifetime: TimeSpan.FromSeconds(10)); var nonce = sut.IssueNonce(); time.Advance(TimeSpan.FromSeconds(11)); sut.ValidateNonce(nonce).Should().BeFalse("RFC 9449 §8: expired nonce must be rejected"); } [Fact] public void ValidateNonce_Tampered_Mac_Returns_False() { var (sut, _) = BuildSut(); var nonce = sut.IssueNonce(); var bytes = Base64UrlEncoder.DecodeBytes(nonce); bytes[^1] ^= 0x01; // flip a bit in the MAC var tampered = Base64UrlEncoder.Encode(bytes); sut.ValidateNonce(tampered).Should().BeFalse("HMAC-tampered nonce must not validate"); } [Fact] public void ValidateNonce_Different_Secret_Returns_False() { var time = new FakeTimeProvider(DateTimeOffset.UtcNow); var optsA = Options.Create(new RedbIdentityOptions { Issuer = new Uri("https://identity.test/"), Dpop = new DpopOptions { Enabled = true, NonceSigningSecret = "secret-A" } }); var optsB = Options.Create(new RedbIdentityOptions { Issuer = new Uri("https://identity.test/"), Dpop = new DpopOptions { Enabled = true, NonceSigningSecret = "secret-B" } }); var providerA = new HmacDpopNonceProvider(optsA, time); var providerB = new HmacDpopNonceProvider(optsB, time); var nonceA = providerA.IssueNonce(); providerB.ValidateNonce(nonceA).Should().BeFalse( "nonces signed with secret-A must not validate against provider with secret-B"); } [Fact] public void ValidateNonce_Empty_Or_Garbage_Returns_False() { var (sut, _) = BuildSut(); sut.ValidateNonce("").Should().BeFalse(); sut.ValidateNonce("not-base64url!").Should().BeFalse(); sut.ValidateNonce("AAAA").Should().BeFalse("payload too short"); } } Path: redb-identity/tests/redb.Identity.Tests/DynamicRegistration/ClientRegistrationManagementProcessorTests.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/DynamicRegistration/ClientRegistrationManagementProcessorTests.cs ---- using System.Security.Cryptography; using System.Text; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Registration; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.DynamicRegistration; /// /// Z2 (RFC 7592): Unit tests for . /// Exercises read/update/delete via operation header plus RFC 7592 §3 security: /// missing/wrong/non-DCR RAT → 401; unknown client → 404; RAT verified in fixed time; /// client_secret NEVER echoed back on read. /// public class ClientRegistrationManagementProcessorTests { private const string Token = "test-registration-access-token-abcdef1234567890"; private readonly IOpenIddictApplicationManager _manager = Substitute.For(); private readonly IRedbService _redb = Substitute.For(); private static string Sha256Hex(string s) { var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(s)); var sb = new StringBuilder(bytes.Length * 2); foreach (var b in bytes) sb.Append(b.ToString("x2")); return sb.ToString(); } private ClientRegistrationManagementProcessor CreateProcessor() { var services = new ServiceCollection(); services.AddSingleton(_manager); services.AddSingleton(_redb); var sp = services.BuildServiceProvider(); var ctx = Substitute.For(); ctx.GetServiceProvider().Returns(sp); // NSubstitute auto-mocks interface return types — pin GetFromRegistry to null so // GetIdentityService falls through to the host SP instead of an empty auto-mocked scope. ctx.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); ctx.GetService().Returns(_redb); return new ClientRegistrationManagementProcessor(ctx); } private static TestExchange MakeExchange(string operation, string? clientId, string? bearer = Token) { var ex = new TestExchange(); ex.In.Headers["operation"] = operation; if (clientId is not null) ex.In.Headers["client_id"] = clientId; if (bearer is not null) ex.In.Headers["access_token"] = bearer; return ex; } private RedbObject ApplicationWithStoredHash( string clientId = "client-123", string? redirectUri = "https://app.example.com/cb", bool hasDcrHash = true) { var app = new RedbObject { name = "My App", Props = new ApplicationProps { ClientId = clientId, ClientType = "public", RedirectUris = redirectUri is null ? null : [redirectUri], ApplicationType = "web", RegistrationAccessTokenHash = hasDcrHash ? Sha256Hex(Token) : null } }; _manager.FindByClientIdAsync(clientId, Arg.Any()) .Returns(new ValueTask(app)); return app; } // ── Auth failures ── [Fact] public async Task Missing_ClientId_Returns_400() { var proc = CreateProcessor(); var ex = MakeExchange("read", clientId: null); await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); } [Fact] public async Task Missing_Bearer_Returns_401() { var proc = CreateProcessor(); var ex = MakeExchange("read", "client-123", bearer: null); await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); var body = (IDictionary)ex.Out.Body!; body["error"]!.ToString().Should().Be("invalid_token"); } [Fact] public async Task Unknown_Client_Returns_404() { _manager.FindByClientIdAsync(Arg.Any(), Arg.Any()) .Returns(new ValueTask((object?)null)); var proc = CreateProcessor(); var ex = MakeExchange("read", "does-not-exist"); await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(404); var body = (IDictionary)ex.Out.Body!; body["error"]!.ToString().Should().Be("invalid_client_id"); } [Fact] public async Task Client_Without_Dcr_Hash_Returns_401() { ApplicationWithStoredHash(hasDcrHash: false); var proc = CreateProcessor(); var ex = MakeExchange("read", "client-123"); await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); var body = (IDictionary)ex.Out.Body!; body["error"]!.ToString().Should().Be("invalid_token"); body["error_description"]!.ToString().Should().Contain("not eligible"); } [Fact] public async Task Wrong_Bearer_Returns_401() { ApplicationWithStoredHash(); var proc = CreateProcessor(); var ex = MakeExchange("read", "client-123", bearer: "not-the-real-token"); await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); var body = (IDictionary)ex.Out.Body!; body["error"]!.ToString().Should().Be("invalid_token"); } [Fact] public async Task Authorization_Header_Accepted_As_Fallback() { ApplicationWithStoredHash(); var proc = CreateProcessor(); var ex = MakeExchange("read", "client-123", bearer: null); ex.In.Headers["Authorization"] = $"Bearer {Token}"; await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(200); } // ── Read ── [Fact] public async Task Read_Returns_Metadata_Without_Secrets() { var app = ApplicationWithStoredHash(); app.Props.ClientSecret = "super-secret-should-not-leak"; var proc = CreateProcessor(); var ex = MakeExchange("read", "client-123"); await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(200); var body = (IDictionary)ex.Out.Body!; body["client_id"]!.ToString().Should().Be("client-123"); body["client_name"]!.ToString().Should().Be("My App"); body.ContainsKey("client_secret").Should().BeFalse("RFC 7592 §2.3 — client_secret MUST NOT be returned on GET"); body.ContainsKey("registration_access_token").Should().BeFalse("RAT is one-shot at creation — never echoed"); var redirs = (System.Collections.Generic.IEnumerable)((System.Text.Json.JsonElement)body["redirect_uris"]!).EnumerateArray().Cast(); redirs.Select(o => o!.ToString()).Should().ContainSingle().Which.Should().Be("https://app.example.com/cb"); } [Theory] [InlineData("public", null, null, "none")] [InlineData("confidential", "hashed-secret", null, "client_secret_basic")] [InlineData("confidential", null, "https://keys.example.com/jwks", "private_key_jwt")] public async Task Read_Answers_The_Auth_Method_And_Keys_As_Stored(string clientType, string? secret, string? jwksUri, string method) { var app = ApplicationWithStoredHash(); app.Props.ClientType = clientType; app.Props.ClientSecret = secret; app.Props.JwksUri = jwksUri; app.Props.RequestObjectSigningAlg = "PS256"; var ex = MakeExchange("read", "client-123"); await CreateProcessor().Process(ex); var body = (IDictionary)ex.Out!.Body!; body["token_endpoint_auth_method"]!.ToString().Should().Be(method); body["request_object_signing_alg"]!.ToString().Should().Be("PS256"); if (jwksUri is null) body.ContainsKey("jwks_uri").Should().BeFalse(); else body["jwks_uri"]!.ToString().Should().Be(jwksUri); } // ── Update ── [Fact] public async Task Update_Persists_Changes_And_Returns_Updated_Metadata() { var app = ApplicationWithStoredHash(); RedbObject? savedApp = null; _redb.SaveAsync(Arg.Do>(r => savedApp = r)) .Returns(Task.FromResult(1L)); var proc = CreateProcessor(); var ex = MakeExchange("update", "client-123"); ex.In.Body = new DynamicRegistrationRequest { ClientName = "Renamed App", RedirectUris = ["https://new.example.com/cb"] }; await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(200); savedApp.Should().BeSameAs(app); savedApp!.name.Should().Be("Renamed App"); savedApp.Props.RedirectUris.Should().BeEquivalentTo(["https://new.example.com/cb"]); var body = (IDictionary)ex.Out.Body!; body["client_name"]!.ToString().Should().Be("Renamed App"); ((System.Text.Json.JsonElement)body["redirect_uris"]!).EnumerateArray() .Select(e => e.GetString()).Should().BeEquivalentTo(["https://new.example.com/cb"]); ex.Properties["identity-event-type"].Should().Be(IdentityAuditEventIds.ClientUpdated); } [Fact] public async Task Update_Accepts_Json_String_Body() { ApplicationWithStoredHash(); _redb.SaveAsync(Arg.Any>()).Returns(Task.FromResult(1L)); var proc = CreateProcessor(); var ex = MakeExchange("update", "client-123"); ex.In.Body = """{"client_name":"From Json","redirect_uris":["https://json.example.com/cb"]}"""; await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(200); var body = (IDictionary)ex.Out.Body!; body["client_name"]!.ToString().Should().Be("From Json"); } [Fact] public async Task Update_With_Invalid_Body_Returns_400() { ApplicationWithStoredHash(); var proc = CreateProcessor(); var ex = MakeExchange("update", "client-123"); ex.In.Body = 42; // unsupported type await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); var body = (IDictionary)ex.Out.Body!; body["error"]!.ToString().Should().Be("invalid_client_metadata"); } // ── Delete ── [Fact] public async Task Delete_Calls_Manager_DeleteAsync_And_Returns_204() { var app = ApplicationWithStoredHash(); var proc = CreateProcessor(); var ex = MakeExchange("delete", "client-123"); await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(204); await _manager.Received(1).DeleteAsync(app, Arg.Any()); ex.Properties["identity-event-type"].Should().Be(IdentityAuditEventIds.ClientDeleted); } // ── Unknown operation ── [Fact] public async Task Unknown_Operation_Returns_400() { ApplicationWithStoredHash(); var proc = CreateProcessor(); var ex = MakeExchange("explode", "client-123"); await proc.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); var body = (IDictionary)ex.Out.Body!; body["error"]!.ToString().Should().Be("invalid_request"); } } Path: redb-identity/tests/redb.Identity.Tests/DynamicRegistration/DynamicRegistrationProcessorTests.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/DynamicRegistration/DynamicRegistrationProcessorTests.cs ---- using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NSubstitute; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Registration; using redb.Identity.Contracts.Configuration; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.DynamicRegistration; public class DynamicRegistrationProcessorTests { private readonly IOpenIddictApplicationManager _manager = Substitute.For(); private readonly IRedbService _redb = Substitute.For(); private readonly RedbIdentityOptions _opts = new() { Features = new IdentityFeatureFlags { EnableDynamicRegistration = true }, DynamicRegistrationAllowedGrantTypes = ["authorization_code", "refresh_token"], DynamicRegistrationAllowedScopes = ["openid", "profile", "email", "offline_access"] }; private DynamicRegistrationProcessor CreateProcessor(RedbIdentityOptions? options = null) { var services = new ServiceCollection(); services.AddSingleton(_manager); services.AddSingleton(_redb); var sp = services.BuildServiceProvider(); var context = Substitute.For(); context.GetServiceProvider().Returns(sp); // NSubstitute auto-mocks interface return types — pin GetFromRegistry to null so // GetIdentityService falls through to the host SP instead of an empty auto-mocked scope. context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); // Z2: AggregateProcessor calls context.GetRedbService(null, exchange) after CreateAsync // to persist the RAT hash — route the request through the context.GetService fallback. context.GetService().Returns(_redb); return new DynamicRegistrationProcessor(context, Options.Create(options ?? _opts)); } private static TestExchange CreateExchange(DynamicRegistrationRequest? body = null) { var exchange = new TestExchange(); exchange.In.Body = body; return exchange; } private void SetupManager() { // Production pipeline (post-refactor) splits manager.CreateAsync(descriptor, ct) into: // 1. PopulateAsync(app, descriptor, ct) — copies descriptor → app.Props // 2. app.Props.RegistrationAccessTokenHash = ratHash // 3. CreateAsync(app, [secret,] ct) — single redb persist with hash already set // Mocks must be wired against this split, otherwise nothing is invoked and Received(...) // assertions over the legacy CreateAsync(descriptor, ct) overload silently fail. _manager.PopulateAsync( Arg.Any(), Arg.Any(), Arg.Any()) .Returns(ci => { // Mirror the production OpenIddict store: when PopulateAsync runs, it copies // descriptor metadata onto the app envelope so subsequent persistence has it. if (ci.Arg() is RedbObject ro) { var d = ci.Arg(); ro.Props.ClientId = d.ClientId; ro.Props.ClientType = d.ClientType; ro.Props.ConsentType = d.ConsentType; ro.Props.ApplicationType = d.ApplicationType; ro.Props.Permissions = d.Permissions.ToArray(); ro.Props.Requirements = d.Requirements.ToArray(); ro.Props.RedirectUris = d.RedirectUris.Select(u => u.AbsoluteUri).ToArray(); ro.Props.PostLogoutRedirectUris = d.PostLogoutRedirectUris.Select(u => u.AbsoluteUri).ToArray(); } return ValueTask.CompletedTask; }); _manager.CreateAsync(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(ValueTask.CompletedTask); _manager.CreateAsync(Arg.Any(), Arg.Any()) .Returns(ValueTask.CompletedTask); // Z2: processor re-reads the created application after CreateAsync to persist the RAT hash. _manager.FindByClientIdAsync(Arg.Any(), Arg.Any()) .Returns(ci => new ValueTask(new RedbObject { Props = new ApplicationProps { ClientId = ci.Arg() } })); } // ── Happy path ── [Fact] public async Task Register_MinimalRequest_ReturnsClientCredentials() { SetupManager(); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], ClientName = "My SPA" }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body.Should().NotBeNull(); body!["client_id"].Should().NotBeNull(); body["client_secret"].Should().NotBeNull(); body["client_name"]!.ToString().Should().Be("My SPA"); body["token_endpoint_auth_method"]!.ToString().Should().Be("client_secret_basic"); body["application_type"]!.ToString().Should().Be("web"); exchange.Out.Headers["redbHttp.ResponseCode"].Should().Be(201); exchange.Properties["identity-event-type"].Should().Be("ClientRegistered"); } [Fact] public async Task Register_PublicClient_NoSecret() { SetupManager(); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], TokenEndpointAuthMethod = "none", ClientName = "Public App" }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body.Should().NotBeNull(); body!["client_id"].Should().NotBeNull(); body.ContainsKey("client_secret").Should().BeFalse("public clients don't get secrets"); body["token_endpoint_auth_method"]!.ToString().Should().Be("none"); exchange.Out.Headers["redbHttp.ResponseCode"].Should().Be(201); } [Fact] public async Task Register_WithScopes_EchoedInResponse() { SetupManager(); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], Scope = "openid profile email" }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["scope"]!.ToString().Should().Be("openid profile email"); exchange.Out.Headers["redbHttp.ResponseCode"].Should().Be(201); } [Fact] public async Task Register_WithGrantTypes_EchoedInResponse() { SetupManager(); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], GrantTypes = ["authorization_code", "refresh_token"] }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body.Should().NotBeNull(); // grant_types comes back as JsonElement from the serialization round-trip exchange.Out.Headers["redbHttp.ResponseCode"].Should().Be(201); } [Fact] public async Task Register_NativeApp_SetsApplicationType() { // RFC 8252 (OAuth 2.0 for Native Apps, BCP 212): // - private-use URI scheme redirect (§7.1) — "com.example.app://callback" // - application_type=native (per OIDC Dynamic Client Registration §2 + // RFC 8252 §8.4 — native apps SHOULD be registered as public clients) // - token_endpoint_auth_method=none (RFC 8252 §8.4 — native apps are // public clients, no client_secret). SetupManager(); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["com.example.app://callback"], ApplicationType = "native", TokenEndpointAuthMethod = "none" }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["application_type"]!.ToString().Should().Be("native"); exchange.Out.Headers["redbHttp.ResponseCode"].Should().Be(201); } [Fact] public async Task Register_CreatesApp_WithCorrectPermissions() { SetupManager(); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], GrantTypes = ["authorization_code", "refresh_token"], Scope = "openid profile" }); await processor.Process(exchange); await _manager.Received(1).PopulateAsync( Arg.Any(), Arg.Is(d => d.ClientType == "confidential" && d.ConsentType == "implicit" && d.Permissions.Contains("ept:token") && d.Permissions.Contains("ept:authorization") && d.Permissions.Contains("gt:authorization_code") && d.Permissions.Contains("gt:refresh_token") && d.Permissions.Contains("scp:openid") && d.Permissions.Contains("scp:profile") && d.Requirements.Contains("ft:pkce") ), Arg.Any()); } [Fact] public async Task Register_ClientSecretPost_ReturnsSecretAndConfidentialType() { SetupManager(); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], TokenEndpointAuthMethod = "client_secret_post" }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["client_secret"].Should().NotBeNull(); body["token_endpoint_auth_method"]!.ToString().Should().Be("client_secret_post"); exchange.Out.Headers["redbHttp.ResponseCode"].Should().Be(201); } [Fact] public async Task Register_SetsClientIdIssuedAt() { SetupManager(); var processor = CreateProcessor(); var before = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; var issuedAtElement = (System.Text.Json.JsonElement)body!["client_id_issued_at"]!; var issuedAt = issuedAtElement.GetInt64(); issuedAt.Should().BeGreaterThanOrEqualTo(before); } // ── Validation errors ── [Fact] public async Task Register_NullBody_ReturnsError() { var processor = CreateProcessor(); var exchange = new TestExchange(); exchange.In.Body = null; await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_client_metadata"); } [Fact] public async Task Register_InvalidJson_ReturnsError() { var processor = CreateProcessor(); var exchange = new TestExchange(); exchange.In.Body = "not-valid-json{{{"; await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_client_metadata"); } [Fact] public async Task Register_DisallowedGrantType_ReturnsError() { var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { GrantTypes = ["client_credentials"], RedirectUris = ["https://app.example.com/callback"] }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_client_metadata"); body["error_description"]!.ToString().Should().Contain("client_credentials"); } [Fact] public async Task Register_DisallowedScope_ReturnsError() { var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], Scope = "openid identity:manage" }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_client_metadata"); body["error_description"]!.ToString().Should().Contain("identity:manage"); } [Fact] public async Task Register_AuthCodeWithoutRedirectUris_ReturnsError() { var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { GrantTypes = ["authorization_code"] // No redirect_uris }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_redirect_uri"); } [Fact] public async Task Register_InvalidRedirectUri_ReturnsError() { var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["not a uri"] }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_redirect_uri"); } // C5 — RFC 6749 §3.1.2 / OAuth 2.1 §4.1: wildcards and fragments must be rejected. [Theory] [InlineData("https://*.example.com/cb")] [InlineData("https://app.example.com/*")] [InlineData("https://app.example.com/cb#frag")] public async Task Register_RedirectUriWithWildcardOrFragment_ReturnsError(string uri) { var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = [uri] }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_redirect_uri"); } [Fact] public async Task Register_PostLogoutRedirectUriWithWildcard_ReturnsError() { var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], PostLogoutRedirectUris = ["https://*.example.com/logout"] }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_client_metadata"); } [Fact] public async Task Register_InvalidApplicationType_ReturnsError() { var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], ApplicationType = "desktop" }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_client_metadata"); body["error_description"]!.ToString().Should().Contain("application_type"); } [Fact] public async Task Register_UnsupportedAuthMethod_ReturnsError() { var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], TokenEndpointAuthMethod = "private_key_jwt" }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_client_metadata"); body["error_description"]!.ToString().Should().Contain("private_key_jwt"); } // ── Initial access token ── [Fact] public async Task Register_WithTokenRequired_ValidToken_Succeeds() { SetupManager(); var opts = new RedbIdentityOptions { Features = new IdentityFeatureFlags { EnableDynamicRegistration = true }, DynamicRegistrationInitialAccessToken = "my-secret-token" }; var processor = CreateProcessor(opts); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); exchange.In.Headers["access_token"] = "my-secret-token"; await processor.Process(exchange); exchange.Out!.Headers["redbHttp.ResponseCode"].Should().Be(201); } [Fact] public async Task Register_WithTokenRequired_MissingToken_Returns401() { var opts = new RedbIdentityOptions { Features = new IdentityFeatureFlags { EnableDynamicRegistration = true }, DynamicRegistrationInitialAccessToken = "my-secret-token" }; var processor = CreateProcessor(opts); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_token"); exchange.Out.Headers["redbHttp.ResponseCode"].Should().Be(401); } [Fact] public async Task Register_WithTokenRequired_WrongToken_Returns401() { var opts = new RedbIdentityOptions { Features = new IdentityFeatureFlags { EnableDynamicRegistration = true }, DynamicRegistrationInitialAccessToken = "my-secret-token" }; var processor = CreateProcessor(opts); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); exchange.In.Headers["access_token"] = "wrong-token"; await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_token"); exchange.Out.Headers["redbHttp.ResponseCode"].Should().Be(401); } [Fact] public async Task Register_WithTokenRequired_AuthorizationHeader_Succeeds() { SetupManager(); var opts = new RedbIdentityOptions { Features = new IdentityFeatureFlags { EnableDynamicRegistration = true }, DynamicRegistrationInitialAccessToken = "my-secret-token" }; var processor = CreateProcessor(opts); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); exchange.In.Headers["Authorization"] = "Bearer my-secret-token"; await processor.Process(exchange); exchange.Out!.Headers["redbHttp.ResponseCode"].Should().Be(201); } // ── JSON body parsing ── [Fact] public async Task Register_JsonStringBody_ParsedCorrectly() { SetupManager(); var processor = CreateProcessor(); var exchange = new TestExchange(); exchange.In.Body = """{"redirect_uris":["https://app.example.com/callback"],"client_name":"JSON App"}"""; await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["client_name"]!.ToString().Should().Be("JSON App"); exchange.Out.Headers["redbHttp.ResponseCode"].Should().Be(201); } [Fact] public async Task Register_JsonBytesBody_ParsedCorrectly() { SetupManager(); var processor = CreateProcessor(); var exchange = new TestExchange(); exchange.In.Body = System.Text.Encoding.UTF8.GetBytes( """{"redirect_uris":["https://app.example.com/callback"],"client_name":"Bytes App"}"""); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["client_name"]!.ToString().Should().Be("Bytes App"); exchange.Out.Headers["redbHttp.ResponseCode"].Should().Be(201); } // ── Defaults ── [Fact] public async Task Register_NoGrantTypes_DefaultsToAuthorizationCode() { SetupManager(); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); await processor.Process(exchange); // Verify PKCE requirement was set (only for authorization_code) await _manager.Received(1).PopulateAsync( Arg.Any(), Arg.Is(d => d.Requirements.Contains("ft:pkce") && d.Permissions.Contains("gt:authorization_code") ), Arg.Any()); } [Fact] public async Task Register_DefaultResponseType_IsCode() { SetupManager(); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); await processor.Process(exchange); await _manager.Received(1).PopulateAsync( Arg.Any(), Arg.Is(d => d.Permissions.Contains("rst:code") ), Arg.Any()); } [Fact] public async Task Register_InvalidPostLogoutRedirectUri_ReturnsError() { var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], PostLogoutRedirectUris = ["not a uri"] }); await processor.Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_client_metadata"); } [Fact] public async Task Register_NoTokenRequired_Succeeds_WithoutToken() { SetupManager(); // Default opts have no DynamicRegistrationInitialAccessToken var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); await processor.Process(exchange); exchange.Out!.Headers["redbHttp.ResponseCode"].Should().Be(201); } // ── Z1: Registration Access Token (RFC 7591 §3.2.1 / RFC 7592) ── private static string? GetBodyString(IExchange exchange, string key) { var dict = exchange.Out!.Body as IDictionary; if (dict is null || !dict.TryGetValue(key, out var raw) || raw is null) return null; if (raw is System.Text.Json.JsonElement je) return je.ValueKind == System.Text.Json.JsonValueKind.String ? je.GetString() : je.ToString(); return raw.ToString(); } [Fact] public async Task Register_Response_Includes_RegistrationAccessToken_And_ClientUri() { SetupManager(); var opts = new RedbIdentityOptions { Features = new IdentityFeatureFlags { EnableDynamicRegistration = true }, Issuer = new Uri("https://id.example.com"), DynamicRegistrationAllowedGrantTypes = ["authorization_code"], DynamicRegistrationAllowedScopes = ["openid"] }; var processor = CreateProcessor(opts); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); await processor.Process(exchange); exchange.Out!.Headers["redbHttp.ResponseCode"].Should().Be(201); var token = GetBodyString(exchange, "registration_access_token"); token.Should().NotBeNullOrWhiteSpace( "RFC 7591 §3.2.1 — response MUST include registration_access_token when management is supported"); token!.Length.Should().BeGreaterThan(32, "token must carry enough entropy for OWASP ASVS 2.3.1"); var uri = GetBodyString(exchange, "registration_client_uri"); uri.Should().NotBeNullOrWhiteSpace(); uri!.Should().StartWith("https://id.example.com/connect/register/"); var clientId = GetBodyString(exchange, "client_id")!; uri.Should().EndWith(Uri.EscapeDataString(clientId)); } [Fact] public async Task Register_Persists_Sha256_Hash_Of_RegistrationAccessToken() { // Arrange: capture the app envelope passed to CreateAsync to inspect RegistrationAccessTokenHash. // Production sets app.Props.RegistrationAccessTokenHash BEFORE calling CreateAsync(app, …), // so capturing the reference is sufficient (no separate _redb.SaveAsync round-trip). SetupManager(); RedbObject? persisted = null; _manager.CreateAsync( Arg.Do(o => persisted = o as RedbObject ?? persisted), Arg.Any(), Arg.Any()) .Returns(ValueTask.CompletedTask); _manager.CreateAsync( Arg.Do(o => persisted = o as RedbObject ?? persisted), Arg.Any()) .Returns(ValueTask.CompletedTask); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); // Act await processor.Process(exchange); // Assert — hash is stored, NOT the token (OWASP A02:2021 — no cleartext credentials at rest). var token = GetBodyString(exchange, "registration_access_token")!; var expectedHash = Convert.ToHexString( System.Security.Cryptography.SHA256.HashData( System.Text.Encoding.UTF8.GetBytes(token))).ToLowerInvariant(); persisted.Should().NotBeNull("processor must persist the application carrying the RAT hash"); persisted!.Props.RegistrationAccessTokenHash.Should().Be(expectedHash); persisted.Props.RegistrationAccessTokenHash.Should().NotContain(token, "the token itself must never be persisted — only its SHA-256 hash"); } [Fact] public async Task Register_ClientUri_Encodes_ClientId_Safely() { // Force a tricky client_id by having the manager's CreateAsync set one with reserved chars. _manager.CreateAsync(Arg.Any(), Arg.Any()) .Returns(ci => { var d = ci.Arg(); d.ClientId = "client/with spaces?x"; return new object(); }); _manager.FindByClientIdAsync(Arg.Any(), Arg.Any()) .Returns(ci => new ValueTask(new RedbObject { Props = new ApplicationProps { ClientId = ci.Arg() } })); var processor = CreateProcessor(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"] }); await processor.Process(exchange); var uri = GetBodyString(exchange, "registration_client_uri")!; uri.Should().NotContain(" ", "path segment must be URL-escaped"); uri.Should().NotContain("?x", "query-like fragments of the client_id must not leak into the URL unescaped"); } // ── request_uris (OIDC DCR §2) ── [Fact] public async Task Register_RequestUris_AreStoredAndEchoed() { SetupManager(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], RequestUris = ["https://app.example.com/ro.jwt#hash", "https://app.example.com/ro.jwt#hash"], }); await CreateProcessor().Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["request_uris"]!.ToString().Should().Contain("https://app.example.com/ro.jwt#hash"); await _manager.Received().CreateAsync( Arg.Is(o => ((RedbObject)o).Props.RequestUris!.SequenceEqual(new[] { "https://app.example.com/ro.jwt#hash" })), Arg.Any(), Arg.Any()); } [Theory] [InlineData("/relative/ro.jwt")] [InlineData("ftp://app.example.com/ro.jwt")] [InlineData("https://user:pw@app.example.com/ro.jwt")] [InlineData("https://app.example.com/*.jwt")] public async Task Register_InvalidRequestUri_IsRefusedAsInvalidClientMetadata(string requestUri) { SetupManager(); var exchange = CreateExchange(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], RequestUris = [requestUri], }); await CreateProcessor().Process(exchange); var body = exchange.Out!.Body as IDictionary; body!["error"]!.ToString().Should().Be("invalid_client_metadata"); } // ── keys and request_object_signing_alg: stored, and answered from storage ── private const string OneKeyJwks = """ {"keys":[{"kty":"RSA","use":"sig","kid":"k1","alg":"RS256", "n":"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw", "e":"AQAB"}]} """; private RedbIdentityOptions LoopbackKeys() { var o = new RedbIdentityOptions { DynamicRegistrationInitialAccessToken = _opts.DynamicRegistrationInitialAccessToken, DynamicRegistrationAllowedGrantTypes = _opts.DynamicRegistrationAllowedGrantTypes, }; o.ClientKeys.AllowPrivateNetworkTargets = true; return o; } private async Task<(IDictionary Body, RedbObject? Stored)> Register( DynamicRegistrationRequest request, RedbIdentityOptions? options = null) { SetupManager(); RedbObject? stored = null; _manager.CreateAsync(Arg.Do(o => stored = (RedbObject)o), Arg.Any()) .Returns(ValueTask.CompletedTask); _manager.CreateAsync(Arg.Do(o => stored = (RedbObject)o), Arg.Any(), Arg.Any()) .Returns(ValueTask.CompletedTask); var exchange = CreateExchange(request); await CreateProcessor(options).Process(exchange); return ((IDictionary)exchange.Out!.Body!, stored); } [Fact] public async Task Register_PrivateKeyJwt_WithJwksUri_StoresAndAnswersTheAddress() { var (body, stored) = await Register(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], TokenEndpointAuthMethod = "private_key_jwt", JsonWebKeySetUri = "https://127.0.0.1/jwks", }, LoopbackKeys()); body.ContainsKey("error").Should().BeFalse(body.TryGetValue("error_description", out var d) ? d?.ToString() : null); stored!.Props.JwksUri.Should().Be("https://127.0.0.1/jwks"); body["jwks_uri"]!.ToString().Should().Be("https://127.0.0.1/jwks"); } [Fact] public async Task Register_SecretClient_WithJwks_StoresIt_ForRequestObjects() { var (body, stored) = await Register(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], JsonWebKeySet = JsonDocument.Parse(OneKeyJwks).RootElement, }); body.ContainsKey("error").Should().BeFalse(); await _manager.Received().PopulateAsync(Arg.Any(), Arg.Is(d => d.JsonWebKeySet != null && d.JsonWebKeySet.Keys.Count == 1), Arg.Any()); body.ContainsKey("jwks").Should().BeTrue("the inline set was stored, so it is answered"); stored.Should().NotBeNull(); } [Fact] public async Task Register_JwksAndJwksUri_Together_AreRefused() { var (body, _) = await Register(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], TokenEndpointAuthMethod = "private_key_jwt", JsonWebKeySet = JsonDocument.Parse(OneKeyJwks).RootElement, JsonWebKeySetUri = "https://127.0.0.1/jwks", }, LoopbackKeys()); body["error"]!.ToString().Should().Be("invalid_client_metadata"); } [Theory] [InlineData("http://127.0.0.1/jwks")] // not https [InlineData("https://169.254.169.254/jwks")] // link-local, refused by the guard public async Task Register_JwksUri_TheKeyFetchWouldRefuse_IsRefusedAtRegistration(string uri) { var (body, stored) = await Register(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], TokenEndpointAuthMethod = "private_key_jwt", JsonWebKeySetUri = uri, }); body["error"]!.ToString().Should().Be("invalid_client_metadata"); stored.Should().BeNull(); } [Fact] public async Task Register_PrivateKeyJwt_WithoutKeys_IsRefused() { var (body, _) = await Register(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], TokenEndpointAuthMethod = "private_key_jwt", }); body["error"]!.ToString().Should().Be("invalid_client_metadata"); } [Theory] [InlineData("PS256", true)] [InlineData("RS256", true)] [InlineData("none", false)] [InlineData("HS256", false)] public async Task Register_RequestObjectSigningAlg_IsStoredWhenAllowed(string alg, bool accepted) { var (body, stored) = await Register(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], RequestObjectSigningAlg = alg, }); if (accepted) { stored!.Props.RequestObjectSigningAlg.Should().Be(alg); body["request_object_signing_alg"]!.ToString().Should().Be(alg); } else { body["error"]!.ToString().Should().Be("invalid_client_metadata"); } } [Theory] [InlineData("https://127.0.0.1/bc-logout")] [InlineData("https://169.254.169.254/bc-logout")] [InlineData("http://203.0.113.10/bc-logout")] public async Task Register_BackchannelLogoutUri_TheGuardRefuses_IsInvalidClientMetadata(string uri) { var (body, stored) = await Register(new DynamicRegistrationRequest { RedirectUris = ["https://app.example.com/callback"], BackchannelLogoutUri = uri, }); body["error"]!.ToString().Should().Be("invalid_client_metadata"); stored.Should().BeNull(); } } Path: redb-identity/tests/redb.Identity.Tests/Embedding/EmbeddingHostChecksTests.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/Embedding/EmbeddingHostChecksTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Module; using Xunit; namespace redb.Identity.Tests.Embedding; /// /// The ways an own host used to start Identity half-configured, without a word: each now fails at /// with a message that names what is missing, before anything /// listens or touches the database. /// public class EmbeddingHostChecksTests { private const string Issuer = "http://localhost:5999/"; private static Func Start(IServiceCollection services, IConfiguration configuration) => async () => { await using var provider = services.BuildServiceProvider(); await using var host = await RedbIdentityHost.StartAsync(provider, configuration, redb.Identity.Http.InitRoute.main); }; private static IServiceCollection Host() { var services = new ServiceCollection(); services.AddLogging(); services.AddRedbIdentityHost(); return services; } private static IConfiguration Config(params (string Key, string? Value)[] overrides) => EmbeddingSmokeTests.Configuration(Issuer, 5999, overrides); [Fact] public async Task Without_AddRedbIdentityHost_the_start_names_it() { // Before: direct-vm consumers failed to start, the error went to the log and discovery answered 500. var services = new ServiceCollection(); services.AddLogging(); (await Start(services, Config()).Should().ThrowAsync()) .WithMessage("*AddRedbIdentityHost()*"); } [Fact] public async Task Without_logging_the_start_names_it() { // Before: a route context without a logger factory swallowed the modules' start-up log. var services = new ServiceCollection(); services.AddRedbIdentityHost(); (await Start(services, Config()).Should().ThrowAsync()) .WithMessage("*AddLogging()*"); } [Fact] public async Task A_missing_issuer_is_named() { // Before: the module started on https://localhost/ and every token carried that issuer. var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { ["Identity:AllowEphemeralKeys"] = "true", ["IdentityTransport:Http:PublicPort"] = "5999", }).Build(); (await Start(Host(), configuration).Should().ThrowAsync()) .WithMessage("*Identity:Issuer*missing*"); } [Fact] public async Task An_issuer_that_is_not_an_absolute_uri_is_named() { (await Start(Host(), Config(("Identity:Issuer", "id.example.com"))).Should().ThrowAsync()) .WithMessage("*Identity:Issuer*id.example.com*"); } [Fact] public async Task No_key_source_is_named() { (await Start(Host(), Config(("Identity:AllowEphemeralKeys", "false"))).Should().ThrowAsync()) .WithMessage("*Identity:UsePropsSigningKeyStore*Identity:AllowEphemeralKeys*"); } [Fact] public async Task A_facade_without_the_transport_section_is_named() { // Before: the HTTP facade listened on its default 8080 while the issuer named another port. var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { ["Identity:Issuer"] = Issuer, ["Identity:AllowEphemeralKeys"] = "true", }).Build(); (await Start(Host(), configuration).Should().ThrowAsync()) .WithMessage("*IdentityTransport*"); } [Fact] public async Task Options_registered_in_the_host_container_are_refused_not_ignored() { // Before: the module ignored them and started on the defaults of the configuration section. var services = Host(); services.AddRedbIdentityServer(new RedbIdentityOptions { Issuer = new Uri(Issuer), AllowEphemeralKeys = true, }); (await Start(services, Config()).Should().ThrowAsync()) .WithMessage("*AddRedbIdentityServer*'Identity' configuration section*"); } } Path: redb-identity/tests/redb.Identity.Tests/Embedding/EmbeddingSmokeTests.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/Embedding/EmbeddingSmokeTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Sockets; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using redb.Core; using redb.Identity.Core; using redb.Identity.Core.Module; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Embedding; /// /// Identity inside a host of its own, with no Tsak worker: the host registers redb, hands the /// configuration sections to a route context and calls the entry points of the modules. /// [Collection("PostgresCollection")] public class EmbeddingSmokeTests { private const string ManagementClientId = "embedding-smoke-mgmt"; private const string ManagementClientSecret = "embedding-smoke-secret"; private readonly ITestOutputHelper _out; public EmbeddingSmokeTests(ITestOutputHelper output) => _out = output; /// /// The host code this test runs is the whole of what an embedding host has to write: logging, redb, /// AddRedbIdentityHost(), then RedbIdentityHost.StartAsync with the configuration and the /// HTTP facade. Disposing the host closes the port. /// [Fact] public async Task One_host_call_runs_identity_in_an_own_host_and_dispose_stops_it() { var port = FreePort(); var issuer = $"http://localhost:{port}/"; var configuration = Configuration(issuer, port); var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(PostgresConnectionString()); services.AddRedbIdentityHost(); await using var provider = services.BuildServiceProvider(); var identity = await RedbIdentityHost.StartAsync(provider, configuration, redb.Identity.Http.InitRoute.main); using var http = new HttpClient { BaseAddress = new Uri(issuer) }; try { await ServesIdentityAsync(http, identity, provider, issuer); } finally { await identity.DisposeAsync(); } // After dispose the port is closed. var afterStop = async () => await http.GetAsync("/.well-known/openid-configuration"); await afterStop.Should().ThrowAsync("disposing the host closes its port"); } internal static IConfiguration Configuration(string issuer, int port, params (string Key, string? Value)[] extra) { var values = new Dictionary { ["Identity:Issuer"] = issuer, ["Identity:AllowEphemeralKeys"] = "true", ["Identity:DisableAccessTokenEncryption"] = "true", // Loopback only, so the test host does not make the OS firewall ask about the test binary. ["IdentityTransport:Http:Host"] = "localhost", ["IdentityTransport:Http:PublicPort"] = port.ToString(System.Globalization.CultureInfo.InvariantCulture), }; foreach (var (key, value) in extra) values[key] = value; return new ConfigurationBuilder().AddInMemoryCollection(values).Build(); } private async Task ServesIdentityAsync(HttpClient http, RedbIdentityHost identity, IServiceProvider provider, string issuer) { // Discovery answers with the configured issuer. var discovery = await http.GetAsync("/.well-known/openid-configuration"); var discoveryBody = await discovery.Content.ReadAsStringAsync(); _out.WriteLine($"discovery [{(int)discovery.StatusCode}] {Short(discoveryBody)}"); discovery.StatusCode.Should().Be(HttpStatusCode.OK); JsonDocument.Parse(discoveryBody).RootElement.GetProperty("issuer").GetString().Should().Be(issuer); // The start-up created the e-mail unique index. (await EmailIndexCountAsync(provider)).Should().Be(1, "the module's start-up creates UX_users_email"); // A management call without a token is refused. var anonymous = await http.GetAsync("/api/v1/identity/users"); _out.WriteLine($"management without token [{(int)anonymous.StatusCode}]"); anonymous.StatusCode.Should().Be(HttpStatusCode.Unauthorized); // With a token of a client that may ask for the management scope it passes. await SeedManagementClientAsync(identity.Context); var token = await ClientCredentialsTokenAsync(http); using var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "/api/v1/identity/users"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var authorized = await http.SendAsync(request); _out.WriteLine($"management with token [{(int)authorized.StatusCode}] {Short(await authorized.Content.ReadAsStringAsync())}"); authorized.StatusCode.Should().Be(HttpStatusCode.OK); } internal static string PostgresConnectionString() => new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetPostgresConnectionString(); internal static string Short(string text) => text.Length <= 300 ? text : text[..300] + "..."; internal static async Task EmailIndexCountAsync(IServiceProvider provider) { await using var scope = provider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); return TestRedbSetup.SelectedProvider switch { TestRedbSetup.Provider.MsSql => await redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM sys.indexes WHERE name = 'UX_users_email'"), TestRedbSetup.Provider.Postgres => await redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM pg_indexes WHERE indexname = 'UX_users_email'"), _ => await redb.Context.ExecuteScalarAsync( "SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND name='UX_users_email'"), }; } /// /// Registers the client the test asks a management token for. Identity's services live in the /// module's own container; its scope factory is what the module publishes in the context registry. /// internal static async Task SeedManagementClientAsync(redb.Route.Abstractions.IRouteContext context) { var factory = context.GetFromRegistry("identity-sp:default") ?? throw new InvalidOperationException("The module did not publish its scope factory."); await using var scope = factory.CreateAsyncScope(); var manager = scope.ServiceProvider.GetRequiredService(); var existing = await manager.FindByClientIdAsync(ManagementClientId); if (existing is not null) await manager.DeleteAsync(existing); await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = ManagementClientId, ClientSecret = ManagementClientSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "Embedding smoke management client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.Prefixes.Scope + "identity:manage", }, }); } internal static async Task ClientCredentialsTokenAsync(HttpClient http) { var response = await http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = ManagementClientId, ["client_secret"] = ManagementClientSecret, ["scope"] = "identity:manage", })); var body = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) throw new InvalidOperationException($"Token request failed ({(int)response.StatusCode}): {body}"); return JsonDocument.Parse(body).RootElement.GetProperty("access_token").GetString() ?? throw new InvalidOperationException("No access_token in the token response."); } internal static int FreePort() { using var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } } Path: redb-identity/tests/redb.Identity.Tests/Events/AuditSinkFailureMetricTests.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/Events/AuditSinkFailureMetricTests.cs ---- using System.Diagnostics.Metrics; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Core.Metrics; using redb.Identity.Core.Routes.Processors; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Events; /// /// An audit row that could not be written does not stop the event, but it must not vanish into a log /// line either: the failure is counted on the Identity meter, tagged with the event type. /// public class AuditSinkFailureMetricTests { [Fact] public async Task AFailedAuditWrite_IsCounted_AndTheEventGoesOn() { var failures = new List<(long Value, string? EventType)>(); using var listener = new MeterListener(); listener.InstrumentPublished = (instrument, l) => { if (instrument.Meter.Name == IdentityMetrics.MeterName && instrument.Name == "identity.audit.write_failures") l.EnableMeasurementEvents(instrument); }; listener.SetMeasurementEventCallback((_, value, tags, _) => { string? eventType = null; foreach (var tag in tags) if (tag.Key == "event_type") eventType = tag.Value?.ToString(); lock (failures) failures.Add((value, eventType)); }); // A host with the Identity meter and no redb at all: the write cannot succeed. var services = new ServiceCollection(); services.AddSingleton(); await using var provider = services.BuildServiceProvider(); listener.Start(); await using var context = new RouteContext(provider, "audit-sink-failure"); var processor = new AuditRelationalSinkProcessor(context, NullLogger.Instance); var exchange = new Exchange(new Message()); exchange.Out = new Message(); exchange.Out.Headers["event_type"] = "UserCreated"; var act = async () => await processor.Process(exchange); await act.Should().NotThrowAsync("audit persistence must never stop the originating flow"); lock (failures) { failures.Should().ContainSingle(); failures[0].Value.Should().Be(1); failures[0].EventType.Should().Be("UserCreated"); } } } Path: redb-identity/tests/redb.Identity.Tests/Events/EventDispatchTests.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/Events/EventDispatchTests.cs ---- using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Logging; using NSubstitute; using redb.Identity.Contracts.Events; using redb.Identity.Core.Configuration; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Events; public class EventDispatchTests { private readonly ILogger _logger = Substitute.For(); private readonly EventDispatchProcessor _processor; public EventDispatchTests() { _processor = new EventDispatchProcessor(_logger); } private static IdentityEvent DeserializeEvent(IExchange exchange) { // Body now carries the typed IdentityEvent directly — wire-encoding happens at // the transport boundary (.Marshal step or content-type-aware producer). return exchange.Out!.Body.Should().BeOfType().Subject; } [Fact] public async Task TokenIssued_CreatesTypedEvent() { var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "TokenIssued"; exchange.Properties["identity-event-data"] = new Dictionary { ["clientId"] = "my-app", ["grantType"] = "client_credentials" }; exchange.In.Headers["client_id"] = "my-app"; await _processor.Process(exchange); var evt = DeserializeEvent(exchange); evt.EventType.Should().Be("TokenIssued"); evt.ClientId.Should().Be("my-app"); evt.Details.Should().ContainKey("clientId"); exchange.Out!.Headers["event-type"].Should().Be("TokenIssued"); } [Fact] public async Task ClientRegistered_CreatesTypedEvent() { var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "ClientRegistered"; exchange.Properties["identity-event-data"] = new { ClientId = "new-app" }; await _processor.Process(exchange); var evt = DeserializeEvent(exchange); evt.EventType.Should().Be("ClientRegistered"); evt.Details.Should().ContainKey("ClientId"); } [Fact] public async Task NoEventType_NoOp() { var exchange = new TestExchange(); await _processor.Process(exchange); exchange.Out.Should().BeNull(); exchange.IsStopped.Should().BeTrue("the raw request copy must not reach the sink, webhooks or targets"); } // ── What leaves the dispatcher: the event and its own headers, nothing of the request ── private static readonly string[] EventHeaders = ["event-type", "event_id", "event_type", "timestamp", "user_id", "client_id", "actor_subject", "ip_address", "user_agent", "details"]; /// The WireTap copy of a client-credentials POST /connect/token, as the HTTP facade hands it over. private static TestExchange TokenRequestCopy() { var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "TokenIssued"; exchange.Properties["identity-event-data"] = new Dictionary { ["GrantType"] = "client_credentials" }; exchange.In.Body = "grant_type=client_credentials&client_id=app1&client_secret=s3cret"; exchange.In.Headers["redbHttp.Method"] = "POST"; exchange.In.Headers["redbHttp.Path"] = "/connect/token"; exchange.In.Headers["redbHttp.Url"] = "https://id.example/connect/token"; exchange.In.Headers["redbHttp.RemoteAddress"] = "10.1.2.3"; exchange.In.Headers["Host"] = "id.example"; exchange.In.Headers["Content-Length"] = "64"; exchange.In.Headers["Cookie"] = ".redb.session=abc"; exchange.In.Headers["Authorization"] = "Bearer eyJhbGciOi.token.sig"; exchange.In.Headers["User-Agent"] = "curl/8.0"; exchange.In.Headers["grant_type"] = "client_credentials"; exchange.In.Headers["client_id"] = "app1"; exchange.In.Headers["client_secret"] = "s3cret"; // The business route's response is on Out of the copy. exchange.Out = new TestMessage { Body = "{\"access_token\":\"eyJhbGciOi.token.sig\"}" }; exchange.Out.Headers["Set-Cookie"] = ".redb.session=abc"; return exchange; } [Fact] public async Task TokenRequest_EventCarriesOnlyEventHeaders() { var exchange = TokenRequestCopy(); await _processor.Process(exchange); exchange.IsStopped.Should().BeFalse(); exchange.In.Headers.Should().BeEmpty("the request's headers must not survive into the event exchange"); exchange.In.Body.Should().BeNull(); exchange.Out!.Headers.Keys.Should().BeEquivalentTo(EventHeaders); exchange.Out.Body.Should().BeOfType(); // What the request contributed is the event's own fields, taken before the request was dropped. exchange.Out.Headers["client_id"].Should().Be("app1"); exchange.Out.Headers["ip_address"].Should().Be("10.1.2.3"); exchange.Out.Headers["user_agent"].Should().Be("curl/8.0"); JsonSerializer.Serialize(exchange.Out.Body).Should().NotContain("s3cret").And.NotContain("eyJhbGciOi"); } [Fact] public async Task TokenRequest_ThroughThePipeline_NextStepSeesOnlyTheEvent() { // The events route is a pipeline: dispatch, then sink / webhooks / multicast. The pipeline merges // Out headers into In, so this is where the request's headers used to ride along. IMessage? seen = null; var pipeline = new redb.Route.Processors.PipelineProcessor(); pipeline.Add(_processor); pipeline.Add(new CaptureProcessor(m => seen = m)); await pipeline.Process(TokenRequestCopy()); seen.Should().NotBeNull(); seen!.Headers.Keys.Should().BeEquivalentTo(EventHeaders); seen.Body.Should().BeOfType(); } [Fact] public async Task NoEventType_PipelineGoesNoFurther() { var reached = false; var pipeline = new redb.Route.Processors.PipelineProcessor(); pipeline.Add(_processor); pipeline.Add(new CaptureProcessor(_ => reached = true)); var exchange = TokenRequestCopy(); exchange.Properties.Remove("identity-event-type"); await pipeline.Process(exchange); reached.Should().BeFalse("a request copy without an event must not be delivered anywhere"); } private sealed class CaptureProcessor(Action capture) : IProcessor { public Task Process(IExchange exchange, CancellationToken ct = default) { capture(exchange.In); return Task.CompletedTask; } } [Fact] public async Task Event_ContainsTimestamp() { var before = DateTimeOffset.UtcNow; var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "UserCreated"; await _processor.Process(exchange); var evt = DeserializeEvent(exchange); evt.Timestamp.Should().BeOnOrAfter(before); evt.Timestamp.Should().BeOnOrBefore(DateTimeOffset.UtcNow); } [Fact] public async Task Event_PicksUpActorHeaders() { var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "PasswordChanged"; exchange.In.Headers["client_id"] = "admin-panel"; exchange.In.Headers["user_id"] = "42"; await _processor.Process(exchange); var evt = DeserializeEvent(exchange); evt.ClientId.Should().Be("admin-panel"); evt.UserId.Should().Be("42"); } [Fact] public async Task Event_NullData_DetailsIsNull() { var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "ScopeDeleted"; await _processor.Process(exchange); var evt = DeserializeEvent(exchange); evt.Details.Should().BeNull(); } // ── Audit-specific tests ── [Fact] public async Task Event_PicksUpIpAddressAndUserAgent() { var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "TokenIssued"; exchange.In.Headers["ip_address"] = "192.168.1.100"; exchange.In.Headers["user_agent"] = "Mozilla/5.0"; await _processor.Process(exchange); var evt = DeserializeEvent(exchange); evt.IpAddress.Should().Be("192.168.1.100"); evt.UserAgent.Should().Be("Mozilla/5.0"); } [Fact] public async Task Event_SetsSqlParamHeaders() { var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "UserCreated"; exchange.Properties["identity-event-data"] = new Dictionary { ["Login"] = "testuser" }; exchange.In.Headers["client_id"] = "admin"; exchange.In.Headers["user_id"] = "7"; exchange.In.Headers["ip_address"] = "10.0.0.1"; exchange.In.Headers["user_agent"] = "curl/8.0"; await _processor.Process(exchange); exchange.Out!.Headers["event_id"].Should().NotBeNull(); exchange.Out.Headers["event_type"].Should().Be("UserCreated"); exchange.Out.Headers["timestamp"].Should().BeOfType(); exchange.Out.Headers["user_id"].Should().Be("7"); exchange.Out.Headers["client_id"].Should().Be("admin"); exchange.Out.Headers["ip_address"].Should().Be("10.0.0.1"); exchange.Out.Headers["user_agent"].Should().Be("curl/8.0"); exchange.Out.Headers["details"].Should().BeOfType() .Which.Should().Contain("Login"); } [Fact] public async Task Event_NullFields_SetDbNull() { var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "ScopeDeleted"; // No user_id, client_id, ip_address, user_agent, details await _processor.Process(exchange); exchange.Out!.Headers["user_id"].Should().Be(DBNull.Value); exchange.Out.Headers["client_id"].Should().Be(DBNull.Value); exchange.Out.Headers["ip_address"].Should().Be(DBNull.Value); exchange.Out.Headers["user_agent"].Should().Be(DBNull.Value); exchange.Out.Headers["details"].Should().Be(DBNull.Value); } [Fact] public async Task Filter_WildcardAllowsAll() { var opts = new IdentityAuditOptions { Enabled = true, Filter = "*" }; var processor = new EventDispatchProcessor(_logger, opts); var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "TokenIssued"; await processor.Process(exchange); exchange.Out.Should().NotBeNull(); } [Fact] public async Task Filter_WhitelistAllowsMatching() { var opts = new IdentityAuditOptions { Enabled = true, Filter = "TokenIssued,UserLoggedOut" }; var processor = new EventDispatchProcessor(_logger, opts); var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "TokenIssued"; await processor.Process(exchange); exchange.Out.Should().NotBeNull(); } [Fact] public async Task Filter_WhitelistBlocksNonMatching() { var opts = new IdentityAuditOptions { Enabled = true, Filter = "TokenIssued,UserLoggedOut" }; var processor = new EventDispatchProcessor(_logger, opts); var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "ScopeCreated"; await processor.Process(exchange); exchange.Out.Should().BeNull(); exchange.IsStopped.Should().BeTrue(); } [Fact] public async Task Filter_DisabledAudit_NoFiltering() { var opts = new IdentityAuditOptions { Enabled = false, Filter = "TokenIssued" }; var processor = new EventDispatchProcessor(_logger, opts); var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "ScopeCreated"; await processor.Process(exchange); // When audit is disabled, filter is not applied — events still flow for ILogger exchange.Out.Should().NotBeNull(); } [Fact] public async Task BodyIsTypedIdentityEvent() { var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "TokenIssued"; exchange.In.Headers["client_id"] = "app1"; await _processor.Process(exchange); // Core MUST NOT pre-serialise: Body is the typed IdentityEvent; // ContentType="application/json" hints downstream marshallers. var evt = exchange.Out!.Body.Should().BeOfType().Subject; evt.EventType.Should().Be("TokenIssued"); evt.ClientId.Should().Be("app1"); exchange.Out!.ContentType.Should().Be("application/json"); } } Path: redb-identity/tests/redb.Identity.Tests/ExternalProvider/ExternalUserProviderTests.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/ExternalProvider/ExternalUserProviderTests.cs ---- using System.Text; using System.Text.Json; using AwesomeAssertions; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.ExternalProvider; /// /// E2E integration tests for SPI. /// Full pipeline: ROPC request → OpenIddict → HandleTokenRequestHandler → LoginService /// (with DI-injected FakeExternalUserProvider) → PostgreSQL → JWT token. /// No direct LoginService calls — everything goes through the real pipeline. /// [Collection("ProductionBootstrap")] public class ExternalUserProviderTests : IDisposable { private readonly ProductionBootstrapFixture _fx; private readonly ITestOutputHelper _out; public ExternalUserProviderTests(ProductionBootstrapFixture fx, ITestOutputHelper output) { _fx = fx; _out = output; } public void Dispose() { // Always clear handlers after each test to prevent cross-contamination _fx.FakeExternalProvider.UserHandlers.Clear(); } private Dictionary RopcBody(string username, string password, string scope = "openid profile email") { return new Dictionary { ["grant_type"] = "password", ["username"] = username, ["password"] = password, ["client_id"] = ProductionBootstrapFixture.TestClientId, ["client_secret"] = ProductionBootstrapFixture.TestClientSecret, ["scope"] = scope }; } private static JsonElement DecodeJwtPayload(string jwt) { var parts = jwt.Split('.'); var json = Encoding.UTF8.GetString(Convert.FromBase64String(PadBase64(parts[1]))); return JsonSerializer.Deserialize(json); } private static string PadBase64(string b64) => (b64.Length % 4) switch { 2 => b64 + "==", 3 => b64 + "=", _ => b64 }; // ───────────────────────────────────────────── // 1. Happy path: external auth → new user → token // ───────────────────────────────────────────── [Fact] public async Task ExternalAuth_NewUser_CreatesUserAndIssuesJwtWithClaims() { var extUsername = $"ext_e2e_a_{Guid.NewGuid():N}"[..20]; _fx.FakeExternalProvider.UserHandlers[extUsername] = password => password == "ext-secret" ? ExternalAuthResult.Success( externalId: $"cn={extUsername},ou=users,dc=corp", displayName: $"Alice {extUsername}", email: $"alice-{extUsername}@corp.example.com", givenName: "Alice", familyName: "External", additionalClaims: new Dictionary { ["department"] = "R&D" }) : ExternalAuthResult.Failed("Wrong password"); // Full ROPC pipeline request var result = await _fx.Request(IdentityEndpoints.Token, RopcBody(extUsername, "ext-secret")); // 1) Token response var response = result.Should().BeOfType>().Subject; response.Should().NotContainKey("error", because: $"ROPC should succeed, got: {response.GetValueOrDefault("error_description")}"); response.Should().ContainKey("access_token"); var accessToken = response["access_token"]!.ToString()!; _out.WriteLine($"access_token length={accessToken.Length}"); // 2) JWT claims (proves IdentityPrincipalBuilder wired the external profile) var claims = DecodeJwtPayload(accessToken); claims.TryGetProperty("sub", out _).Should().BeTrue("JWT must contain sub"); claims.TryGetProperty("name", out var name).Should().BeTrue("JWT must contain name"); name.GetString().Should().Be(extUsername); claims.TryGetProperty("given_name", out var gn).Should().BeTrue("JWT must contain given_name"); gn.GetString().Should().Be("Alice"); claims.TryGetProperty("family_name", out var fn).Should().BeTrue("JWT must contain family_name"); fn.GetString().Should().Be("External"); claims.TryGetProperty("email", out var email).Should().BeTrue("JWT must contain email"); email.GetString().Should().Be($"alice-{extUsername}@corp.example.com"); // 3) DB state (proves LoginService.ResolveExternalUser created user + UserProps) var coreUser = await _fx.Redb.UserProvider.GetUserByLoginAsync(extUsername); coreUser.Should().NotBeNull("local _users row must be created"); coreUser!.Enabled.Should().BeTrue(); coreUser.CodeString.Should().Be("fake-test", "CodeString must store provider name"); var oidcObj = await _fx.Redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync(); oidcObj.Should().NotBeNull("UserProps must be created"); oidcObj!.Props.ExternalIdentities.Should().ContainKey("fake-test"); oidcObj.Props.ExternalIdentities!["fake-test"].Sub.Should().Contain(extUsername); oidcObj.Props.GivenName.Should().Be("Alice"); oidcObj.Props.FamilyName.Should().Be("External"); oidcObj.Props.CustomClaims.Should().ContainKey("department"); oidcObj.Props.CustomClaims!["department"].Should().Be("R&D"); } // ───────────────────────────────────────────── // 2. Repeat login: profile synced, same user ID // ───────────────────────────────────────────── [Fact] public async Task ExternalAuth_SecondLogin_SyncsProfileAndReturnsSameSubject() { var extUsername = $"ext_e2e_b_{Guid.NewGuid():N}"[..20]; _fx.FakeExternalProvider.UserHandlers[extUsername] = password => password == "bob-pass" ? ExternalAuthResult.Success( externalId: $"cn={extUsername},dc=corp", displayName: $"Bob {extUsername}", email: $"bob-v1-{extUsername}@corp.example.com", phone: "+1000000001", givenName: "Bob", familyName: "Original") : ExternalAuthResult.Failed("Wrong password"); // First ROPC — creates user var result1 = await _fx.Request(IdentityEndpoints.Token, RopcBody(extUsername, "bob-pass", "openid profile email phone")); var resp1 = result1.Should().BeOfType>().Subject; resp1.Should().NotContainKey("error"); var sub1 = DecodeJwtPayload(resp1["access_token"]!.ToString()!) .GetProperty("sub").GetString(); _out.WriteLine($"First login sub={sub1}"); // Verify first-login _users state var user1 = await _fx.Redb.UserProvider.GetUserByLoginAsync(extUsername); user1!.Email.Should().Be($"bob-v1-{extUsername}@corp.example.com"); user1.Phone.Should().Be("+1000000001"); // Change profile on external side (email, phone, name all change) _fx.FakeExternalProvider.UserHandlers[extUsername] = password => password == "bob-pass" ? ExternalAuthResult.Success( externalId: $"cn={extUsername},dc=corp", displayName: $"BobUp {extUsername}", email: $"bob-v2-{extUsername}@corp.example.com", phone: "+2000000002", givenName: "Bobby", familyName: "Updated") : ExternalAuthResult.Failed("Wrong password"); // Second ROPC — finds existing user, syncs profile var result2 = await _fx.Request(IdentityEndpoints.Token, RopcBody(extUsername, "bob-pass", "openid profile email phone")); var resp2 = result2.Should().BeOfType>().Subject; resp2.Should().NotContainKey("error"); var sub2 = DecodeJwtPayload(resp2["access_token"]!.ToString()!) .GetProperty("sub").GetString(); sub2.Should().Be(sub1, "second login must return same user"); // JWT claims synced var claims2 = DecodeJwtPayload(resp2["access_token"]!.ToString()!); claims2.GetProperty("given_name").GetString().Should().Be("Bobby"); claims2.GetProperty("family_name").GetString().Should().Be("Updated"); claims2.GetProperty("email").GetString().Should().Be($"bob-v2-{extUsername}@corp.example.com"); // _users row updated (authoritative sync from external) var user2 = await _fx.Redb.UserProvider.GetUserByLoginAsync(extUsername); user2!.Email.Should().Be($"bob-v2-{extUsername}@corp.example.com", "_users.Email must be synced"); user2.Phone.Should().Be("+2000000002", "_users.Phone must be synced"); user2.Name.Should().Be($"BobUp {extUsername}", "_users.Name must be synced"); // UserProps updated — sub is now a GUID, so look up by the local user id. var oidcObj = await _fx.Redb.Query() .WhereRedb(o => o.Key == user2.Id) .FirstOrDefaultAsync(); oidcObj!.value_guid!.Value.ToString("D").Should().Be(sub1, "the public sub claim must equal UserProps.value_guid for the same user"); oidcObj.Props.GivenName.Should().Be("Bobby"); oidcObj.Props.FamilyName.Should().Be("Updated"); oidcObj.Props.EmailVerified.Should().BeTrue(); oidcObj.Props.PhoneNumberVerified.Should().BeTrue(); } // ───────────────────────────────────────────── // 3. Explicit reject: provider returns Failed → no local fallthrough // ───────────────────────────────────────────── [Fact] public async Task ExternalAuth_ExplicitReject_ReturnsAccessDenied_NoFallthrough() { var extUsername = $"ext_e2e_e_{Guid.NewGuid():N}"[..20]; // Provider CLAIMS this user but rejects — must NOT fall through to local _fx.FakeExternalProvider.UserHandlers[extUsername] = _ => ExternalAuthResult.Failed("LDAP bind failed: invalid credentials"); var result = await _fx.Request(IdentityEndpoints.Token, RopcBody(extUsername, "wrong-pass")); var response = result.Should().BeOfType>().Subject; response.Should().ContainKey("error"); response["error"].Should().Be("access_denied"); } // ───────────────────────────────────────────── // 4. Provider returns null → fallback to local auth // ───────────────────────────────────────────── [Fact] public async Task ExternalAuth_ProviderSkips_FallsBackToLocal() { var localUsername = $"ext_e2e_l_{Guid.NewGuid():N}"[..20]; var localPassword = "Local@Pass1"; await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = localUsername, Password = localPassword, Name = $"LocalE2E {localUsername}", // Per run: emails are unique in _users (UX_users_email); the MSSQL test database is never // wiped between runs, so a fixed address collides on the second run. Email = $"{localUsername}@test.com", Enabled = true }); // FakeProvider has NO handler for this user → returns null → skip // (handlers are cleared by Dispose, but we also don't add any) var result = await _fx.Request(IdentityEndpoints.Token, RopcBody(localUsername, localPassword)); var response = result.Should().BeOfType>().Subject; response.Should().NotContainKey("error", because: $"local fallback should work, got: {response.GetValueOrDefault("error_description")}"); response.Should().ContainKey("access_token"); // JWT sub = the public per-user GUID (UserProps.value_guid). // The bigint local user-id is mirrored into the internal `redb:user_id` claim. var claims = DecodeJwtPayload(response["access_token"]!.ToString()!); var coreUser = await _fx.Redb.UserProvider.GetUserByLoginAsync(localUsername); var oidcObj = await _fx.Redb.Query() .WhereRedb(o => o.Key == coreUser!.Id) .FirstOrDefaultAsync(); oidcObj.Should().NotBeNull("LoginService persists UserProps with value_guid on first login"); oidcObj!.value_guid.Should().NotBeNull().And.NotBe(Guid.Empty); claims.GetProperty("sub").GetString().Should().Be(oidcObj.value_guid!.Value.ToString("D")); claims.GetProperty("redb:user_id").GetString().Should().Be(coreUser!.Id.ToString()); _out.WriteLine($"Local fallback OK: sub={oidcObj.value_guid}, internal_uid={coreUser.Id}"); } // ───────────────────────────────────────────── // 5. Provider throws exception → skipped → fallback to local // ───────────────────────────────────────────── [Fact] public async Task ExternalAuth_ProviderThrows_SkippedGracefully_FallbackWorks() { var throwUsername = $"ext_e2e_t_{Guid.NewGuid():N}"[..20]; var localPassword = "Fallback@Pass1"; await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = throwUsername, Password = localPassword, Name = $"FallbackE2E {throwUsername}", Enabled = true }); // Provider blows up → must be caught and skipped _fx.FakeExternalProvider.UserHandlers[throwUsername] = _ => throw new InvalidOperationException("LDAP server unreachable"); var result = await _fx.Request(IdentityEndpoints.Token, RopcBody(throwUsername, localPassword)); var response = result.Should().BeOfType>().Subject; response.Should().NotContainKey("error", because: $"provider exception must not bubble, got: {response.GetValueOrDefault("error_description")}"); response.Should().ContainKey("access_token"); } // ───────────────────────────────────────────── // 6. Disabled user → reject even if external provider says yes // ───────────────────────────────────────────── [Fact] public async Task ExternalAuth_DisabledUser_RejectsEvenIfExternalSucceeds() { var extUsername = $"ext_e2e_d_{Guid.NewGuid():N}"[..20]; await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = extUsername, Password = "Dummy@Pass1", Name = $"DisabledE2E {extUsername}", Enabled = false }); _fx.FakeExternalProvider.UserHandlers[extUsername] = _ => ExternalAuthResult.Success( externalId: $"cn={extUsername},dc=corp", displayName: $"Dis {extUsername}"); var result = await _fx.Request(IdentityEndpoints.Token, RopcBody(extUsername, "any-pass")); var response = result.Should().BeOfType>().Subject; response.Should().ContainKey("error"); response["error"].Should().Be("access_denied"); } // ───────────────────────────────────────────── // 7. Wrong password on external provider → proper OAuth2 error // ───────────────────────────────────────────── [Fact] public async Task ExternalAuth_WrongPassword_ReturnsAccessDenied() { var extUsername = $"ext_e2e_w_{Guid.NewGuid():N}"[..20]; _fx.FakeExternalProvider.UserHandlers[extUsername] = password => password == "correct-pass" ? ExternalAuthResult.Success( externalId: "cn=test,dc=corp", displayName: "Test User") : ExternalAuthResult.Failed("Bad credentials"); var result = await _fx.Request(IdentityEndpoints.Token, RopcBody(extUsername, "wrong-pass")); var response = result.Should().BeOfType>().Subject; response.Should().ContainKey("error"); response["error"].Should().Be("access_denied"); } } Path: redb-identity/tests/redb.Identity.Tests/Federation/FederationProcessorTests.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/Federation/FederationProcessorTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Federation; /// /// Integration tests for the federation (OIDC redirect-based auth) flow. /// Full pipeline: FederationChallenge → state encrypt → FederationCallback /// → code exchange (via FakeFederatedAuthProvider) → user provisioning → session. /// Uses real PostgreSQL and real route pipeline (direct-vm:// access). /// [Collection("Federation")] public class FederationProcessorTests : IDisposable { private readonly FederationFixture _fx; private readonly ITestOutputHelper _out; public FederationProcessorTests(FederationFixture fx, ITestOutputHelper output) { _fx = fx; _out = output; } public void Dispose() { _fx.FakeProvider.ChallengeHandler = null; _fx.FakeProvider.CallbackHandler = null; } // ═══════════════════════════════════════════════ // Challenge endpoint // ═══════════════════════════════════════════════ [Fact] public async Task Challenge_ValidProvider_ReturnsRedirectUri() { var body = new Dictionary { ["provider"] = "fake-oidc", ["returnUrl"] = "/dashboard", ["callbackUrl"] = "https://identity.test.local/connect/federation/callback" }; var result = await _fx.Request(IdentityEndpoints.FederationChallenge, body); var response = result.Should().BeOfType>().Subject; response.Should().ContainKey("redirect_uri"); response.Should().NotContainKey("error"); var redirectUri = response["redirect_uri"]!.ToString()!; redirectUri.Should().StartWith("https://fake-oidc.test/authorize"); redirectUri.Should().Contain("state="); _out.WriteLine($"Challenge redirect_uri: {redirectUri}"); } [Fact] public async Task Challenge_MissingProvider_ReturnsError() { var body = new Dictionary { ["returnUrl"] = "/dashboard", ["callbackUrl"] = "https://identity.test.local/connect/federation/callback" }; var result = await _fx.Request(IdentityEndpoints.FederationChallenge, body); var response = result.Should().BeOfType>().Subject; response["error"].Should().Be("invalid_request"); response["error_description"]!.ToString().Should().Contain("provider"); } [Fact] public async Task Challenge_UnknownProvider_ReturnsError() { var body = new Dictionary { ["provider"] = "nonexistent-provider", ["callbackUrl"] = "https://identity.test.local/connect/federation/callback" }; var result = await _fx.Request(IdentityEndpoints.FederationChallenge, body); var response = result.Should().BeOfType>().Subject; response["error"].Should().Be("invalid_request"); response["error_description"]!.ToString().Should().Contain("nonexistent-provider"); } [Fact] public async Task Challenge_MissingCallbackUrl_ReturnsError() { var body = new Dictionary { ["provider"] = "fake-oidc" }; var result = await _fx.Request(IdentityEndpoints.FederationChallenge, body); var response = result.Should().BeOfType>().Subject; response["error"].Should().Be("server_error"); response["error_description"]!.ToString().Should().Contain("Callback URL"); } // ═══════════════════════════════════════════════ // Full Challenge → Callback flow (happy path) // ═══════════════════════════════════════════════ [Fact] public async Task FullFlow_NewUser_CreatesUserAndSession() { var uniqueCode = Guid.NewGuid().ToString("N")[..12]; var expectedSub = $"fed-sub-{uniqueCode}"; var expectedEmail = $"alice-fed-{uniqueCode}@corp.example.com"; _fx.FakeProvider.CallbackHandler = (code, codeVerifier, nonce) => ExternalAuthResult.Success( externalId: expectedSub, displayName: $"Alice Fed {uniqueCode}", email: expectedEmail, givenName: "Alice", familyName: "Federation"); // Step 1: Challenge → get encrypted state var challengeBody = new Dictionary { ["provider"] = "fake-oidc", ["returnUrl"] = "/my-app", ["callbackUrl"] = "https://identity.test.local/connect/federation/callback" }; var challengeResult = await _fx.Request(IdentityEndpoints.FederationChallenge, challengeBody); var challengeResp = challengeResult.Should().BeOfType>().Subject; challengeResp.Should().NotContainKey("error", because: $"challenge should succeed, got: {challengeResp.GetValueOrDefault("error_description")}"); // Extract the encrypted state from the redirect_uri var redirectUri = challengeResp["redirect_uri"]!.ToString()!; var stateParam = ExtractQueryParam(redirectUri, "state"); stateParam.Should().NotBeNullOrEmpty("redirect_uri must contain state parameter"); // Step 2: Callback → exchange code + create user + create session var callbackBody = new Dictionary { ["code"] = uniqueCode, ["state"] = stateParam, ["callbackUrl"] = "https://identity.test.local/connect/federation/callback" }; var callbackResult = await _fx.Request(IdentityEndpoints.FederationCallback, callbackBody); var callbackResp = callbackResult.Should().BeOfType>().Subject; callbackResp["success"].Should().Be(true, because: $"callback should succeed, got: {callbackResp.GetValueOrDefault("error_description")}"); callbackResp.Should().ContainKey("userId"); callbackResp.Should().ContainKey("username"); callbackResp.Should().ContainKey("sessionId"); callbackResp["returnUrl"].Should().Be("/my-app"); var userId = Convert.ToInt64(callbackResp["userId"]); var username = callbackResp["username"]!.ToString()!; var sessionId = Convert.ToInt64(callbackResp["sessionId"]); userId.Should().BeGreaterThan(0); sessionId.Should().BeGreaterThan(0); _out.WriteLine($"Created federated user: id={userId}, username={username}, sessionId={sessionId}"); // Step 3: Verify DB state — user was auto-provisioned var coreUser = await _fx.Redb.UserProvider.GetUserByIdAsync(userId); coreUser.Should().NotBeNull("local _users row must be created"); coreUser!.Enabled.Should().BeTrue(); coreUser.Email.Should().Be(expectedEmail); // Step 4: Verify UserProps row exists with given/family name claims var userPropsRow = await _fx.Redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync(); userPropsRow.Should().NotBeNull("UserProps must be created"); userPropsRow!.Props.GivenName.Should().Be("Alice"); userPropsRow.Props.FamilyName.Should().Be("Federation"); // V4-UNIQUE: per-link FederatedIdentityProps row keyed by the [RedbUnique] LinkKey // "fake-oidc:{sub}" for reverse lookup (was the value_string mirror before F2). var expectedKey = $"fake-oidc:{expectedSub}"; var fedRow = await _fx.Redb.GetByUniqueAsync(p => p.LinkKey, expectedKey); fedRow.Should().NotBeNull("FederatedIdentityProps reverse-lookup row must exist"); fedRow!.key.Should().Be(userId); } [Fact] public async Task DirectLoginService_ResolveFederatedUser_Works() { var uniqueCode = Guid.NewGuid().ToString("N")[..12]; var stableSub = $"stable-sub-{uniqueCode}"; var email = $"direct-{uniqueCode}@test.com"; var ext = ExternalAuthResult.Success( externalId: stableSub, displayName: $"Direct Test {uniqueCode}", email: email, givenName: "Direct", familyName: "Test"); using var scope = _fx.ServiceProvider.CreateScope(); var loginService = scope.ServiceProvider.GetRequiredService(); var result = await loginService.ResolveFederatedUserAsync("fake-oidc", ext); result.Succeeded.Should().BeTrue( because: $"ResolveFederatedUserAsync should succeed, got: {result.ErrorMessage}"); result.UserId.Should().BeGreaterThan(0); _out.WriteLine($"Direct resolve: userId={result.UserId}, username={result.Username}"); } [Fact] public async Task FullFlow_MinimalCallback_Works() { // Exact same pattern as FullFlow_NewUser — minimal reproduction test var uniqueCode = Guid.NewGuid().ToString("N")[..12]; var expectedSub = $"min-sub-{uniqueCode}"; var expectedEmail = $"minimal-{uniqueCode}@test.com"; _fx.FakeProvider.CallbackHandler = (code, codeVerifier, nonce) => ExternalAuthResult.Success( externalId: expectedSub, displayName: $"Minimal {uniqueCode}", email: expectedEmail, givenName: "Min", familyName: "Test"); var state = await DoChallenge(); var result = await DoCallback(uniqueCode, state); result.Should().ContainKey("success", because: $"minimal callback should succeed, got: {string.Join(", ", result.Select(kv => $"{kv.Key}={kv.Value}"))}"); result["success"].Should().Be(true); } [Fact] public async Task FullFlow_RepeatLogin_SyncsProfileAndReturnsSameUser() { var uniqueCode1 = Guid.NewGuid().ToString("N")[..12]; var uniqueCode2 = Guid.NewGuid().ToString("N")[..12]; var stableSub = $"rep-sub-{uniqueCode1}"; var email1 = $"bob-v1-{uniqueCode1}@test.com"; _fx.FakeProvider.CallbackHandler = (code, codeVerifier, nonce) => ExternalAuthResult.Success( externalId: stableSub, displayName: $"Bob Original {uniqueCode1}", email: email1, givenName: "Bob", familyName: "Original"); var state1 = await DoChallenge(); var result1 = await DoCallback(uniqueCode1, state1); result1.Should().ContainKey("success", because: $"first login should succeed, got: {string.Join(", ", result1.Select(kv => $"{kv.Key}={kv.Value}"))}"); result1["success"].Should().Be(true); var userId1 = Convert.ToInt64(result1["userId"]); _out.WriteLine($"First login: userId={userId1}"); // Change profile on "external" side var email2 = $"bob-v2-{uniqueCode2}@test.com"; _fx.FakeProvider.CallbackHandler = (code, codeVerifier, nonce) => ExternalAuthResult.Success( externalId: stableSub, displayName: $"Bob Updated {uniqueCode1}", email: email2, givenName: "Bobby", familyName: "Updated"); // Second login — same sub → same user, synced profile var state2 = await DoChallenge(); var result2 = await DoCallback(uniqueCode2, state2); result2.Should().ContainKey("success", because: $"second login should succeed, got: {string.Join(", ", result2.Select(kv => $"{kv.Key}={kv.Value}"))}"); result2["success"].Should().Be(true); var userId2 = Convert.ToInt64(result2["userId"]); userId2.Should().Be(userId1, "second login must return same user"); // Verify profile was synced var coreUser = await _fx.Redb.UserProvider.GetUserByIdAsync(userId1); coreUser!.Name.Should().Be($"Bob Updated {uniqueCode1}"); coreUser.Email.Should().Be(email2); var oidcObj = await _fx.Redb.Query() .WhereRedb(o => o.Key == userId1) .FirstOrDefaultAsync(); oidcObj!.Props.GivenName.Should().Be("Bobby"); oidcObj.Props.FamilyName.Should().Be("Updated"); } // ═══════════════════════════════════════════════ // Callback error scenarios // ═══════════════════════════════════════════════ [Fact] public async Task Callback_InvalidState_ReturnsError() { var body = new Dictionary { ["code"] = "some-code", ["state"] = "totally-invalid-garbage-state", ["callbackUrl"] = "https://identity.test.local/connect/federation/callback" }; var result = await _fx.Request(IdentityEndpoints.FederationCallback, body); var response = result.Should().BeOfType>().Subject; response["success"].Should().Be(false); response["error"].Should().Be("invalid_state"); } [Fact] public async Task Callback_ExpiredState_ReturnsError() { // Create a valid state but with IssuedAt in the distant past var stateProtector = _fx.ServiceProvider.GetService(typeof(FederationStateProtector)) as FederationStateProtector; stateProtector.Should().NotBeNull(); var expiredState = stateProtector!.Protect(new FederationState { ProviderId = "fake-oidc", ReturnUrl = "/", IssuedAt = DateTimeOffset.UtcNow.AddMinutes(-30) // way past the 5-min TTL }); var body = new Dictionary { ["code"] = "some-code", ["state"] = expiredState, ["callbackUrl"] = "https://identity.test.local/connect/federation/callback" }; var result = await _fx.Request(IdentityEndpoints.FederationCallback, body); var response = result.Should().BeOfType>().Subject; response["success"].Should().Be(false); response["error"].Should().Be("invalid_state"); } [Fact] public async Task Callback_IdpReturnsError_PropagatesError() { var body = new Dictionary { ["error"] = "access_denied", ["error_description"] = "User denied consent" }; var result = await _fx.Request(IdentityEndpoints.FederationCallback, body); var response = result.Should().BeOfType>().Subject; response["success"].Should().Be(false); response["error"].Should().Be("access_denied"); response["error_description"]!.ToString().Should().Contain("User denied consent"); } [Fact] public async Task Callback_MissingCode_ReturnsError() { var stateProtector = _fx.ServiceProvider.GetService(typeof(FederationStateProtector)) as FederationStateProtector; var validState = stateProtector!.Protect(new FederationState { ProviderId = "fake-oidc", ReturnUrl = "/" }); var body = new Dictionary { ["state"] = validState, ["callbackUrl"] = "https://identity.test.local/connect/federation/callback" }; var result = await _fx.Request(IdentityEndpoints.FederationCallback, body); var response = result.Should().BeOfType>().Subject; response["success"].Should().Be(false); response["error"].Should().Be("invalid_request"); } [Fact] public async Task Callback_ProviderReturnsFailure_ReturnsAccessDenied() { _fx.FakeProvider.CallbackHandler = (code, codeVerifier, nonce) => ExternalAuthResult.Failed("Token exchange failed: bad code"); var state = await DoChallenge(); var result = await DoCallback("bad-code", state); result["success"].Should().Be(false); result["error"].Should().Be("access_denied"); result["error_description"]!.ToString().Should().Contain("Token exchange failed"); } [Fact] public async Task Callback_StateReplay_SecondUseRejected_OneTimeUse() { // C6: federation state is one-time-use. The same state blob must not be // accepted twice — the second callback must return invalid_state regardless // of whether the upstream provider would accept the code. var uniqueCode = Guid.NewGuid().ToString("N")[..12]; var sub = $"replay-sub-{uniqueCode}"; _fx.FakeProvider.CallbackHandler = (code, codeVerifier, nonce) => ExternalAuthResult.Success(externalId: sub, displayName: $"Replay User {uniqueCode}", email: $"{uniqueCode}@test.com"); // First callback with valid state — succeeds and consumes the jti. var state = await DoChallenge(); var result1 = await DoCallback(uniqueCode, state); result1["success"].Should().Be(true); // Second callback with the same state — must be rejected by the nonce store. var result2 = await DoCallback(uniqueCode, state); result2["success"].Should().Be(false); result2["error"].Should().Be("invalid_state"); } // ═══════════════════════════════════════════════ // Helpers // ═══════════════════════════════════════════════ private async Task DoChallenge(string returnUrl = "/") { var body = new Dictionary { ["provider"] = "fake-oidc", ["returnUrl"] = returnUrl, ["callbackUrl"] = "https://identity.test.local/connect/federation/callback" }; var result = await _fx.Request(IdentityEndpoints.FederationChallenge, body); var resp = result.Should().BeOfType>().Subject; resp.Should().NotContainKey("error", because: $"challenge should succeed, got: {resp.GetValueOrDefault("error_description")}"); var redirectUri = resp["redirect_uri"]!.ToString()!; return ExtractQueryParam(redirectUri, "state")!; } private async Task> DoCallback(string code, string state) { var body = new Dictionary { ["code"] = code, ["state"] = state, ["callbackUrl"] = "https://identity.test.local/connect/federation/callback" }; var result = await _fx.Request(IdentityEndpoints.FederationCallback, body); return result.Should().BeOfType>().Subject; } private static string? ExtractQueryParam(string url, string paramName) { var uri = new Uri(url, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) uri = new Uri("http://dummy" + url); var query = uri.Query.TrimStart('?'); foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) { var parts = pair.Split('=', 2); if (parts.Length == 2 && parts[0] == paramName) return Uri.UnescapeDataString(parts[1]); } return null; } } Path: redb-identity/tests/redb.Identity.Tests/Federation/H8FederationPolishTests.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/Federation/H8FederationPolishTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Federation; /// /// H8 (v1.0 DoD §4): integration tests for the federation polish work — admin CRUD over /// PROPS-stored providers, multi-link reverse lookup, last-credential guard, and the /// self-service /me/federated-identities endpoint. /// /// /// Reuses (real Postgres + full route context). Tests /// that don't need an external IdP exercise the routes/services directly; tests that /// require a real OIDC flow gate themselves on . /// /// [Collection("MockOidcE2E")] [Trait("Category", "Integration")] [Trait("Requires", "MockOAuth2")] public class H8FederationPolishTests { private readonly MockOidcE2EFixture _fx; private readonly ITestOutputHelper _out; public H8FederationPolishTests(MockOidcE2EFixture fx, ITestOutputHelper output) { _fx = fx; _out = output; } private void EnsureReady() => _fx.RequireServer(); // ═══════════════════════════════════════════════ // H8 — Admin CRUD over PROPS-stored federation providers // ═══════════════════════════════════════════════ [Fact] public async Task AdminCrud_RoundTrips_ProviderAndEncryptsSecret() { EnsureReady(); var providerId = $"h8-test-{Guid.NewGuid():N}"[..16]; var clientSecret = "super-secret-" + Guid.NewGuid().ToString("N"); // CREATE var createBody = new redb.Identity.Contracts.Federation.CreateFederationProviderRequest { ProviderId = providerId, Kind = "oidc", DisplayName = "H8 Test Provider", Authority = "http://localhost:9199/h8-test", ClientId = "h8-client", ClientSecret = clientSecret, Scopes = ["openid", "profile"], Enabled = true, Priority = 50, }; var createResult = await Forward(IdentityEndpoints.ManageFederationProviders, "create", createBody); var created = createResult.Should().BeOfType().Subject; created.ProviderId.Should().Be(providerId); created.HasSecret.Should().BeTrue("DataProtection-encrypted secret should be stored"); // Plaintext must NEVER appear in the response. var createdJson = System.Text.Json.JsonSerializer.Serialize(created); createdJson.Should().NotContain(clientSecret); var createdId = long.Parse(created.Id); // Verify the PROPS row stores ciphertext, not plaintext. WithRedb so this // doesn't share an NpgsqlConnection with the WireTap audit pipeline still // wrapping up Forward()'s INSERT INTO identity_audit_log on a background task. var stored = await _fx.WithRedb(redb => redb.LoadAsync(createdId)); stored.Should().NotBeNull(); stored!.Props.EncryptedClientSecret.Should().NotBeNullOrEmpty(); stored.Props.EncryptedClientSecret.Should().NotContain(clientSecret, "must be encrypted at rest"); stored.Props.ProviderId.Should().Be(providerId, "ProviderId is the [RedbUnique] key now (V4-UNIQUE); the value_string mirror is gone"); // Round-trip via DataProtection: the protector decrypts back to the original. var protector = _fx.ServiceProvider.GetRequiredService(); protector.Unprotect(stored.Props.EncryptedClientSecret).Should().Be(clientSecret); // READ var readResult = await Forward(IdentityEndpoints.ManageFederationProviders, "read", new Dictionary { ["id"] = createdId }); readResult.Should().BeOfType() .Subject.HasSecret.Should().BeTrue(); // UPDATE (rotate secret) var newSecret = "rotated-secret-" + Guid.NewGuid().ToString("N"); var updateBody = new redb.Identity.Contracts.Federation.UpdateFederationProviderRequest { Id = createdId.ToString(), DisplayName = "H8 Test Provider (renamed)", ClientSecret = newSecret, }; var updateResult = await Forward(IdentityEndpoints.ManageFederationProviders, "update", updateBody); var updated = updateResult.Should().BeOfType().Subject; updated.DisplayName.Should().Be("H8 Test Provider (renamed)"); updated.HasSecret.Should().BeTrue(); var afterRotate = await _fx.WithRedb(redb => redb.LoadAsync(createdId)); protector.Unprotect(afterRotate!.Props.EncryptedClientSecret).Should().Be(newSecret, "rotation should overwrite the encrypted blob"); // UPDATE (clear secret with empty string) var clearBody = new redb.Identity.Contracts.Federation.UpdateFederationProviderRequest { Id = createdId.ToString(), ClientSecret = string.Empty, }; var clearResult = await Forward(IdentityEndpoints.ManageFederationProviders, "update", clearBody); clearResult.Should().BeOfType() .Subject.HasSecret.Should().BeFalse("empty string must clear the stored secret"); // DELETE — soft-delete via IdentityDeletionHelper. Verify the row no longer // appears via the standard query path (re-parented under the trash scheme). var deleteResult = await Forward(IdentityEndpoints.ManageFederationProviders, "delete", new Dictionary { ["id"] = createdId }); deleteResult.Should().NotBeNull(); var afterDelete = await _fx.WithRedb(redb => redb.GetByUniqueAsync(p => p.ProviderId, providerId)); afterDelete.Should().BeNull("deletion must remove the PROPS row from queries"); } [Fact] public async Task AdminCrud_RejectsDuplicateProviderId() { EnsureReady(); var providerId = $"h8-dup-{Guid.NewGuid():N}"[..16]; var req = new redb.Identity.Contracts.Federation.CreateFederationProviderRequest { ProviderId = providerId, Kind = "oidc", DisplayName = "Dup", Authority = "http://example.invalid/", ClientId = "x", }; await Forward(IdentityEndpoints.ManageFederationProviders, "create", req); var dup = await Forward(IdentityEndpoints.ManageFederationProviders, "create", req); var error = dup.Should().BeOfType( "duplicate ProviderId must return an error document").Subject; error.Error.Should().Be("duplicate"); } // ═══════════════════════════════════════════════ // H8 — Per-link FederatedIdentityProps + last-credential guard // ═══════════════════════════════════════════════ [Fact] public async Task LinkAndUnlink_LastCredentialGuard_BlocksWhenNoPassword() { EnsureReady(); var loginService = _fx.ServiceProvider.GetRequiredService(); // Create a fresh user with no password. var login = $"h8-fed-only-{Guid.NewGuid():N}"[..20]; var newUser = await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = login, Password = "InitialP@ssw0rd!", Name = login, Email = login + "@example.test", Enabled = true, }); // No password set — emulates a user that arrived only via federation. // Mark HasUserPassword=false explicitly on UserProps. var userProps = await _fx.Redb.Query() .WhereRedb(o => o.Key == newUser.Id) .FirstOrDefaultAsync(); if (userProps is null) { userProps = new redb.Core.Models.Entities.RedbObject(new UserProps()); userProps.key = newUser.Id; userProps.name = login; } userProps.Props.HasUserPassword = false; await _fx.Redb.SaveAsync(userProps); // Link a single federated identity. var ext1 = ExternalAuthResult.Success( externalId: "ext-sub-1-" + Guid.NewGuid().ToString("N"), displayName: "Ext User 1", email: login + "@idp.test"); await loginService.LinkFederatedIdentityAsync(newUser.Id, "h8-prov-a", ext1); var links = await loginService.ListFederatedIdentitiesAsync(newUser.Id); links.Should().HaveCount(1); links[0].ProviderId.Should().Be("h8-prov-a"); // Try unlinking via the /me processor → expect 409 last_credential_method // because HasUserPassword=false AND only one social link remains. The processor // pulls callerId from the management-subject exchange property; rather than // staging an HTTP-level token we exercise the PROPS invariant directly here: // the link must still survive an attempted unlink while HasUserPassword=false. var allLinks = await loginService.ListFederatedIdentitiesAsync(newUser.Id); allLinks.Count.Should().Be(1); userProps = await _fx.Redb.Query() .WhereRedb(o => o.Key == newUser.Id) .FirstOrDefaultAsync(); userProps!.Props.HasUserPassword.Should().BeFalse( "this user has no password — the guard must trigger on the next unlink attempt"); // Now flip HasUserPassword=true and verify unlink succeeds (covers the // "user added a password → can drop their last social" path). userProps.Props.HasUserPassword = true; await _fx.Redb.SaveAsync(userProps); var unlinked = await loginService.UnlinkFederatedIdentityAsync(newUser.Id, "h8-prov-a"); unlinked.Should().BeTrue(); (await loginService.ListFederatedIdentitiesAsync(newUser.Id)).Should().BeEmpty(); } [Fact] public async Task MultiProvider_ReverseLookup_FindsCorrectUser() { EnsureReady(); var loginService = _fx.ServiceProvider.GetRequiredService(); var login = $"h8-multi-{Guid.NewGuid():N}"[..20]; var newUser = await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = login, Password = "InitialP@ssw0rd!", Name = login, Email = login + "@example.test", Enabled = true, }); var subA = "ext-A-" + Guid.NewGuid().ToString("N"); var subB = "ext-B-" + Guid.NewGuid().ToString("N"); await loginService.LinkFederatedIdentityAsync(newUser.Id, "h8-prov-a", ExternalAuthResult.Success(externalId: subA, email: login + "@idp-a.test")); await loginService.LinkFederatedIdentityAsync(newUser.Id, "h8-prov-b", ExternalAuthResult.Success(externalId: subB, email: login + "@idp-b.test")); var links = await loginService.ListFederatedIdentitiesAsync(newUser.Id); links.Should().HaveCount(2); links.Select(l => l.ProviderId).Should().BeEquivalentTo(new[] { "h8-prov-a", "h8-prov-b" }); // Both reverse lookups must find the same user via the per-link [RedbUnique] LinkKey // (V4-UNIQUE; was the value_string mirror before F2). var keyA = FederatedIdentityProps.MakeLinkKey("h8-prov-a", subA); var keyB = FederatedIdentityProps.MakeLinkKey("h8-prov-b", subB); var rowA = await _fx.Redb.GetByUniqueAsync(p => p.LinkKey, keyA); var rowB = await _fx.Redb.GetByUniqueAsync(p => p.LinkKey, keyB); rowA.Should().NotBeNull(); rowB.Should().NotBeNull(); rowA!.key.Should().Be(newUser.Id); rowB!.key.Should().Be(newUser.Id); } private async Task Forward(string endpointUri, string operation, object body) { // Dispatch via the route just like the HTTP controller would: include the // 'operation' header so the management processor selects the right branch. var exchange = await _fx.RequestWithHeaders(endpointUri, body, new Dictionary { ["operation"] = operation }); return exchange.Out?.Body; } } Path: redb-identity/tests/redb.Identity.Tests/Federation/MockOidcE2ETests.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/Federation/MockOidcE2ETests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Core.Query; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Federation; /// /// End-to-end federation tests against a real mock-oauth2-server (navikt). /// Validates the complete OIDC flow: discovery → PKCE challenge → interactive login /// → authorization code → token exchange → id_token validation → user provisioning. /// Requires: route-mock-oauth2 container on port 9199. /// [Collection("MockOidcE2E")] [Trait("Category", "Integration")] [Trait("Requires", "MockOAuth2")] public class MockOidcE2ETests { private readonly MockOidcE2EFixture _fx; private readonly ITestOutputHelper _out; public MockOidcE2ETests(MockOidcE2EFixture fx, ITestOutputHelper output) { _fx = fx; _out = output; } private void EnsureServerAvailable() => _fx.RequireServer(); // ═══════════════════════════════════════════════ // Discovery // ═══════════════════════════════════════════════ [Fact] public async Task Discovery_MockOidcServer_IsReachable() { EnsureServerAvailable(); using var http = new HttpClient(); var disco = await http.GetStringAsync( $"{MockOidcE2EFixture.Authority}/.well-known/openid-configuration"); disco.Should().Contain("authorization_endpoint"); disco.Should().Contain("token_endpoint"); disco.Should().Contain("jwks_uri"); _out.WriteLine("mock-oauth2-server discovery OK"); } // ═══════════════════════════════════════════════ // Full E2E: Challenge → Interactive Login → Callback → User // ═══════════════════════════════════════════════ [Fact] public async Task FullE2E_NewUser_RealOidcFlow() { EnsureServerAvailable(); var uniqueId = Guid.NewGuid().ToString("N")[..8]; var mockUsername = $"e2e-user-{uniqueId}"; // Step 1: Challenge → get redirect URL pointing to real mock-oauth2-server var challengeBody = new Dictionary { ["provider"] = MockOidcE2EFixture.ProviderId, ["returnUrl"] = "/e2e-dashboard", ["callbackUrl"] = MockOidcE2EFixture.CallbackUrl }; var challengeResult = await _fx.Request(IdentityEndpoints.FederationChallenge, challengeBody); var challengeResp = challengeResult.Should().BeOfType>().Subject; challengeResp.Should().NotContainKey("error", because: $"challenge should succeed, got: {challengeResp.GetValueOrDefault("error_description")}"); var redirectUri = challengeResp["redirect_uri"]!.ToString()!; _out.WriteLine($"Challenge redirect: {redirectUri}"); // Verify the redirect points to real mock-oauth2-server redirectUri.Should().StartWith(MockOidcE2EFixture.Authority); redirectUri.Should().Contain("response_type=code"); redirectUri.Should().Contain("code_challenge_method=S256"); redirectUri.Should().Contain("code_challenge="); // PKCE // Extract the encrypted state from the redirect URL var encryptedState = MockOidcE2EFixture.ExtractQueryParam(redirectUri, "state"); encryptedState.Should().NotBeNullOrEmpty(); // Step 2: Simulate browser login on mock-oauth2-server var (code, returnedState) = await _fx.SimulateInteractiveLogin(redirectUri, mockUsername); _out.WriteLine($"Mock login complete: code={code[..8]}..., state matches={returnedState == encryptedState}"); returnedState.Should().Be(encryptedState, "mock-oauth2-server should echo our state"); // Step 3: Callback → code exchange (real token endpoint) → user provisioning var callbackBody = new Dictionary { ["code"] = code, ["state"] = encryptedState, ["callbackUrl"] = MockOidcE2EFixture.CallbackUrl }; var callbackResult = await _fx.Request(IdentityEndpoints.FederationCallback, callbackBody); var callbackResp = callbackResult.Should().BeOfType>().Subject; callbackResp.Should().ContainKey("success"); callbackResp["success"].Should().Be(true, because: $"callback should succeed, got error: {callbackResp.GetValueOrDefault("error")} / {callbackResp.GetValueOrDefault("error_description")}"); callbackResp.Should().ContainKey("userId"); callbackResp.Should().ContainKey("sessionId"); callbackResp.Should().ContainKey("username"); callbackResp["returnUrl"].Should().Be("/e2e-dashboard"); var userId = Convert.ToInt64(callbackResp["userId"]); var sessionId = Convert.ToInt64(callbackResp["sessionId"]); userId.Should().BeGreaterThan(0); sessionId.Should().BeGreaterThan(0); _out.WriteLine($"User provisioned: userId={userId}, sessionId={sessionId}, username={callbackResp["username"]}"); // Step 4: Verify DB — UserProps row + per-link FederatedIdentityProps row exist (H8). var userPropsRow = await _fx.Redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync(); userPropsRow.Should().NotBeNull("UserProps must be created for federated user"); // Per-link reverse-lookup row: [RedbUnique] LinkKey format "{providerId}:{sub}" // (V4-UNIQUE; was the value_string mirror before F2). var providerPrefix = MockOidcE2EFixture.ProviderId + ":"; var fedRow = await _fx.Redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync(); fedRow.Should().NotBeNull("FederatedIdentityProps row must be created for the link"); fedRow!.Props.LinkKey.Should().StartWith(providerPrefix); _out.WriteLine($"Federated link stored: LinkKey={fedRow.Props.LinkKey}"); } [Fact] public async Task FullE2E_RepeatLogin_ReturnsSameUser() { EnsureServerAvailable(); var uniqueId = Guid.NewGuid().ToString("N")[..8]; var mockUsername = $"e2e-repeat-{uniqueId}"; // First login var (userId1, sessionId1) = await DoFullE2EFlow(mockUsername); _out.WriteLine($"First login: userId={userId1}, sessionId={sessionId1}"); // Second login with same username (same sub from mock-oauth2-server) var (userId2, sessionId2) = await DoFullE2EFlow(mockUsername); _out.WriteLine($"Second login: userId={userId2}, sessionId={sessionId2}"); userId2.Should().Be(userId1, "repeat login should resolve the same user"); sessionId2.Should().NotBe(sessionId1, "each login should create a new session"); } [Fact] public async Task FullE2E_DifferentUsers_CreateDifferentAccounts() { EnsureServerAvailable(); var uniqueId = Guid.NewGuid().ToString("N")[..8]; var (userId1, _) = await DoFullE2EFlow($"e2e-alice-{uniqueId}"); var (userId2, _) = await DoFullE2EFlow($"e2e-bob-{uniqueId}"); userId1.Should().NotBe(userId2, "different IdP users should get different local accounts"); _out.WriteLine($"Alice={userId1}, Bob={userId2}"); } [Fact] public async Task Challenge_RealDiscovery_ContainsPkceAndScopes() { EnsureServerAvailable(); var challengeBody = new Dictionary { ["provider"] = MockOidcE2EFixture.ProviderId, ["returnUrl"] = "/", ["callbackUrl"] = MockOidcE2EFixture.CallbackUrl }; var challengeResult = await _fx.Request(IdentityEndpoints.FederationChallenge, challengeBody); var resp = challengeResult.Should().BeOfType>().Subject; resp.Should().NotContainKey("error"); var redirectUri = resp["redirect_uri"]!.ToString()!; // Verify PKCE parameters are present MockOidcE2EFixture.ExtractQueryParam(redirectUri, "code_challenge").Should().NotBeNullOrEmpty(); MockOidcE2EFixture.ExtractQueryParam(redirectUri, "code_challenge_method").Should().Be("S256"); // Verify scopes var scope = MockOidcE2EFixture.ExtractQueryParam(redirectUri, "scope"); scope.Should().Contain("openid"); // Verify nonce MockOidcE2EFixture.ExtractQueryParam(redirectUri, "nonce").Should().NotBeNullOrEmpty(); _out.WriteLine($"PKCE + scopes + nonce verified in authorize URL"); } // ═══════════════════════════════════════════════ // Helpers // ═══════════════════════════════════════════════ private async Task<(long userId, long sessionId)> DoFullE2EFlow(string mockUsername) { var challengeBody = new Dictionary { ["provider"] = MockOidcE2EFixture.ProviderId, ["returnUrl"] = "/", ["callbackUrl"] = MockOidcE2EFixture.CallbackUrl }; var challengeResult = await _fx.Request(IdentityEndpoints.FederationChallenge, challengeBody); var challengeResp = challengeResult.Should().BeOfType>().Subject; challengeResp.Should().NotContainKey("error", because: $"challenge failed: {challengeResp.GetValueOrDefault("error_description")}"); var redirectUri = challengeResp["redirect_uri"]!.ToString()!; var encryptedState = MockOidcE2EFixture.ExtractQueryParam(redirectUri, "state")!; var (code, _) = await _fx.SimulateInteractiveLogin(redirectUri, mockUsername); var callbackBody = new Dictionary { ["code"] = code, ["state"] = encryptedState, ["callbackUrl"] = MockOidcE2EFixture.CallbackUrl }; var callbackResult = await _fx.Request(IdentityEndpoints.FederationCallback, callbackBody); var resp = callbackResult.Should().BeOfType>().Subject; resp["success"].Should().Be(true, because: $"E2E flow failed: {resp.GetValueOrDefault("error")} / {resp.GetValueOrDefault("error_description")}"); return (Convert.ToInt64(resp["userId"]), Convert.ToInt64(resp["sessionId"])); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/AdminMfaManagementTests.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/AdminMfaManagementTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Options; using OtpNet; using redb.Identity.Client; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// The admin MFA operations of the management API end to end, over real HTTP: TOTP setup, confirm with the first /// code and the setup token, status, recovery code regeneration, disable. Once with raw requests, once through /// , so neither the controller nor the client can drop a member the processor needs /// (confirm lost the setup token in April and nothing noticed: the client tests only look at the request URL, /// and the processor tests call the processor directly). /// [Collection("ProductionHttp")] public class AdminMfaManagementTests { private const string Base = "/api/v1/identity/mfa"; private readonly ProductionHttpFixture _fx; public AdminMfaManagementTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Totp_enrollment_runs_through_the_management_api() { var userId = await CreateUserAsync(); var setup = await Post($"{Base}/totp/setup", new { userId, username = "admin-mfa" }); var secret = setup.GetProperty("secret_base32").GetString()!; var setupToken = setup.GetProperty("setup_token").GetString()!; var confirmed = await Post($"{Base}/totp/confirm", new { userId, code = Code(secret), setupToken }); confirmed.GetProperty("confirmed").GetBoolean().Should().BeTrue(); confirmed.GetProperty("recovery_codes").GetArrayLength().Should().Be(10); var status = await Get($"{Base}/status/{userId}"); status.GetProperty("enabled").GetBoolean().Should().BeTrue(); status.GetProperty("methods").EnumerateArray().Select(m => m.GetString()).Should().Contain("totp"); status.GetProperty("recovery_codes_remaining").GetInt32().Should().Be(10); var regenerated = await Post($"{Base}/recovery-codes/regenerate", new { userId }); regenerated.GetProperty("recovery_codes").GetArrayLength().Should().Be(10); var disabled = await Send(HttpMethod.Delete, $"{Base}/totp/{userId}", null); disabled.GetProperty("disabled").GetBoolean().Should().BeTrue(); (await Get($"{Base}/status/{userId}")).GetProperty("enabled").GetBoolean().Should().BeFalse(); } [Fact] public async Task Totp_enrollment_runs_through_the_identity_client() { var client = Client(); var userId = await CreateUserAsync(); var setup = await client.SetupUserTotpAsync(userId, "admin-mfa-client"); var secret = setup.GetProperty("secret_base32").GetString()!; var setupToken = setup.GetProperty("setup_token").GetString()!; var confirmed = await client.ConfirmUserTotpAsync(userId, Code(secret), setupToken); confirmed.GetProperty("confirmed").GetBoolean().Should().BeTrue(confirmed.ToString()); var status = await client.GetUserMfaStatusAsync(userId); status.GetProperty("enabled").GetBoolean().Should().BeTrue(); var regenerated = await client.RegenerateUserRecoveryCodesAsync(userId); regenerated.GetProperty("recovery_codes").GetArrayLength().Should().Be(10); var disabled = await client.DisableUserTotpAsync(userId); disabled.GetProperty("disabled").GetBoolean().Should().BeTrue(); (await client.GetUserMfaStatusAsync(userId)).GetProperty("enabled").GetBoolean().Should().BeFalse(); } private static string Code(string base32Secret) => new Totp(Base32Encoding.ToBytes(base32Secret)).ComputeTotp(); private IdentityClient Client() { var http = new HttpClient { BaseAddress = _fx.Http.BaseAddress }; http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return new IdentityClient(http, Options.Create(new IdentityClientOptions { BaseUrl = _fx.Http.BaseAddress! })); } private async Task CreateUserAsync() { var login = "mfa-" + Guid.NewGuid().ToString("N")[..10]; var created = await Post("/api/v1/identity/users", new { login, password = "Str0ng!Passw0rd", displayName = login }); return created.GetProperty("id").GetInt64(); } private Task Get(string path) => Send(HttpMethod.Get, path, null); private Task Post(string path, object body) => Send(HttpMethod.Post, path, body); private Task Send(HttpMethod method, string path, object? body) => SendAs(_fx.ManagementToken, method, path, body, HttpStatusCode.OK); private async Task SendAs(string token, HttpMethod method, string path, object? body, HttpStatusCode expected) { var request = new HttpRequestMessage(method, path) { Content = body is null ? null : JsonContent.Create(body) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var response = await _fx.Http.SendAsync(request); var text = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(expected, $"{method} {path}: {text}"); return JsonDocument.Parse(text).RootElement; } // ── The granular scopes of the MFA surface ── [Fact] public async Task A_token_with_identity_mfa_write_runs_the_whole_enrollment_of_another_user() { var token = await GranularTokenAsync("identity:mfa:write"); var userId = await CreateUserAsync(); var setup = await SendAs(token, HttpMethod.Post, $"{Base}/totp/setup", new { userId, username = "granular-mfa" }, HttpStatusCode.OK); var secret = setup.GetProperty("secret_base32").GetString()!; var setupToken = setup.GetProperty("setup_token").GetString()!; (await SendAs(token, HttpMethod.Post, $"{Base}/totp/confirm", new { userId, code = Code(secret), setupToken }, HttpStatusCode.OK)) .GetProperty("confirmed").GetBoolean().Should().BeTrue(); (await SendAs(token, HttpMethod.Get, $"{Base}/status/{userId}", null, HttpStatusCode.OK)) .GetProperty("enabled").GetBoolean().Should().BeTrue("identity:mfa:write implies read"); (await SendAs(token, HttpMethod.Post, $"{Base}/recovery-codes/regenerate", new { userId }, HttpStatusCode.OK)) .GetProperty("recovery_codes").GetArrayLength().Should().Be(10); (await SendAs(token, HttpMethod.Delete, $"{Base}/totp/{userId}", null, HttpStatusCode.OK)) .GetProperty("disabled").GetBoolean().Should().BeTrue(); } [Fact] public async Task A_token_with_identity_mfa_read_reads_the_status_and_changes_nothing() { var token = await GranularTokenAsync("identity:mfa:read"); var userId = await CreateUserAsync(); (await SendAs(token, HttpMethod.Get, $"{Base}/status/{userId}", null, HttpStatusCode.OK)) .GetProperty("enabled").GetBoolean().Should().BeFalse(); await SendAs(token, HttpMethod.Post, $"{Base}/totp/setup", new { userId, username = "granular-mfa" }, HttpStatusCode.Forbidden); await SendAs(token, HttpMethod.Post, $"{Base}/recovery-codes/regenerate", new { userId }, HttpStatusCode.Forbidden); await SendAs(token, HttpMethod.Delete, $"{Base}/totp/{userId}", null, HttpStatusCode.Forbidden); (await Get($"{Base}/status/{userId}")).GetProperty("enabled").GetBoolean().Should().BeFalse("nothing was set up"); } [Fact] public async Task A_token_with_identity_users_write_alone_cannot_touch_mfa() { var token = await GranularTokenAsync("identity:users:write"); var userId = await CreateUserAsync(); await SendAs(token, HttpMethod.Get, $"{Base}/status/{userId}", null, HttpStatusCode.Forbidden); await SendAs(token, HttpMethod.Post, $"{Base}/totp/setup", new { userId, username = "granular-mfa" }, HttpStatusCode.Forbidden); await SendAs(token, HttpMethod.Delete, $"{Base}/totp/{userId}", null, HttpStatusCode.Forbidden); } /// A client_credentials token of a fresh client allowed exactly . private async Task GranularTokenAsync(string scope) { var clientId = "mfa-scope-" + Guid.NewGuid().ToString("N")[..10]; const string clientSecret = "mfa-scope-client-secret-1234"; await Post("/api/v1/identity/applications", new { clientId, clientSecret, displayName = clientId, permissions = new[] { "ept:token", "gt:client_credentials", "scp:" + scope }, }); var response = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["scope"] = scope, ["client_id"] = clientId, ["client_secret"] = clientSecret, })); var text = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(HttpStatusCode.OK, text); return JsonDocument.Parse(text).RootElement.GetProperty("access_token").GetString()!; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/AdminResultWireTests.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/AdminResultWireTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.RegularExpressions; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// The answers of the remaining management routes (groups, roles, claim definitions, claim mappers, claim /// scopes, federation providers, webhooks, impersonation) as bytes on the wire. The expected strings are what /// these routes answered while their bodies were anonymous objects; values the store decides (ids, times) are /// matched by pattern, every name, its order and every null are matched exactly. /// [Collection("ProductionHttp")] public class AdminResultWireTests { private const string Time = "\"[^\"]+\""; private readonly ProductionHttpFixture _fx; public AdminResultWireTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task A_group_and_its_members_answer_in_their_shapes() { var name = "wire-" + Guid.NewGuid().ToString("N")[..8]; var (_, parent) = await Ok(HttpMethod.Post, "/api/v1/identity/groups", new { name, groupType = "team", description = "d" }); var parentId = Id(parent); Match(parent, $$"""^\{"id":{{parentId}},"name":"{{name}}","parentId":(null|\d+),"groupType":"team","description":"d","createdAt":{{Time}},"modifiedAt":(null|{{Time}})\}$"""); var (_, child) = await Ok(HttpMethod.Post, $"/api/v1/identity/groups/{parentId}/children", new { name = name + "-c" }); var childId = Id(child); Match(child, $$"""^\{"id":{{childId}},"name":"{{name}}-c","parentId":{{parentId}},"groupType":null,"description":null,"createdAt":{{Time}},"modifiedAt":(null|{{Time}})\}$"""); var (_, read) = await Ok(HttpMethod.Get, $"/api/v1/identity/groups/{childId}"); Match(read, $$"""^\{"id":{{childId}},"name":"{{name}}-c","parentId":{{parentId}},"groupType":null,"description":null,"createdAt":{{Time}},"modifiedAt":(null|{{Time}})\}$"""); var (_, updated) = await Ok(HttpMethod.Put, $"/api/v1/identity/groups/{childId}", new { name = name + "-c2" }); updated.Should().Be($$"""{"success":true,"groupId":{{childId}}}"""); var (_, tree) = await Ok(HttpMethod.Get, $"/api/v1/identity/groups/{parentId}/tree"); Match(tree, $$"""^\{"id":{{parentId}},"name":"{{name}}","parentId":(null|\d+),"groupType":"team","description":"d","level":\d+,"children":\[\{"id":{{childId}},"name":"{{name}}-c2","parentId":{{parentId}},"groupType":null,"description":null,"level":\d+,"children":\[\]\}\]\}$"""); var (_, path) = await Ok(HttpMethod.Get, $"/api/v1/identity/groups/{childId}/path"); Match(path, $$"""^\[(\{"id":\d+,"name":"[^"]*","parentId":(null|\d+),"groupType":(null|"[^"]*"),"description":(null|"[^"]*"),"createdAt":{{Time}},"modifiedAt":(null|{{Time}})\},?)+\]$"""); var (_, children) = await Ok(HttpMethod.Get, $"/api/v1/identity/groups/{parentId}/children"); Match(children, $$"""^\[\{"id":{{childId}},"name":"{{name}}-c2","parentId":{{parentId}},"groupType":null,"description":null,"createdAt":{{Time}},"modifiedAt":(null|{{Time}})\}\]$"""); var (_, search) = await Ok(HttpMethod.Get, $"/api/v1/identity/groups/search?query={name}-c2"); Match(search, """^\{"items":\[.*\],"total":\d+,"offset":0,"count":\d+\}$"""); Match(search, $$"""\{"id":{{childId}},"name":"{{name}}-c2","parentId":{{parentId}},"groupType":null,"description":null,"createdAt":{{Time}},"modifiedAt":(null|{{Time}}),"memberCount":0\}"""); var userId = await CreateUserAsync(); var (_, added) = await Ok(HttpMethod.Post, $"/api/v1/identity/groups/{childId}/members", new { userId = long.Parse(userId), role = "member" }); Match(added, $$"""^\{"success":true,"membershipId":\d+,"groupId":{{childId}},"userId":{{userId}},"role":"member"\}$"""); var (_, changed) = await Ok(HttpMethod.Put, $"/api/v1/identity/groups/{childId}/members/{userId}", new { role = "owner" }); changed.Should().Be($$"""{"success":true,"groupId":{{childId}},"userId":{{userId}},"role":"owner"}"""); var (_, check) = await Ok(HttpMethod.Get, $"/api/v1/identity/groups/{childId}/members/{userId}/check"); check.Should().Be($$"""{"isMember":true,"groupId":{{childId}},"userId":{{userId}}}"""); var (_, removed) = await Ok(HttpMethod.Delete, $"/api/v1/identity/groups/{childId}/members/{userId}"); removed.Should().Be($$"""{"success":true,"groupId":{{childId}},"userId":{{userId}}}"""); var (_, other) = await Ok(HttpMethod.Post, "/api/v1/identity/groups", new { name = name + "-o" }); var otherId = Id(other); var (_, moved) = await Ok(HttpMethod.Post, $"/api/v1/identity/groups/{childId}/move", new { newParentGroupId = long.Parse(otherId) }); moved.Should().Be($$"""{"success":true,"groupId":{{childId}},"newParentGroupId":{{otherId}}}"""); var (_, deleted) = await Ok(HttpMethod.Delete, $"/api/v1/identity/groups/{childId}"); deleted.Should().Be($$"""{"success":true,"groupId":{{childId}}}"""); } [Fact] public async Task Roles_answer_success_and_the_error_document() { var (_, created) = await Ok(HttpMethod.Post, "/api/v1/identity/roles", new { name = "wire_" + Guid.NewGuid().ToString("N")[..8] }); var (_, deleted) = await Ok(HttpMethod.Delete, $"/api/v1/identity/roles/{Id(created)}"); deleted.Should().Be("""{"success":true}"""); var (status, missing) = await SendAsync(HttpMethod.Get, "/api/v1/identity/roles/987654321"); status.Should().Be(HttpStatusCode.NotFound, missing); Match(missing, """^\{"error":"not_found","error_description":"[^"]+"\}$"""); } [Fact] public async Task Claim_definitions_answer_success_and_the_error_document() { var (_, created) = await Ok(HttpMethod.Post, "/api/v1/identity/claim-definitions", new { claimName = "wire_" + Guid.NewGuid().ToString("N")[..8] }); var (_, deleted) = await Ok(HttpMethod.Delete, $"/api/v1/identity/claim-definitions/{Id(created)}"); deleted.Should().Be("""{"success":true}"""); var (status, missing) = await SendAsync(HttpMethod.Get, "/api/v1/identity/claim-definitions/987654321"); status.Should().Be(HttpStatusCode.NotFound, missing); missing.Should().Be("""{"error":"not_found","error_description":"ClaimDefinition 987654321 not found"}"""); } [Fact] public async Task A_claim_mapper_delete_answers_success() { var (_, created) = await Ok(HttpMethod.Post, "/api/v1/identity/claim-mappers", new { name = "wire_" + Guid.NewGuid().ToString("N")[..8], claimType = "wire_claim", sourceKind = "Constant", constantValue = "x" }); var (_, deleted) = await Ok(HttpMethod.Delete, $"/api/v1/identity/claim-mappers/{Id(created)}"); deleted.Should().Be("""{"success":true}"""); } [Fact] public async Task A_claim_scope_delete_answers_what_it_cascaded() { var name = "wire_" + Guid.NewGuid().ToString("N")[..8]; var (_, created) = await Ok(HttpMethod.Post, "/api/v1/identity/claim-scopes", new { name }); var (_, deleted) = await Ok(HttpMethod.Delete, $"/api/v1/identity/claim-scopes/{Id(created)}"); deleted.Should().Be("""{"success":true,"cascadedAssignments":0,"cascadedMappers":0}"""); } [Fact] public async Task A_federation_provider_delete_answers_success() { var providerId = "wire-" + Guid.NewGuid().ToString("N")[..8]; var (_, created) = await Ok(HttpMethod.Post, "/api/v1/identity/federation-providers", new { providerId, kind = "oidc", displayName = "Wire", authority = "http://example.invalid/", clientId = "x" }); var (_, deleted) = await Ok(HttpMethod.Delete, $"/api/v1/identity/federation-providers/{Id(created)}"); deleted.Should().Be("""{"success":true}"""); } [Fact] public async Task Webhooks_answer_success_the_deliveries_and_the_error_document() { var (_, created) = await Ok(HttpMethod.Post, "/api/v1/identity/webhooks", new { url = "http://127.0.0.1:9/wire", displayName = "wire", eventTypeFilter = "UserCreated", enabled = false }); var id = Id(created); var (_, updated) = await Ok(HttpMethod.Put, $"/api/v1/identity/webhooks/{id}", new { displayName = "wire2" }); updated.Should().Be("""{"success":true}"""); var (_, deliveries) = await Ok(HttpMethod.Get, $"/api/v1/identity/webhooks/deliveries?destination={id}"); Match(deliveries, """^\{"items":\[\],"offset":0,"count":\d+\}$"""); var (status, missing) = await SendAsync(HttpMethod.Get, "/api/v1/identity/webhooks/987654321"); status.Should().Be(HttpStatusCode.NotFound, missing); missing.Should().Be("""{"error":"not_found","error_description":"Webhook 987654321 not found"}"""); var (_, deleted) = await Ok(HttpMethod.Delete, $"/api/v1/identity/webhooks/{id}"); deleted.Should().Be("""{"success":true}"""); } [Fact] public async Task Impersonation_answers_its_target_the_stop_and_the_error_document() { var userId = await CreateUserAsync(); var (startStatus, started) = await SendAsync(HttpMethod.Post, $"/api/v1/identity/admin/impersonate/start/{userId}", new { reason = "wire" }); startStatus.Should().Be(HttpStatusCode.OK, started); Match(started, $$"""^\{"targetUserId":{{userId}},"targetLogin":"wire-[0-9a-f]+"\}$"""); var (_, stopped) = await Ok(HttpMethod.Post, $"/api/v1/identity/admin/impersonate/stop/{userId}", new { }); stopped.Should().Be("""{"stopped":true}"""); var (status, missing) = await SendAsync(HttpMethod.Post, "/api/v1/identity/admin/impersonate/start/987654321", new { reason = "wire" }); status.Should().Be(HttpStatusCode.NotFound, missing); missing.Should().Be("""{"error":"not_found","error_description":"User 987654321 not found"}"""); } private static void Match(string body, string pattern) => Regex.IsMatch(body, pattern).Should().BeTrue(body); [Fact] public async Task Sessions_answer_the_page_the_preview_and_the_counts() { var (_, page) = await Ok(HttpMethod.Get, "/api/v1/identity/sessions?offset=0&count=25"); Match(page, """^\{"items":\[.*\],"total":\d+,"offset":0,"count":25\}$"""); var userId = await CreateUserAsync(); var (_, preview) = await Ok(HttpMethod.Delete, $"/api/v1/identity/sessions/all?userId={userId}&dryRun=true"); preview.Should().Be("""{"success":true,"dryRun":true,"wouldRevoke":0,"sampleSessionIds":[]}"""); var (_, revokedAll) = await Ok(HttpMethod.Delete, $"/api/v1/identity/sessions/all?userId={userId}"); revokedAll.Should().Be("""{"success":true,"revoked":0}"""); var (_, revoked) = await Ok(HttpMethod.Delete, "/api/v1/identity/sessions?sessionId=987654321"); revoked.Should().Be("""{"success":true,"revoked":0}"""); var (_, loggedOut) = await Ok(HttpMethod.Post, $"/api/v1/identity/sessions/logout?userId={userId}"); loggedOut.Should().Be("""{"success":true,"sessionsRevoked":0}"""); } private async Task CreateUserAsync() { var login = "wire-" + Guid.NewGuid().ToString("N")[..10]; var (_, body) = await Ok(HttpMethod.Post, "/api/v1/identity/users", new { login, password = "Str0ng!Passw0rd", displayName = login }); return Id(body); } private async Task<(HttpStatusCode Status, string Body)> Ok(HttpMethod method, string path, object? content = null) { var (status, body) = await SendAsync(method, path, content); status.Should().Be(HttpStatusCode.OK, $"{method} {path}: {body}"); return (status, body); } private async Task<(HttpStatusCode Status, string Body)> SendAsync(HttpMethod method, string path, object? content = null) { using var request = new HttpRequestMessage(method, path); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); if (content is not null) request.Content = JsonContent.Create(content); using var response = await _fx.Http.SendAsync(request); return (response.StatusCode, await response.Content.ReadAsStringAsync()); } private static string Id(string json) { using var document = JsonDocument.Parse(json); var id = document.RootElement.GetProperty("id"); return id.ValueKind == JsonValueKind.Number ? id.GetInt64().ToString() : id.GetString()!; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/ApplicationRequestUrisTests.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/ApplicationRequestUrisTests.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// A client's registered request_uris over the HTTP management API, stored on the provider under test: set /// by update, read back exactly (fragment included), cleared by an empty array. /// [Collection("ProductionHttp")] public class ApplicationRequestUrisTests { private const string Path = "/api/v1/identity/applications"; private readonly ProductionHttpFixture _fx; public ApplicationRequestUrisTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Request_uris_round_trip_through_the_store() { var clientId = "requri-" + Guid.NewGuid().ToString("N")[..12]; var (created, createdBody) = await Send(HttpMethod.Post, Path, new { clientId, displayName = "Request URIs", clientType = "confidential", clientSecret = "requri-secret-" + Guid.NewGuid().ToString("N"), }); ((int)created).Should().BeInRange(200, 299, createdBody); var id = Json(createdBody).GetProperty("id").GetString(); string[] uris = ["https://client.example.com/ro.jwt#q9_hash", "https://client.example.com/ro2.jwt?v=1"]; var (updated, updatedBody) = await Send(HttpMethod.Put, $"{Path}/{id}", new { requestUris = uris }); ((int)updated).Should().BeInRange(200, 299, updatedBody); var (_, read) = await Send(HttpMethod.Get, $"{Path}/{id}", null); Json(read).GetProperty("requestUris").EnumerateArray().Select(e => e.GetString()).Should().Equal(uris); var (_, cleared) = await Send(HttpMethod.Put, $"{Path}/{id}", new { requestUris = Array.Empty() }); var left = Json(cleared).TryGetProperty("requestUris", out var after) && after.ValueKind is JsonValueKind.Array ? after.GetArrayLength() : 0; left.Should().Be(0, cleared); } private async Task<(System.Net.HttpStatusCode Status, string Body)> Send(HttpMethod method, string path, object? body) { using var request = new HttpRequestMessage(method, path); if (body is not null) request.Content = JsonContent.Create(body); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); using var response = await _fx.Http.SendAsync(request); return (response.StatusCode, await response.Content.ReadAsStringAsync()); } private static JsonElement Json(string body) => JsonDocument.Parse(body).RootElement; } Path: redb-identity/tests/redb.Identity.Tests/FullStack/AuditActorTests.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/AuditActorTests.cs ---- using Microsoft.Extensions.DependencyInjection; using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Serialization; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// An audit row of a change made through the management or account API records who made it: the client of the /// access token in client_id, the token's subject in actor_subject (the client id for a /// client-credentials token, the user's public subject for a user token), and the caller's address. /// [Collection("ProductionHttp")] public class AuditActorTests { private readonly ProductionHttpFixture _fx; public AuditActorTests(ProductionHttpFixture fx) => _fx = fx; private sealed class Row { [JsonPropertyName("client_id")] public string? ClientId { get; set; } [JsonPropertyName("actor_subject")] public string? ActorSubject { get; set; } [JsonPropertyName("ip_address")] public string? IpAddress { get; set; } [JsonPropertyName("details")] public string? Details { get; set; } } /// The audit write runs on a WireTap after the answer, so the row is polled for. private async Task AuditRowAsync(string eventType, string detailsContains) { for (var i = 0; i < 50; i++) { var rows = await _fx.UseRedbAsync(redb => redb.Context.QueryAsync( "SELECT client_id, actor_subject, ip_address, details FROM identity_audit_log WHERE event_type = @p0", eventType)); var row = rows.FirstOrDefault(r => r.Details?.Contains(detailsContains, StringComparison.Ordinal) == true); if (row is not null) return row; await Task.Delay(100); } throw new InvalidOperationException($"No {eventType} audit row containing '{detailsContains}'."); } private async Task SendAsync(string token, HttpMethod method, string path, object body) { using var request = new HttpRequestMessage(method, path) { Content = JsonContent.Create(body) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); using var response = await _fx.Http.SendAsync(request); var text = await response.Content.ReadAsStringAsync(); ((int)response.StatusCode).Should().BeInRange(200, 299, $"{method} {path}: {text}"); return text.Length == 0 ? default : JsonDocument.Parse(text).RootElement.Clone(); } [Fact] public async Task A_management_change_records_the_acting_client_and_subject() { var clientId = "audit-actor-" + Guid.NewGuid().ToString("N")[..10]; await SendAsync(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/applications", new { clientId, clientSecret = "audit-actor-secret-1234", clientType = "confidential", displayName = clientId, }); var row = await AuditRowAsync("ClientRegistered", clientId); row.ClientId.Should().Be(ProductionHttpFixture.TestMgmtClientId); row.ActorSubject.Should().Be(ProductionHttpFixture.TestMgmtClientId, "a client-credentials token's subject is the client"); row.IpAddress.Should().NotBeNullOrEmpty(); // The audit API answers the field (optional: absent for other events and for older rows). using var query = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/audit?eventType=ClientRegistered&count=50"); query.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); using var answer = await _fx.Http.SendAsync(query); var text = await answer.Content.ReadAsStringAsync(); answer.StatusCode.Should().Be(HttpStatusCode.OK, text); var item = JsonDocument.Parse(text).RootElement.GetProperty("items").EnumerateArray() .First(i => i.GetRawText().Contains(clientId, StringComparison.Ordinal)); item.GetProperty("actorSubject").GetString().Should().Be(ProductionHttpFixture.TestMgmtClientId); } [Fact] public async Task An_account_change_records_the_users_public_subject_not_an_internal_id() { var login = "auditactor" + Guid.NewGuid().ToString("N")[..10]; var user = await SendAsync(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/users", new { login, password = "Str0ng!Passw0rd", displayName = login }); var internalId = user.GetProperty("id").GetInt64(); var clientId = login + "-client"; const string secret = "audit-actor-client-secret-1234"; await SendAsync(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/applications", new { clientId, clientSecret = secret, displayName = clientId, permissions = new[] { "ept:token", "gt:password", "scp:openid", "scp:identity:account" }, }); using var tokenResponse = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = login, ["password"] = "Str0ng!Passw0rd", ["scope"] = "openid identity:account", ["client_id"] = clientId, ["client_secret"] = secret, })); var tokenBody = await tokenResponse.Content.ReadAsStringAsync(); tokenResponse.StatusCode.Should().Be(HttpStatusCode.OK, tokenBody); var token = JsonDocument.Parse(tokenBody).RootElement.GetProperty("access_token").GetString()!; var subject = JsonDocument.Parse(Microsoft.IdentityModel.Tokens.Base64UrlEncoder.Decode(token.Split('.')[1])) .RootElement.GetProperty("sub").GetString()!; await SendAsync(token, HttpMethod.Put, "/api/v1/identity/me/password", new { oldPassword = "Str0ng!Passw0rd", newPassword = "N3w!Str0ngPassw0rd" }); var row = await AuditRowAsync("PasswordChanged", login); row.ClientId.Should().Be(clientId); row.ActorSubject.Should().Be(subject).And.NotBe(internalId.ToString(System.Globalization.CultureInfo.InvariantCulture)); Guid.TryParse(row.ActorSubject, out _).Should().BeTrue("the public subject is a GUID"); row.IpAddress.Should().NotBeNullOrEmpty(); } /// /// A table of an earlier version gains actor_subject at start, and the step is safe to run again, as a /// second node starting later (or at once) does. Run against a scratch table of the old shape with the exact /// statement of this provider's script; SQLite, which has no ADD COLUMN IF NOT EXISTS, through the listener's /// own step. /// [Fact] public async Task The_actor_subject_column_is_added_to_an_older_table_and_the_step_can_run_again() { var table = "audit_probe_" + Guid.NewGuid().ToString("N")[..10]; var provider = _fx.ServiceProvider.GetRequiredService().ProviderName ?? ""; await _fx.UseRedbAsync(async redb => { await redb.Context.ExecuteAsync($"CREATE TABLE {table} (id BIGINT, client_id VARCHAR(200))"); try { for (var run = 0; run < 2; run++) { if (provider.Equals("Sqlite", StringComparison.OrdinalIgnoreCase)) { await global::redb.Identity.Core.Module.IdentityAuditLogTableInitListener.AddSqliteColumnAsync(redb, table, "actor_subject", "TEXT"); } else { var isPg = provider.Equals("PostgreSQL", StringComparison.OrdinalIgnoreCase); var script = global::redb.Identity.Core.Module.IdentityAuditLogTableInitListener.ReadEmbedded(isPg ? "redb.Identity.Core.sql.audit.pg_create_table.sql" : "redb.Identity.Core.sql.audit.mssql_create_table.sql")!; string statement; if (isPg) { statement = script.Split('\n').Single(l => l.Contains("ADD COLUMN IF NOT EXISTS actor_subject")).Trim(); } else { var start = script.IndexOf("IF NOT EXISTS (SELECT 1 FROM sys.columns", script.IndexOf("-- actor_subject:", StringComparison.Ordinal), StringComparison.Ordinal); var end = script.IndexOf("END;", start, StringComparison.Ordinal) + "END;".Length; statement = script[start..end]; } await redb.Context.ExecuteAsync(statement.Replace("identity_audit_log", table, StringComparison.Ordinal)); } } // The column is there exactly once and takes a value. await redb.Context.ExecuteAsync($"INSERT INTO {table} (id, client_id, actor_subject) VALUES (1, 'c', 's')"); (await redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM {table} WHERE actor_subject = 's'")).Should().Be(1); } finally { await redb.Context.ExecuteAsync($"DROP TABLE {table}"); } return 0; }); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/AuditCompletenessFullCycleTests.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/AuditCompletenessFullCycleTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// H6 / H7 (v1.0 DoD): every well-formed Introspection / Revocation / Device-Authorization /// request emits the expected entry in the audit catalog. /// /// Path: HTTP → Kestrel → HTTP facade → core route → OpenIddict pipeline → WireTap → /// EventDispatchProcessor → AuditEventSinkProcessor → PROPS → admin GET /audit query. /// /// [Collection("ProductionHttp")] public class AuditCompletenessFullCycleTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public AuditCompletenessFullCycleTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } // ══════════════════════════════════════════════ // H6 — Introspection (RFC 7662) // ══════════════════════════════════════════════ [Fact] public async Task Introspection_EmitsTokenIntrospectedAuditEvent() { var token = await ObtainAccessTokenAsync(); var resp = await _http.PostAsync("/connect/introspect", new FormUrlEncodedContent(new Dictionary { ["token"] = token, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret })); resp.StatusCode.Should().Be(HttpStatusCode.OK, "RFC 7662 §2.2: introspection must answer 200 — got {0}: {1}", resp.StatusCode, await resp.Content.ReadAsStringAsync()); // No fixed sleep: QueryAuditAsync polls until the row appears (the WireTap audit branch // finishes after the HTTP response). var rows = await QueryAuditAsync("TokenIntrospected"); rows.Should().NotBeEmpty( "core processor must emit audit catalog event TokenIntrospected after a well-formed introspection"); } // ══════════════════════════════════════════════ // H6 — Revocation (RFC 7009) // ══════════════════════════════════════════════ [Fact] public async Task Revocation_EmitsTokenRevokedAuditEvent() { // Use refresh-token: RFC 7009 §2: introspectable & revocable for confidential clients. var (_, refresh) = await ObtainAccessAndRefreshAsync(); var resp = await _http.PostAsync("/connect/revocation", new FormUrlEncodedContent(new Dictionary { ["token"] = refresh, ["token_type_hint"] = "refresh_token", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret })); resp.StatusCode.Should().Be(HttpStatusCode.OK, "RFC 7009 §2.2: revocation must answer 200 — got {0}: {1}", resp.StatusCode, await resp.Content.ReadAsStringAsync()); // No fixed sleep: QueryAuditAsync polls until the row appears (the WireTap audit branch // finishes after the HTTP response). var rows = await QueryAuditAsync("TokenRevoked"); rows.Should().NotBeEmpty( "core processor must emit audit catalog event TokenRevoked after a well-formed revocation"); } // ══════════════════════════════════════════════ // H7 — Device Authorization (RFC 8628) // ══════════════════════════════════════════════ [Fact] public async Task DeviceAuthorization_EmitsDeviceCodeIssuedAuditEvent() { var resp = await _http.PostAsync("/connect/deviceauthorization", new FormUrlEncodedContent(new Dictionary { ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["scope"] = "openid" })); resp.StatusCode.Should().Be(HttpStatusCode.OK, "RFC 8628 §3.2: device authorization must answer 200 — got {0}: {1}", resp.StatusCode, await resp.Content.ReadAsStringAsync()); // No fixed sleep: QueryAuditAsync polls until the row appears (the WireTap audit branch // finishes after the HTTP response). var rows = await QueryAuditAsync("DeviceCodeIssued"); rows.Should().NotBeEmpty( "core processor must emit audit catalog event DeviceCodeIssued after issuing a device_code"); } // ══════════════════════════════════════════════ // helpers // ══════════════════════════════════════════════ private async Task ObtainAccessTokenAsync() { var resp = await _http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, // 'groups' is registered globally by RedbIdentityServer and granted to TestClientId. ["scope"] = "groups" })); resp.IsSuccessStatusCode.Should().BeTrue( "obtain access token failed: {0}", await resp.Content.ReadAsStringAsync()); var json = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; return json.GetProperty("access_token").GetString()!; } private async Task<(string Access, string Refresh)> ObtainAccessAndRefreshAsync() { var resp = await _http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid offline_access groups" })); resp.IsSuccessStatusCode.Should().BeTrue( "obtain refresh token failed: {0}", await resp.Content.ReadAsStringAsync()); var json = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; return ( json.GetProperty("access_token").GetString()!, json.GetProperty("refresh_token").GetString()!); } private async Task> QueryAuditAsync(string eventType) { // Polling retry: GET /audit can transiently return 503 / "Database temporarily // unavailable" when the in-process audit pipeline is still flushing its // background INSERT batch onto the same NpgsqlConnection pool slot that the // /audit SELECT now wants. OnException in IdentityCoreRouteBuilder // catches it and returns the 503 envelope; we poll a few times so a 100-200 ms // window of contention doesn't fail the test. Each attempt opens a fresh HTTP // request → fresh per-request DI scope → fresh connection from the pool. HttpResponseMessage? lastResp = null; string lastBody = string.Empty; var started = System.Diagnostics.Stopwatch.StartNew(); for (var attempt = 0; attempt < 10; attempt++) { using var req = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/identity/audit?eventType={eventType}&count=50"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); lastResp = await _http.SendAsync(req); lastBody = await lastResp.Content.ReadAsStringAsync(); if (lastResp.IsSuccessStatusCode) { var doc = JsonDocument.Parse(lastBody); var items = doc.RootElement.GetProperty("items").EnumerateArray().ToList(); // Keep polling while the answer is an EMPTY success, not only while it is a 503. // The audit row is written by a WireTap branch that finishes after the response the // caller already got, so "200 with no rows yet" is the normal first answer under load // — and returning it immediately is what made these tests depend on a fixed sleep. if (items.Count > 0) { if (attempt > 0) Console.Error.WriteLine( $"QueryAuditAsync({eventType}): row appeared on attempt {attempt + 1} after {started.ElapsedMilliseconds} ms"); return items; } } await Task.Delay(300); } lastResp!.IsSuccessStatusCode.Should().BeTrue( "GET /audit failed after 10 attempts: {0} {1}", lastResp.StatusCode, lastBody); // Ten successful-but-empty answers: the event genuinely never arrived. Report how long we // waited — that is what separates "audit is slow" from "audit never fired" if this fails — // and let the caller's assertion name the missing event type. Console.Error.WriteLine( $"QueryAuditAsync({eventType}): no row after 10 attempts / {started.ElapsedMilliseconds} ms"); return new List(); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/ConcurrentDuplicateStatusTests.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/ConcurrentDuplicateStatusTests.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Contracts.Scim; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.FullStack; /// /// Concurrent creation of one and the same record through the HTTP surface. The check before the /// insert cannot serialise the callers, so the losers reach the database and are refused by a /// unique key. That refusal is a conflict the caller caused: it must be answered 409, never 500. /// The answer depends on which exception type the provider raises, so these tests are worth /// running on every provider. /// [Collection("ProductionHttp")] public class ConcurrentDuplicateStatusTests { private const int Callers = 6; private readonly ProductionHttpFixture _fx; private readonly ITestOutputHelper _out; public ConcurrentDuplicateStatusTests(ProductionHttpFixture fx, ITestOutputHelper output) { _fx = fx; _out = output; } [Fact] public async Task FederationProvider_ConcurrentSameProviderId_OneCreated_OthersConflict() { var providerId = "race-" + Guid.NewGuid().ToString("N")[..12]; var statuses = await SendConcurrentlyAsync(() => Management("/api/v1/identity/federation-providers", new { providerId, kind = "oidc", displayName = "Race " + providerId, authority = "https://idp.example.test/", clientId = "race-client", clientSecret = "race-secret", enabled = false, })); // A loser that arrives after the winner committed is refused by the processor's own check, one // that was already past the check by the unique key. The caller sees the same 409 either way. AssertOneWinnerOthersConflict(statuses); } [Fact] public async Task FederationProvider_SecondCreateOfTheSameProviderId_Answers409() { var providerId = "dup-" + Guid.NewGuid().ToString("N")[..12]; object Body() => new { providerId, kind = "oidc", displayName = "Duplicate " + providerId, authority = "https://idp.example.test/", clientId = "dup-client", clientSecret = "dup-secret", enabled = false, }; using var first = await _fx.Http.SendAsync(Management("/api/v1/identity/federation-providers", Body())); ((int)first.StatusCode).Should().BeInRange(200, 299, await first.Content.ReadAsStringAsync()); using var second = await _fx.Http.SendAsync(Management("/api/v1/identity/federation-providers", Body())); var answer = await second.Content.ReadAsStringAsync(); ((int)second.StatusCode).Should().Be(409, answer); answer.Should().Contain("\"duplicate\""); } [Fact] public async Task Scope_ConcurrentSameName_OneCreated_OthersConflict() { var name = "race-scope-" + Guid.NewGuid().ToString("N")[..12]; var statuses = await SendConcurrentlyAsync(() => Management("/api/v1/identity/scopes", new { name })); AssertOneWinnerOthersConflict(statuses); } [Fact] public async Task ScimUser_ConcurrentSameUserName_OneCreated_OthersConflict() { var user = new ScimUser { UserName = "race-scim-" + Guid.NewGuid().ToString("N")[..12], Active = true }; var statuses = await SendConcurrentlyAsync(() => { var request = new HttpRequestMessage(HttpMethod.Post, "/scim/v2/Users") { Content = new StringContent(JsonSerializer.Serialize(user), Encoding.UTF8, ScimConstants.MediaType), }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ScimToken); return request; }); AssertOneWinnerOthersConflict(statuses); } [Fact] public async Task Group_ConcurrentSameName_OneCreated_OthersConflict() { // Group names are unique: exactly one caller creates the group, the others are told 409. var name = "race-group-" + Guid.NewGuid().ToString("N")[..12]; var statuses = await SendConcurrentlyAsync(() => Management("/api/v1/identity/groups", new { name })); AssertOneWinnerOthersConflict(statuses); } private HttpRequestMessage Management(string path, object body) { var request = new HttpRequestMessage(HttpMethod.Post, path) { Content = JsonContent.Create(body) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return request; } private async Task SendConcurrentlyAsync(Func newRequest) { var responses = await Task.WhenAll( Enumerable.Range(0, Callers).Select(_ => _fx.Http.SendAsync(newRequest()))); try { foreach (var response in responses) _out.WriteLine($"[{(int)response.StatusCode}] {await response.Content.ReadAsStringAsync()}"); return responses.Select(r => (int)r.StatusCode).OrderBy(s => s).ToArray(); } finally { foreach (var response in responses) response.Dispose(); } } private static void AssertOneWinnerOthersConflict(int[] statuses) { statuses.Should().OnlyContain(s => s < 500, "a duplicate is the caller's conflict, not a server failure"); statuses.Count(s => s is >= 200 and < 300).Should().Be(1, "exactly one caller may create the record"); statuses.Count(s => s == 409).Should().Be(Callers - 1, "every other caller must be told 409"); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/DpopBoundTokenResourceTests.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/DpopBoundTokenResourceTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Text.Json; using AwesomeAssertions; using Microsoft.IdentityModel.Tokens; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// RFC 9449 §7: a DPoP-bound access token (cnf.jkt) is usable at the server's own protected endpoints, /// /connect/userinfo and the management API, only under the DPoP scheme with a fresh proof signed by /// the bound key and carrying the token hash (ath). Without the proof it must not work as a bearer token. /// [Collection("ProductionHttp")] public class DpopBoundTokenResourceTests { private const string UserinfoPath = "/connect/userinfo"; private const string ManagementPath = "/api/v1/identity/applications"; private readonly ProductionHttpFixture _fx; public DpopBoundTokenResourceTests(ProductionHttpFixture fx) => _fx = fx; // ─── /connect/userinfo ─── [Fact] public async Task Userinfo_BoundToken_AsBearerWithoutProof_IsRejected() { using var ec = NewKey(); var token = await PasswordTokenAsync(ec); using var req = new HttpRequestMessage(HttpMethod.Get, UserinfoPath); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Userinfo_BoundToken_AsBearerWithValidProof_IsRejected() { using var ec = NewKey(); var token = await PasswordTokenAsync(ec); using var req = new HttpRequestMessage(HttpMethod.Get, UserinfoPath); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); req.Headers.Add("DPoP", BuildProof(ec, "GET", Url(UserinfoPath), token)); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Userinfo_BoundToken_WithDpopSchemeAndValidProof_IsAccepted() { using var ec = NewKey(); var token = await PasswordTokenAsync(ec); using var req = DpopRequest(HttpMethod.Get, UserinfoPath, token, BuildProof(ec, "GET", Url(UserinfoPath), token)); var resp = await _fx.Http.SendAsync(req); var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.OK, body); JsonDocument.Parse(body).RootElement.TryGetProperty("sub", out _).Should().BeTrue(); } [Fact] public async Task Userinfo_BoundToken_WithDpopSchemeAndProofWithoutAth_IsRejected() { using var ec = NewKey(); var token = await PasswordTokenAsync(ec); using var req = DpopRequest(HttpMethod.Get, UserinfoPath, token, BuildProof(ec, "GET", Url(UserinfoPath), accessToken: null)); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Userinfo_BoundToken_WithProofFromAnotherKey_IsRejected() { using var ec = NewKey(); using var other = NewKey(); var token = await PasswordTokenAsync(ec); using var req = DpopRequest(HttpMethod.Get, UserinfoPath, token, BuildProof(other, "GET", Url(UserinfoPath), token)); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Userinfo_BoundToken_WithReplayedProof_IsRejected() { using var ec = NewKey(); var token = await PasswordTokenAsync(ec); var proof = BuildProof(ec, "GET", Url(UserinfoPath), token); using var first = DpopRequest(HttpMethod.Get, UserinfoPath, token, proof); var firstResp = await _fx.Http.SendAsync(first); firstResp.StatusCode.Should().Be(HttpStatusCode.OK, await firstResp.Content.ReadAsStringAsync()); using var second = DpopRequest(HttpMethod.Get, UserinfoPath, token, proof); var secondResp = await _fx.Http.SendAsync(second); secondResp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await secondResp.Content.ReadAsStringAsync()); } [Fact] public async Task Userinfo_BoundToken_WithProofForAnotherUrl_IsRejected() { using var ec = NewKey(); var token = await PasswordTokenAsync(ec); using var req = DpopRequest(HttpMethod.Get, UserinfoPath, token, BuildProof(ec, "GET", Url(ManagementPath), token)); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Userinfo_BoundToken_WithStaleProof_IsRejected() { using var ec = NewKey(); var token = await PasswordTokenAsync(ec); var stale = DateTimeOffset.UtcNow.AddMinutes(-10); using var req = DpopRequest(HttpMethod.Get, UserinfoPath, token, BuildProof(ec, "GET", Url(UserinfoPath), token, stale)); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Userinfo_BoundToken_AsBearer_AnswersWithDpopChallenge() { using var ec = NewKey(); var token = await PasswordTokenAsync(ec); using var req = new HttpRequestMessage(HttpMethod.Get, UserinfoPath); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); AssertDpopChallenge(resp); } [Fact] public async Task Userinfo_UnboundToken_WithDpopScheme_IsRejected() { var token = await PasswordTokenAsync(dpopKey: null); using var ec = NewKey(); using var req = DpopRequest(HttpMethod.Get, UserinfoPath, token, BuildProof(ec, "GET", Url(UserinfoPath), token)); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Userinfo_UnboundToken_AsBearer_IsStillAccepted() { var token = await PasswordTokenAsync(dpopKey: null); using var req = new HttpRequestMessage(HttpMethod.Get, UserinfoPath); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, await resp.Content.ReadAsStringAsync()); } // ─── management API ─── [Fact] public async Task Management_BoundToken_AsBearerWithoutProof_IsRejected() { using var ec = NewKey(); var token = await ManagementTokenAsync(ec); using var req = new HttpRequestMessage(HttpMethod.Get, ManagementPath); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Management_BoundToken_WithDpopSchemeAndValidProof_IsAccepted() { using var ec = NewKey(); var token = await ManagementTokenAsync(ec); using var req = DpopRequest(HttpMethod.Get, ManagementPath, token, BuildProof(ec, "GET", Url(ManagementPath), token)); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Management_BoundToken_WithReplayedProof_IsRejected() { using var ec = NewKey(); var token = await ManagementTokenAsync(ec); var proof = BuildProof(ec, "GET", Url(ManagementPath), token); using var first = DpopRequest(HttpMethod.Get, ManagementPath, token, proof); var firstResp = await _fx.Http.SendAsync(first); firstResp.StatusCode.Should().Be(HttpStatusCode.OK, await firstResp.Content.ReadAsStringAsync()); using var second = DpopRequest(HttpMethod.Get, ManagementPath, token, proof); var secondResp = await _fx.Http.SendAsync(second); secondResp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await secondResp.Content.ReadAsStringAsync()); } [Fact] public async Task Management_BoundToken_WithProofForAnotherMethod_IsRejected() { using var ec = NewKey(); var token = await ManagementTokenAsync(ec); using var req = DpopRequest(HttpMethod.Get, ManagementPath, token, BuildProof(ec, "POST", Url(ManagementPath), token)); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Management_BoundToken_WithStaleProof_IsRejected() { using var ec = NewKey(); var token = await ManagementTokenAsync(ec); var stale = DateTimeOffset.UtcNow.AddMinutes(-10); using var req = DpopRequest(HttpMethod.Get, ManagementPath, token, BuildProof(ec, "GET", Url(ManagementPath), token, stale)); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Management_BoundToken_AsBearer_AnswersWithDpopChallenge() { using var ec = NewKey(); var token = await ManagementTokenAsync(ec); using var req = new HttpRequestMessage(HttpMethod.Get, ManagementPath); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); AssertDpopChallenge(resp); } [Fact] public async Task Management_UnboundToken_WithDpopScheme_IsRejected() { using var ec = NewKey(); using var req = DpopRequest(HttpMethod.Get, ManagementPath, _fx.ManagementToken, BuildProof(ec, "GET", Url(ManagementPath), _fx.ManagementToken)); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, await resp.Content.ReadAsStringAsync()); } // ─── helpers ─── private static ECDsa NewKey() => ECDsa.Create(ECCurve.NamedCurves.nistP256); /// RFC 9449 §7.1: the 401 names the DPoP scheme and carries the error. private static void AssertDpopChallenge(HttpResponseMessage resp) { var challenge = resp.Headers.WwwAuthenticate.Select(h => h.ToString()).ToArray(); challenge.Should().ContainSingle(h => h.StartsWith("DPoP ", StringComparison.Ordinal), string.Join(" | ", challenge)); challenge.Single(h => h.StartsWith("DPoP ", StringComparison.Ordinal)).Should().Contain("error=\"invalid_token\""); } private string Url(string path) => $"{_fx.BaseUrl.TrimEnd('/')}{path}"; private static HttpRequestMessage DpopRequest(HttpMethod method, string path, string token, string proof) { var req = new HttpRequestMessage(method, path); req.Headers.TryAddWithoutValidation("Authorization", $"DPoP {token}"); req.Headers.Add("DPoP", proof); return req; } /// Password grant for the confidential test client; DPoP-bound when is given. private async Task PasswordTokenAsync(ECDsa? dpopKey) { using var req = new HttpRequestMessage(HttpMethod.Post, "/connect/token") { Content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["scope"] = "openid" }) }; var basic = Convert.ToBase64String(Encoding.UTF8.GetBytes( $"{ProductionHttpFixture.TestClientId}:{ProductionHttpFixture.TestClientSecret}")); req.Headers.Authorization = new AuthenticationHeaderValue("Basic", basic); if (dpopKey is not null) req.Headers.Add("DPoP", BuildProof(dpopKey, "POST", Url("/connect/token"), accessToken: null)); return await ReadAccessTokenAsync(req, expectedType: dpopKey is null ? "Bearer" : "DPoP"); } /// client_credentials token with the management scope, bound to . private async Task ManagementTokenAsync(ECDsa dpopKey) { using var req = new HttpRequestMessage(HttpMethod.Post, "/connect/token") { Content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = ProductionHttpFixture.TestMgmtClientId, ["client_secret"] = ProductionHttpFixture.TestMgmtSecret, ["scope"] = "identity:manage" }) }; req.Headers.Add("DPoP", BuildProof(dpopKey, "POST", Url("/connect/token"), accessToken: null)); return await ReadAccessTokenAsync(req, expectedType: "DPoP"); } private async Task ReadAccessTokenAsync(HttpRequestMessage req, string expectedType) { var resp = await _fx.Http.SendAsync(req); var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.OK, body); var json = JsonDocument.Parse(body).RootElement; json.GetProperty("token_type").GetString().Should().Be(expectedType, body); return json.GetProperty("access_token").GetString()!; } /// ES256 DPoP proof (RFC 9449 §4.2); ath is the SHA-256 of when given. private static string BuildProof(ECDsa ec, string method, string url, string? accessToken, DateTimeOffset? issuedAt = null) { var pub = ec.ExportParameters(includePrivateParameters: false); var x = Base64UrlEncoder.Encode(pub.Q.X!); var y = Base64UrlEncoder.Encode(pub.Q.Y!); var headerJson = $"{{\"typ\":\"dpop+jwt\",\"alg\":\"ES256\",\"jwk\":{{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"{x}\",\"y\":\"{y}\"}}}}"; var iat = (issuedAt ?? DateTimeOffset.UtcNow).ToUnixTimeSeconds(); var jti = Guid.NewGuid().ToString("N"); var ath = accessToken is null ? string.Empty : $",\"ath\":\"{Base64UrlEncoder.Encode(SHA256.HashData(Encoding.ASCII.GetBytes(accessToken)))}\""; var payloadJson = $"{{\"htm\":\"{method}\",\"htu\":\"{url}\",\"iat\":{iat},\"jti\":\"{jti}\"{ath}}}"; var signingInput = $"{Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(headerJson))}.{Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(payloadJson))}"; var sig = ec.SignData(Encoding.ASCII.GetBytes(signingInput), HashAlgorithmName.SHA256); return $"{signingInput}.{Base64UrlEncoder.Encode(sig)}"; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/DpopFullCycleTests.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/DpopFullCycleTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; 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; /// /// Full-cycle E2E test for Demonstrating Proof of Possession (RFC 9449 / Z4). /// Scenarios: /// 1. Discovery advertises dpop_signing_alg_values_supported. /// 2. POST /connect/token with a valid DPoP proof yields token_type=DPoP and access token containing cnf.jkt. /// 3. Replay of the same DPoP proof at /token is rejected with invalid_dpop_proof. /// 4. Soft-mode default: requests without the DPoP header still succeed and return Bearer tokens. /// [Collection("ProductionHttp")] public class DpopFullCycleTests { private readonly ProductionHttpFixture _fx; public DpopFullCycleTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Discovery_Advertises_Dpop_Signing_Algs_When_Enabled() { var resp = await _fx.Http.GetAsync("/.well-known/openid-configuration"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; json.TryGetProperty("dpop_signing_alg_values_supported", out var algs) .Should().BeTrue("RFC 9449 §5.1: when DPoP is enabled the discovery doc must advertise the supported algs"); algs.ValueKind.Should().Be(JsonValueKind.Array); var values = algs.EnumerateArray().Select(e => e.GetString()).ToArray(); values.Should().Contain("ES256"); } [Fact] public async Task Token_With_Valid_DPoP_Proof_Returns_DPoP_TokenType_And_Cnf_Jkt_In_AccessToken() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); var url = $"{_fx.BaseUrl.TrimEnd('/')}/connect/token"; var proof = BuildDpopProof(ec, "POST", url); using var req = BuildPasswordTokenRequest(); req.Headers.Add("DPoP", proof); var resp = await _fx.Http.SendAsync(req); var bodyStr = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.OK, "token request with valid DPoP proof must succeed: {0}", bodyStr); var json = JsonDocument.Parse(bodyStr).RootElement; json.GetProperty("token_type").GetString().Should().Be("DPoP", "RFC 9449 §6: when proof is bound, token_type MUST be 'DPoP'"); var accessToken = json.GetProperty("access_token").GetString()!; var jwt = new JsonWebTokenHandler().ReadJsonWebToken(accessToken); jwt.TryGetPayloadValue("cnf", out var cnf).Should().BeTrue( "RFC 9449 §6.1: access tokens bound to a DPoP key MUST carry a 'cnf' claim"); cnf.GetProperty("jkt").GetString().Should().Be(ComputeJkt(ec)); } // Use of a DPoP-bound token at userinfo and the management API: DpopBoundTokenResourceTests. [Fact] public async Task Token_With_Replayed_DPoP_Proof_Is_Rejected() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); var url = $"{_fx.BaseUrl.TrimEnd('/')}/connect/token"; var proof = BuildDpopProof(ec, "POST", url); using var req1 = BuildPasswordTokenRequest(); req1.Headers.Add("DPoP", proof); var first = await _fx.Http.SendAsync(req1); first.StatusCode.Should().Be(HttpStatusCode.OK); using var req2 = BuildPasswordTokenRequest(); req2.Headers.Add("DPoP", proof); var second = await _fx.Http.SendAsync(req2); ((int)second.StatusCode).Should().BeGreaterThanOrEqualTo(400, "RFC 9449 §11.1: replayed DPoP proof must be rejected"); var body = JsonDocument.Parse(await second.Content.ReadAsStringAsync()).RootElement; body.GetProperty("error").GetString().Should().Be("invalid_dpop_proof"); } [Fact] public async Task Token_Without_DPoP_Header_Returns_Bearer_In_SoftMode() { using var req = BuildPasswordTokenRequest(); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, "baseline token request without DPoP must succeed in soft-mode: {0}", await resp.Content.ReadAsStringAsync()); var json = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; json.GetProperty("token_type").GetString().Should().Be("Bearer", "soft-mode default (RequireForAccessTokens=false): without DPoP header the server issues a plain Bearer token"); } [Fact] public async Task Token_With_Wrong_HtmClaim_Is_Rejected() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); var url = $"{_fx.BaseUrl.TrimEnd('/')}/connect/token"; var proof = BuildDpopProof(ec, "GET", url); // wrong method using var req = BuildPasswordTokenRequest(); req.Headers.Add("DPoP", proof); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().BeGreaterThanOrEqualTo(400); var body = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; body.GetProperty("error").GetString().Should().Be("invalid_dpop_proof"); } // ─── Behind a TLS-terminating reverse proxy ─── // // The proxy speaks plain HTTP to the server and reports the client's real origin in // X-Forwarded-Proto. RFC 9449 §4.3 makes the server compare the proof's `htu` with the URL the // client used, which is https://... on the client side and http://... on our socket. Without // host-level forwarded-header resolution the two never match and DPoP cannot be deployed behind // any TLS terminator. The fixture lists the loopback peer as a trusted proxy, so the header is // honoured; the control test below proves the header is what makes the difference. [Fact] public async Task Token_BehindTlsTerminator_HtuWithHttpsScheme_IsAccepted() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); // What the client actually used: https on the public side of the proxy. var publicUrl = $"https://localhost:{_fx.Port}/connect/token"; var proof = BuildDpopProof(ec, "POST", publicUrl); using var req = BuildPasswordTokenRequest(); req.Headers.Add("DPoP", proof); req.Headers.TryAddWithoutValidation("X-Forwarded-Proto", "https"); var resp = await _fx.Http.SendAsync(req); var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.OK, "behind a trusted TLS-terminating proxy the server must see the https URL the client signed: {0}", body); JsonDocument.Parse(body).RootElement.GetProperty("token_type").GetString().Should().Be("DPoP"); } [Fact] public async Task Token_WithoutForwardedProto_HtuWithHttpsScheme_IsRejected() { // Control: same proof, no forwarded header. The socket scheme is http, so the https `htu` // must not match. This pins that the previous test passes because of the header, not // because the scheme check is loose. using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); var publicUrl = $"https://localhost:{_fx.Port}/connect/token"; var proof = BuildDpopProof(ec, "POST", publicUrl); using var req = BuildPasswordTokenRequest(); req.Headers.Add("DPoP", proof); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().BeGreaterThanOrEqualTo(400); var body = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; body.GetProperty("error").GetString().Should().Be("invalid_dpop_proof"); } /// /// Builds a /token request authenticated with the confidential test client + ROPC. /// Adds Authorization: Basic with the client secret. /// private static HttpRequestMessage BuildPasswordTokenRequest() { var req = new HttpRequestMessage(HttpMethod.Post, "/connect/token") { Content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["scope"] = "openid" }) }; var basic = Convert.ToBase64String(Encoding.UTF8.GetBytes( $"{ProductionHttpFixture.TestClientId}:{ProductionHttpFixture.TestClientSecret}")); req.Headers.Authorization = new AuthenticationHeaderValue("Basic", basic); return req; } // ─── Helpers ─── /// /// Builds an ES256 DPoP proof JWT carrying typ=dpop+jwt header, embedded jwk (public key only), /// and claims htm/htu/iat/jti per RFC 9449 §4.2. /// private static string BuildDpopProof(ECDsa ec, string method, string url) { var pubParams = ec.ExportParameters(includePrivateParameters: false); var jwk = new JsonWebKey { Kty = "EC", Crv = "P-256", X = Base64UrlEncoder.Encode(pubParams.Q.X!), Y = Base64UrlEncoder.Encode(pubParams.Q.Y!), Alg = "ES256", }; var jwkJson = $"{{\"crv\":\"{jwk.Crv}\",\"kty\":\"{jwk.Kty}\",\"x\":\"{jwk.X}\",\"y\":\"{jwk.Y}\"}}"; var headerJson = $"{{\"typ\":\"dpop+jwt\",\"alg\":\"ES256\",\"jwk\":{jwkJson}}}"; var iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var jti = Guid.NewGuid().ToString("N"); var payloadJson = $"{{\"htm\":\"{method}\",\"htu\":\"{url}\",\"iat\":{iat},\"jti\":\"{jti}\"}}"; var headerB64 = Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(headerJson)); var payloadB64 = Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(payloadJson)); var signingInput = $"{headerB64}.{payloadB64}"; var sig = ec.SignData(Encoding.ASCII.GetBytes(signingInput), HashAlgorithmName.SHA256); var sigB64 = Base64UrlEncoder.Encode(sig); return $"{signingInput}.{sigB64}"; } private static string ComputeJkt(ECDsa ec) { var pubParams = ec.ExportParameters(includePrivateParameters: false); // RFC 7638: SHA-256 of canonical JSON of the JWK with members in lex-order: crv,kty,x,y. var x = Base64UrlEncoder.Encode(pubParams.Q.X!); var y = Base64UrlEncoder.Encode(pubParams.Q.Y!); var canonical = $"{{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"{x}\",\"y\":\"{y}\"}}"; var hash = SHA256.HashData(Encoding.UTF8.GetBytes(canonical)); return Base64UrlEncoder.Encode(hash); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/DpopJktBindingFullCycleTests.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/DpopJktBindingFullCycleTests.cs ---- using System.Net; using System.Security.Cryptography; using System.Text; 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; /// /// Z4 P2.1 E2E: end-to-end full-cycle test for the dpop_jkt binding at the /// authorization endpoint (RFC 9449 §10). /// /// Pipeline: /// /login → GET /connect/authorize?dpop_jkt=… → callback (code) → POST /connect/token (with DPoP proof) /// /// Scenarios: /// 1. Match: same EC key used for both dpop_jkt and the proof at /token → access_token issued (token_type=DPoP). /// 2. Mismatch: /token DPoP proof comes from a different key → invalid_grant. /// 3. Missing proof: code bound to dpop_jkt but no DPoP header at /token → invalid_grant. /// [Collection("ProductionHttp")] public class DpopJktBindingFullCycleTests { private readonly ProductionHttpFixture _fx; public DpopJktBindingFullCycleTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Authorize_With_DpopJkt_Then_Token_With_Matching_Proof_Succeeds() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); var jkt = ComputeJkt(ec); var (code, verifier) = await ObtainAuthCodeWithDpopJktAsync(jkt); var url = $"{_fx.BaseUrl.TrimEnd('/')}/connect/token"; var proof = BuildDpopProof(ec, "POST", url); using var req = BuildTokenRequest(code, verifier); req.Headers.Add("DPoP", proof); var resp = await _fx.Http.SendAsync(req); var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.OK, "code bound to dpop_jkt must redeem when proof matches: {0}", body); var json = JsonDocument.Parse(body).RootElement; json.GetProperty("token_type").GetString().Should().Be("DPoP"); var at = json.GetProperty("access_token").GetString()!; var jwt = new JsonWebTokenHandler().ReadJsonWebToken(at); jwt.TryGetPayloadValue("cnf", out var cnf).Should().BeTrue(); cnf.GetProperty("jkt").GetString().Should().Be(jkt); } [Fact] public async Task Authorize_With_DpopJkt_Then_Token_With_Mismatched_Proof_Returns_InvalidGrant() { using var ecAuthorize = ECDsa.Create(ECCurve.NamedCurves.nistP256); using var ecToken = ECDsa.Create(ECCurve.NamedCurves.nistP256); // different key var jkt = ComputeJkt(ecAuthorize); var (code, verifier) = await ObtainAuthCodeWithDpopJktAsync(jkt); var url = $"{_fx.BaseUrl.TrimEnd('/')}/connect/token"; var proof = BuildDpopProof(ecToken, "POST", url); using var req = BuildTokenRequest(code, verifier); req.Headers.Add("DPoP", proof); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().BeGreaterThanOrEqualTo(400, "RFC 9449 §10.1: token must be refused when proof's jkt differs from the bound dpop_jkt"); var body = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; body.GetProperty("error").GetString().Should().Be("invalid_grant"); } [Fact] public async Task Authorize_With_DpopJkt_Then_Token_Without_Proof_Returns_InvalidGrant() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); var jkt = ComputeJkt(ec); var (code, verifier) = await ObtainAuthCodeWithDpopJktAsync(jkt); using var req = BuildTokenRequest(code, verifier); // no DPoP header var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().BeGreaterThanOrEqualTo(400); var body = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; body.GetProperty("error").GetString().Should().Be("invalid_grant"); } [Fact] public async Task Authorize_With_Malformed_DpopJkt_Returns_InvalidRequest() { var cookies = new CookieContainer(); using var browser = BuildBrowser(cookies); await LoginAsync(browser); var (verifier, challenge) = GeneratePkce(); var malformedJkt = "not-a-real-jkt!!"; // fails IsWellFormedJkt var url = BuildAuthorizeUrl(verifier: null, challenge, dpopJkt: malformedJkt, state: "x"); _ = verifier; var resp = await browser.GetAsync(url); // Authorize handler returns invalid_request either as a redirect or as a 400 page. if (resp.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found) { var loc = resp.Headers.Location?.ToString() ?? ""; loc.Should().Contain("error=invalid_request", "malformed dpop_jkt must produce invalid_request"); } else { ((int)resp.StatusCode).Should().BeGreaterThanOrEqualTo(400); } } // ─── Pipeline helpers ─── private async Task<(string code, string verifier)> ObtainAuthCodeWithDpopJktAsync(string jkt) { var cookies = new CookieContainer(); using var browser = BuildBrowser(cookies); await LoginAsync(browser); var (verifier, challenge) = GeneratePkce(); var url = BuildAuthorizeUrl(null, challenge, dpopJkt: jkt, state: "dpopjkt-state"); var resp = await browser.GetAsync(url); // Authorize may either redirect to redirect_uri (302/Found) or, in this server's // configuration, return 200 OK with a JSON body containing the code (PAR-style). string? code; if (resp.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found) { var location = resp.Headers.Location?.ToString(); location.Should().NotBeNullOrEmpty(); location!.Should().StartWith(ProductionHttpFixture.TestRedirectUri); code = ExtractQueryParam(location, "code"); } else { resp.StatusCode.Should().Be(HttpStatusCode.OK, "authorize must produce a code: {0}", await resp.Content.ReadAsStringAsync()); var body = await resp.Content.ReadAsStringAsync(); var json = JsonDocument.Parse(body).RootElement; json.TryGetProperty("code", out var c).Should().BeTrue("authorize JSON body must contain code"); code = c.GetString(); } code.Should().NotBeNullOrEmpty("authorize must produce a code"); return (code!, verifier); } private HttpClient BuildBrowser(CookieContainer cookies) { var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true }; return new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; } private static async Task LoginAsync(HttpClient browser) { var loginForm = new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword }); await browser.PostAsync("/login", loginForm); } private static string BuildAuthorizeUrl(string? verifier, string challenge, string dpopJkt, string state) { _ = verifier; return $"/connect/authorize?response_type=code" + $"&client_id={Uri.EscapeDataString(ProductionHttpFixture.TestPublicClientId)}" + $"&redirect_uri={Uri.EscapeDataString(ProductionHttpFixture.TestRedirectUri)}" + $"&scope=openid" + $"&code_challenge={challenge}&code_challenge_method=S256" + $"&state={state}" + $"&dpop_jkt={Uri.EscapeDataString(dpopJkt)}"; } private static HttpRequestMessage BuildTokenRequest(string code, string verifier) => new(HttpMethod.Post, "/connect/token") { Content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["code_verifier"] = verifier }) }; private static string? ExtractQueryParam(string url, string param) { var idx = url.IndexOf('?'); if (idx < 0) return null; var query = url[(idx + 1)..]; var hashIdx = query.IndexOf('#'); if (hashIdx >= 0) query = query[..hashIdx]; foreach (var pair in query.Split('&')) { var kv = pair.Split('=', 2); if (kv.Length == 2 && kv[0] == param) return Uri.UnescapeDataString(kv[1]); } return null; } private static (string verifier, string challenge) GeneratePkce() { var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); var verifier = Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = SHA256.HashData(Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash).TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } // ─── DPoP helpers (same as DpopFullCycleTests) ─── private static string BuildDpopProof(ECDsa ec, string method, string url) { var p = ec.ExportParameters(false); var x = Base64UrlEncoder.Encode(p.Q.X!); var y = Base64UrlEncoder.Encode(p.Q.Y!); var jwk = $"{{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"{x}\",\"y\":\"{y}\"}}"; var header = $"{{\"typ\":\"dpop+jwt\",\"alg\":\"ES256\",\"jwk\":{jwk}}}"; var iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var jti = Guid.NewGuid().ToString("N"); var payload = $"{{\"htm\":\"{method}\",\"htu\":\"{url}\",\"iat\":{iat},\"jti\":\"{jti}\"}}"; var hB64 = Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(header)); var pB64 = Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(payload)); var input = $"{hB64}.{pB64}"; var sig = ec.SignData(Encoding.ASCII.GetBytes(input), HashAlgorithmName.SHA256); return $"{input}.{Base64UrlEncoder.Encode(sig)}"; } private static string ComputeJkt(ECDsa ec) { var p = ec.ExportParameters(false); var x = Base64UrlEncoder.Encode(p.Q.X!); var y = Base64UrlEncoder.Encode(p.Q.Y!); var canonical = $"{{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"{x}\",\"y\":\"{y}\"}}"; return Base64UrlEncoder.Encode(SHA256.HashData(Encoding.UTF8.GetBytes(canonical))); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/DpopNonceHeaderTests.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/DpopNonceHeaderTests.cs ---- using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.Json; using AwesomeAssertions; using Microsoft.IdentityModel.Tokens; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Z4 P2.2 E2E: validates RFC 9449 §8 DPoP-Nonce response-header emission. /// On a successful DPoP-bearing token request the AS rotates the nonce via the /// DPoP-Nonce response header so clients can adopt it for subsequent proofs. /// [Collection("ProductionHttp")] public class DpopNonceHeaderTests { private readonly ProductionHttpFixture _fx; public DpopNonceHeaderTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Token_Endpoint_Emits_DPoP_Nonce_On_Successful_Exchange() { using var ec = ECDsa.Create(ECCurve.NamedCurves.nistP256); var (code, verifier) = await ObtainAuthCodeAsync(); var url = $"{_fx.BaseUrl.TrimEnd('/')}/connect/token"; var proof = BuildDpopProof(ec, "POST", url); using var req = new HttpRequestMessage(HttpMethod.Post, "/connect/token") { Content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["code_verifier"] = verifier }) }; req.Headers.Add("DPoP", proof); var resp = await _fx.Http.SendAsync(req); var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.OK, "DPoP exchange must succeed: {0}", body); var json = JsonDocument.Parse(body).RootElement; json.GetProperty("token_type").GetString().Should().Be("DPoP"); var hasHeader = resp.Headers.TryGetValues("DPoP-Nonce", out var values) || (resp.Content?.Headers?.TryGetValues("DPoP-Nonce", out values) ?? false); var allHeaders = string.Join("; ", resp.Headers.Select(h => $"{h.Key}=[{string.Join(",", h.Value)}]")); hasHeader.Should().BeTrue( "RFC 9449 §8: AS must rotate DPoP-Nonce on every DPoP-bearing response. Headers: {0}", allHeaders); var nonce = values!.First(); nonce.Should().NotBeNullOrWhiteSpace(); nonce.Length.Should().BeGreaterThan(40, "56 raw bytes ≈ 75 base64url chars"); } private async Task<(string code, string verifier)> ObtainAuthCodeAsync() { var cookies = new CookieContainer(); var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true }; using var browser = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; await browser.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword })); var verifier = Base64UrlEncoder.Encode(RandomNumberGenerator.GetBytes(32)); var challenge = Base64UrlEncoder.Encode( SHA256.HashData(Encoding.ASCII.GetBytes(verifier))); var url = $"/connect/authorize?response_type=code" + $"&client_id={Uri.EscapeDataString(ProductionHttpFixture.TestPublicClientId)}" + $"&redirect_uri={Uri.EscapeDataString(ProductionHttpFixture.TestRedirectUri)}" + $"&scope=openid&code_challenge={challenge}&code_challenge_method=S256&state=nonce-test"; var resp = await browser.GetAsync(url); string? code; if (resp.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found) { var loc = resp.Headers.Location?.ToString() ?? ""; var idx = loc.IndexOf("code=", StringComparison.Ordinal); code = idx >= 0 ? Uri.UnescapeDataString(loc[(idx + 5)..].Split('&')[0]) : null; } else { var bod = await resp.Content.ReadAsStringAsync(); var doc = JsonDocument.Parse(bod).RootElement; code = doc.GetProperty("code").GetString(); } code.Should().NotBeNullOrEmpty("authorize must produce a code"); return (code!, verifier); } private static string BuildDpopProof(ECDsa ec, string method, string url) { var p = ec.ExportParameters(false); var x = Base64UrlEncoder.Encode(p.Q.X!); var y = Base64UrlEncoder.Encode(p.Q.Y!); var jwk = $"{{\"crv\":\"P-256\",\"kty\":\"EC\",\"x\":\"{x}\",\"y\":\"{y}\"}}"; var header = $"{{\"typ\":\"dpop+jwt\",\"alg\":\"ES256\",\"jwk\":{jwk}}}"; var iat = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var jti = Guid.NewGuid().ToString("N"); var payload = $"{{\"htm\":\"{method}\",\"htu\":\"{url}\",\"iat\":{iat},\"jti\":\"{jti}\"}}"; var hB64 = Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(header)); var pB64 = Base64UrlEncoder.Encode(Encoding.UTF8.GetBytes(payload)); var input = $"{hB64}.{pB64}"; var sig = ec.SignData(Encoding.ASCII.GetBytes(input), HashAlgorithmName.SHA256); return $"{input}.{Base64UrlEncoder.Encode(sig)}"; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/DynamicRegistrationFullCycleTests.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/DynamicRegistrationFullCycleTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Z1 + Z2 (RFC 7591 §3.2.1 + RFC 7592): Full-stack end-to-end cycle for Dynamic Client Registration. /// /// POST /connect/register → client is created; response carries /// registration_access_token + registration_client_uri. /// GET {registration_client_uri} with the returned RAT → 200 + full metadata, /// NEVER the client_secret. /// GET with a wrong RAT → 401 invalid_token. /// PUT {registration_client_uri} → 200 with mutated fields; subsequent GET reflects them. /// DELETE {registration_client_uri} → 204; subsequent GET → 401 (client gone). /// /// [Collection("ProductionHttp")] public class DynamicRegistrationFullCycleTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public DynamicRegistrationFullCycleTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } [Fact] public async Task Register_Read_Update_Delete_FullCycle() { // ── 1) REGISTER ── var regBody = new { redirect_uris = new[] { "https://initial.example.com/cb" }, client_name = "Z1Z2 Cycle Test", token_endpoint_auth_method = "client_secret_basic" }; var regReq = new HttpRequestMessage(HttpMethod.Post, "/connect/register") { Content = JsonContent.Create(regBody) }; regReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ProductionHttpFixture.DynamicRegAccessToken); var regResp = await _http.SendAsync(regReq); regResp.StatusCode.Should().Be(HttpStatusCode.Created, "register failed: {0}", await regResp.Content.ReadAsStringAsync()); var regJson = await ParseJson(regResp); var clientId = regJson.GetProperty("client_id").GetString()!; var rat = regJson.GetProperty("registration_access_token").GetString()!; var uri = regJson.GetProperty("registration_client_uri").GetString()!; clientId.Should().NotBeNullOrWhiteSpace(); rat.Should().NotBeNullOrWhiteSpace("RFC 7591 §3.2.1 — registration_access_token MUST be issued"); uri.Should().StartWith($"http://localhost:{_fx.Port}/connect/register/"); // Relative path for requests against the fixture's HttpClient. var mgmtPath = $"/connect/register/{Uri.EscapeDataString(clientId)}"; // ── 2) READ with correct RAT ── var getResp = await SendAuthed(HttpMethod.Get, mgmtPath, rat); var getBody = await getResp.Content.ReadAsStringAsync(); getResp.StatusCode.Should().Be(HttpStatusCode.OK, "GET with valid RAT must succeed: [{0}] body='{1}' path={2}", getResp.StatusCode, getBody, mgmtPath); // Diagnostic — if body is non-JSON, fail with actual value. getBody.TrimStart().Should().StartWith("{", "expected JSON response, got: '{0}'", getBody); var getJson = JsonDocument.Parse(getBody).RootElement; getJson.GetProperty("client_id").GetString().Should().Be(clientId); getJson.TryGetProperty("client_secret", out _).Should().BeFalse( "RFC 7592 §2.3 — client_secret MUST NOT be returned on management GET"); getJson.TryGetProperty("registration_access_token", out _).Should().BeFalse( "RAT is one-shot at creation; management reads never echo it"); getJson.GetProperty("redirect_uris").EnumerateArray().Select(e => e.GetString()) .Should().Contain("https://initial.example.com/cb"); // ── 3) READ with wrong RAT → 401 ── var badResp = await SendAuthed(HttpMethod.Get, mgmtPath, "wrong-token-value"); badResp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); var badJson = await ParseJson(badResp); badJson.GetProperty("error").GetString().Should().Be("invalid_token"); // ── 4) UPDATE ── var putReq = new HttpRequestMessage(HttpMethod.Put, mgmtPath) { Content = JsonContent.Create(new { redirect_uris = new[] { "https://updated.example.com/cb" }, client_name = "Z1Z2 Renamed" }) }; putReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", rat); var putResp = await _http.SendAsync(putReq); putResp.StatusCode.Should().Be(HttpStatusCode.OK, "PUT with valid RAT must succeed: {0}", await putResp.Content.ReadAsStringAsync()); // Verify via read — mutations persisted. var verifyResp = await SendAuthed(HttpMethod.Get, mgmtPath, rat); verifyResp.StatusCode.Should().Be(HttpStatusCode.OK); var verifyJson = await ParseJson(verifyResp); verifyJson.GetProperty("client_name").GetString().Should().Be("Z1Z2 Renamed"); verifyJson.GetProperty("redirect_uris").EnumerateArray().Select(e => e.GetString()) .Should().BeEquivalentTo(new[] { "https://updated.example.com/cb" }); // ── 5) DELETE ── var delResp = await SendAuthed(HttpMethod.Delete, mgmtPath, rat); delResp.StatusCode.Should().Be(HttpStatusCode.NoContent); // ── 6) Subsequent read → 401 (client not found, but surfaced as invalid_token per RFC 7592) ── var afterDel = await SendAuthed(HttpMethod.Get, mgmtPath, rat); afterDel.StatusCode.Should().BeOneOf(HttpStatusCode.Unauthorized, HttpStatusCode.NotFound); } private async Task SendAuthed(HttpMethod method, string path, string bearer) { var req = new HttpRequestMessage(method, path); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer); return await _http.SendAsync(req); } private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/EmailMfaEnrollmentTests.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/EmailMfaEnrollmentTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Options; using redb.Identity.Client; using redb.Core; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// E-mail MFA enrollment end to end over real HTTP: setup sends the one-time code to the candidate address (caught /// by the fixture's in-memory e-mail channel) and answers with mfa_state and setup_token; confirm takes /// the code with both. Admin endpoints, the identity client, and the self-service /me/mfa path; a wrong /// code, and a code sent for another setup, are refused. /// [Collection("ProductionHttp")] public class EmailMfaEnrollmentTests { private const string Admin = "/api/v1/identity/mfa"; private const string Me = "/api/v1/identity/me/mfa"; private readonly ProductionHttpFixture _fx; public EmailMfaEnrollmentTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task An_admin_enrolls_a_user_with_the_code_sent_to_the_new_address() { var (userId, login) = await CreateUserAsync(); var address = $"{login}@example.test"; var setup = await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/setup", new { userId, username = login, destination = address }, HttpStatusCode.OK); setup.GetProperty("method").GetString().Should().Be("email"); setup.GetProperty("masked_email").GetString().Should().Be($"{login[0]}***@example.test"); var mfaState = setup.GetProperty("mfa_state").GetString()!; var setupToken = setup.GetProperty("setup_token").GetString()!; var mail = _fx.Emails.ForRecipient(address).Should().ContainSingle().Subject; mail.TemplateId.Should().Be(IdentityEmailTemplates.MfaCode); var code = mail.Vars["code"]; mail.TextBody.Should().Contain(code); var confirmed = await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/confirm", new { userId, code, mfaState, setupToken }, HttpStatusCode.OK); confirmed.GetProperty("confirmed").GetBoolean().Should().BeTrue(); confirmed.GetProperty("recovery_codes").GetArrayLength().Should().Be(10); var status = await Send(_fx.ManagementToken, HttpMethod.Get, $"{Admin}/status/{userId}", null, HttpStatusCode.OK); status.GetProperty("methods").EnumerateArray().Select(m => m.GetString()).Should().Contain("email"); } [Fact] public async Task The_identity_client_runs_the_same_enrollment() { var (userId, login) = await CreateUserAsync(); var address = $"{login}@example.test"; var client = Client(); var setup = await client.SetupUserEmailAsync(userId, login, address); var code = _fx.Emails.ForRecipient(address).Single().Vars["code"]; var confirmed = await client.ConfirmUserEmailAsync(userId, code, setup.GetProperty("mfa_state").GetString()!, setup.GetProperty("setup_token").GetString()!); confirmed.GetProperty("confirmed").GetBoolean().Should().BeTrue(confirmed.ToString()); (await client.GetUserMfaStatusAsync(userId)).GetProperty("methods").EnumerateArray() .Select(m => m.GetString()).Should().Contain("email"); } [Fact] public async Task A_wrong_code_and_a_code_sent_for_another_setup_are_refused() { var (userId, login) = await CreateUserAsync(); var first = $"{login}-a@example.test"; var second = $"{login}-b@example.test"; var setupA = await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/setup", new { userId, username = login, destination = first }, HttpStatusCode.OK); await ClearOtpCooldownAsync(userId); var setupB = await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/setup", new { userId, username = login, destination = second }, HttpStatusCode.OK); var codeA = _fx.Emails.ForRecipient(first).Single().Vars["code"]; var codeB = _fx.Emails.ForRecipient(second).Single().Vars["code"]; // A wrong code for the right setup. var wrong = codeB == "000000" ? "111111" : "000000"; (await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/confirm", new { userId, code = wrong, mfaState = setupB.GetProperty("mfa_state").GetString(), setupToken = setupB.GetProperty("setup_token").GetString(), }, HttpStatusCode.BadRequest)).GetProperty("error").GetString().Should().Be("invalid_code"); // The right code and state of setup A, presented with the setup token of B: the code was not sent for B. (await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/confirm", new { userId, code = codeA, mfaState = setupA.GetProperty("mfa_state").GetString(), setupToken = setupB.GetProperty("setup_token").GetString(), }, HttpStatusCode.BadRequest)).GetProperty("error").GetString().Should().Be("invalid_code"); // Setup B with its own code still goes through. (await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/confirm", new { userId, code = codeB, mfaState = setupB.GetProperty("mfa_state").GetString(), setupToken = setupB.GetProperty("setup_token").GetString(), }, HttpStatusCode.OK)).GetProperty("confirmed").GetBoolean().Should().BeTrue(); } [Fact] public async Task A_second_code_inside_the_cooldown_is_refused_and_nothing_is_sent() { var (userId, login) = await CreateUserAsync(); await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/setup", new { userId, username = login, destination = $"{login}-1@example.test" }, HttpStatusCode.OK); var limited = await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/setup", new { userId, username = login, destination = $"{login}-2@example.test" }, HttpStatusCode.TooManyRequests); limited.GetProperty("error").GetString().Should().Be("rate_limited"); limited.TryGetProperty("setup_token", out _).Should().BeFalse(); _fx.Emails.ForRecipient($"{login}-2@example.test").Should().BeEmpty(); } [Fact] public async Task A_confirm_without_the_setup_token_is_refused_by_validation() { var (userId, _) = await CreateUserAsync(); await Send(_fx.ManagementToken, HttpMethod.Post, $"{Admin}/email/confirm", new { userId, code = "123456", mfaState = "x" }, HttpStatusCode.BadRequest); } [Fact] public async Task A_user_enrolls_their_own_address_through_me_mfa() { var (token, login) = await UserTokenAsync(); var address = $"{login}@example.test"; var setup = await Send(token, HttpMethod.Post, $"{Me}/setup", new { method = "email", destination = address }, HttpStatusCode.OK); var code = _fx.Emails.ForRecipient(address).Single().Vars["code"]; var confirmed = await Send(token, HttpMethod.Post, $"{Me}/confirm", new { method = "email", code, mfa_state = setup.GetProperty("mfa_state").GetString(), setup_token = setup.GetProperty("setup_token").GetString(), }, HttpStatusCode.OK); confirmed.GetProperty("confirmed").GetBoolean().Should().BeTrue(); (await Send(token, HttpMethod.Get, Me, null, HttpStatusCode.OK)).GetProperty("methods").EnumerateArray() .Select(m => m.GetString()).Should().Contain("email"); } /// Lets the next code go out at once: the setup of another address within the cooldown is refused (see above). private Task ClearOtpCooldownAsync(long userId) => _fx.UseRedbAsync(async redb => { var record = await redb.Query().WhereRedb(o => o.Key == userId).FirstOrDefaultAsync(); record!.Props.LastOtpSentAt = null; await redb.SaveAsync(record); }); private IdentityClient Client() { var http = new HttpClient { BaseAddress = _fx.Http.BaseAddress }; http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return new IdentityClient(http, Options.Create(new IdentityClientOptions { BaseUrl = _fx.Http.BaseAddress! })); } private async Task<(long UserId, string Login)> CreateUserAsync() { var login = "emfa" + Guid.NewGuid().ToString("N")[..10]; var created = await Send(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/users", new { login, password = "Str0ng!Passw0rd", displayName = login }, HttpStatusCode.OK); return (created.GetProperty("id").GetInt64(), login); } private async Task<(string Token, string Login)> UserTokenAsync() { var (_, login) = await CreateUserAsync(); var clientId = login + "-client"; const string clientSecret = "emfa-client-secret-1234"; await Send(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/applications", new { clientId, clientSecret, displayName = clientId, permissions = new[] { "ept:token", "gt:password", "scp:openid", "scp:identity:account" }, }, HttpStatusCode.OK); var response = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = login, ["password"] = "Str0ng!Passw0rd", ["scope"] = "openid identity:account", ["client_id"] = clientId, ["client_secret"] = clientSecret, })); var body = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(HttpStatusCode.OK, body); return (JsonDocument.Parse(body).RootElement.GetProperty("access_token").GetString()!, login); } private async Task Send(string token, HttpMethod method, string path, object? body, HttpStatusCode expected) { using var request = new HttpRequestMessage(method, path) { Content = body is null ? null : JsonContent.Create(body) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); using var response = await _fx.Http.SendAsync(request); var text = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(expected, $"{method} {path}: {text}"); return text.Length == 0 ? default : JsonDocument.Parse(text).RootElement.Clone(); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FederationProviderBlankSecretTests.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/FederationProviderBlankSecretTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// One rule for a federation provider's client secret on create and update, over the HTTP management API: the empty /// string means no secret, a value of white space only is refused with 400 and leaves the stored secret as it was. /// [Collection("ProductionHttp")] public class FederationProviderBlankSecretTests { private const string Path = "/api/v1/identity/federation-providers"; private readonly ProductionHttpFixture _fx; public FederationProviderBlankSecretTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Empty_secret_on_create_is_no_secret() { var (status, body) = await Send(HttpMethod.Post, Path, Provider(string.Empty)); ((int)status).Should().BeInRange(200, 299, body); Json(body).GetProperty("hasSecret").GetBoolean().Should().BeFalse(body); } [Theory] [InlineData(" ")] [InlineData(" \t ")] public async Task White_space_secret_on_create_is_refused(string secret) { var (status, body) = await Send(HttpMethod.Post, Path, Provider(secret)); status.Should().Be(HttpStatusCode.BadRequest, body); body.Should().Contain("validation_error"); } [Fact] public async Task White_space_secret_on_update_is_refused_and_keeps_the_stored_secret() { var (created, createdBody) = await Send(HttpMethod.Post, Path, Provider("kept-secret")); ((int)created).Should().BeInRange(200, 299, createdBody); var id = Json(createdBody).GetProperty("id").GetString(); var (status, body) = await Send(HttpMethod.Put, $"{Path}/{id}", new { clientSecret = " " }); status.Should().Be(HttpStatusCode.BadRequest, body); body.Should().Contain("validation_error"); var (_, read) = await Send(HttpMethod.Get, $"{Path}/{id}", null); Json(read).GetProperty("hasSecret").GetBoolean().Should().BeTrue(read); } [Fact] public async Task Empty_secret_on_update_clears_it() { var (_, createdBody) = await Send(HttpMethod.Post, Path, Provider("to-clear")); var id = Json(createdBody).GetProperty("id").GetString(); var (status, body) = await Send(HttpMethod.Put, $"{Path}/{id}", new { clientSecret = string.Empty }); ((int)status).Should().BeInRange(200, 299, body); Json(body).GetProperty("hasSecret").GetBoolean().Should().BeFalse(body); } private static object Provider(string secret) => new { providerId = "blank-" + Guid.NewGuid().ToString("N")[..12], kind = "oidc", displayName = "Blank secret", authority = "https://idp.example.test/", clientId = "blank-client", clientSecret = secret, enabled = false, }; private async Task<(HttpStatusCode Status, string Body)> Send(HttpMethod method, string path, object? body) { using var request = new HttpRequestMessage(method, path); if (body is not null) request.Content = JsonContent.Create(body); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); using var response = await _fx.Http.SendAsync(request); return (response.StatusCode, await response.Content.ReadAsStringAsync()); } private static JsonElement Json(string body) => JsonDocument.Parse(body).RootElement; } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackAccessTokenAudienceTests.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/FullStackAccessTokenAudienceTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.JsonWebTokens; using OpenIddict.Abstractions; using OpenIddict.Validation; using redb.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// RFC 9068 (JWT Profile for OAuth 2.0 Access Tokens) audience conformance, end to end. /// /// §2.2 makes aud REQUIRED in every access token; §3 obliges the authorization /// server to fall back to a default resource indicator when the request names none; §4 /// obliges the resource server to reject a token whose aud does not include it. /// Before this suite the scope store served ScopeProps.Resources but no sign-in /// handler ever attached them to the principal, so issued access tokens carried no /// aud at all and the local validation stack never checked one. /// /// /// Audience composition under test: Resources of the granted scopes ∪ the application's /// AccessTokenAudiences; the OP's own audience ({issuer}/resources) joins /// whenever an identity:* scope is granted, and stands alone when nothing else is /// configured. The management API accepts only tokens carrying the OP's own audience. /// /// [Collection("ProductionHttp")] public class FullStackAccessTokenAudienceTests { private readonly ProductionHttpFixture _fx; public FullStackAccessTokenAudienceTests(ProductionHttpFixture fx) => _fx = fx; private string OwnAudience => RedbIdentityOptions.ResolveDefaultAccessTokenAudience( new Uri($"{_fx.BaseUrl}/"), configured: null); [Fact] public void DefaultAudience_IsIssuerSlashResources_UnlessConfigured() { var issuer = new Uri("https://op.example.com/tenant/"); RedbIdentityOptions.ResolveDefaultAccessTokenAudience(issuer, configured: null) .Should().Be("https://op.example.com/tenant/resources", "the {issuer}/resources pattern (Duende/Okta style) is the built-in default"); RedbIdentityOptions.ResolveDefaultAccessTokenAudience(new Uri("https://op.example.com"), configured: null) .Should().Be("https://op.example.com/resources", "no double slash for a root issuer"); RedbIdentityOptions.ResolveDefaultAccessTokenAudience(issuer, configured: " api://my-default ") .Should().Be("api://my-default", "an operator-configured value wins, trimmed"); } [Fact] public async Task AccessToken_WithoutAnyResource_CarriesTheDefaultAudience() { var token = await IssuePasswordToken( ProductionHttpFixture.TestClientId, ProductionHttpFixture.TestClientSecret, "openid profile"); ReadAudiences(token).Should().BeEquivalentTo(new[] { OwnAudience, ProductionHttpFixture.TestClientId }, "RFC 9068 §3: a request naming no resource gets the AS default resource indicator; " + "the issuing client is an audience too so it can introspect its own token"); } [Fact] public async Task AccessToken_ForExternalApiScope_CarriesOnlyThatResource() { var n = Guid.NewGuid().ToString("N")[..8]; var resource = $"https://api-{n}.example"; await SeedScopeAsync($"e2e-aud-{n}", resource); var (clientId, secret) = await SeedClientAsync($"e2e-aud-ext-{n}", $"e2e-aud-{n}"); var token = await IssueClientCredentialsToken(clientId, secret, $"e2e-aud-{n}"); ReadAudiences(token).Should().BeEquivalentTo(new[] { resource, clientId }, "a token minted for an external API is for that API (and its own client) — the OP's own audience must not leak in"); ReadAudiences(token).Should().NotContain(OwnAudience); } [Fact] public async Task AccessToken_ForExternalApiPlusIdentityScope_CarriesBoth() { var n = Guid.NewGuid().ToString("N")[..8]; var resource = $"https://api-{n}.example"; await SeedScopeAsync($"e2e-aud-{n}", resource); var (clientId, secret) = await SeedClientAsync($"e2e-aud-mix-{n}", $"e2e-aud-{n}", "identity:manage"); var token = await IssueClientCredentialsToken(clientId, secret, $"e2e-aud-{n} identity:manage"); ReadAudiences(token).Should().BeEquivalentTo(new[] { resource, OwnAudience, clientId }, "identity:* scopes are the OP's own API, so its audience rides along with the external one"); } [Fact] public async Task AccessToken_UsesApplicationAccessTokenAudiences() { var n = Guid.NewGuid().ToString("N")[..8]; var extra = $"https://extra-{n}.example"; await SeedScopeAsync($"e2e-aud-plain-{n}", resource: null); var (clientId, secret) = await SeedClientAsync($"e2e-aud-app-{n}", $"e2e-aud-plain-{n}"); await _fx.UseRedbAsync(async redb => { var app = await redb.GetByUniqueAsync(p => p.ClientId, clientId); app!.Props.AccessTokenAudiences = [extra]; await redb.SaveAsync(app); }); var token = await IssueClientCredentialsToken(clientId, secret, $"e2e-aud-plain-{n}"); ReadAudiences(token).Should().BeEquivalentTo(new[] { extra, clientId }, "per-application audiences are a configured resource indicator, so the default steps aside"); } [Fact] public void LocalValidation_RequiresTheOwnAudience() { var options = _fx.ServiceProvider .GetRequiredService>().CurrentValue; options.Audiences.Should().Contain(OwnAudience, "RFC 9068 §4: the OP's own resource side must verify aud, not just signature/issuer/expiry"); } [Fact] public async Task ManagementApi_RejectsTokenMintedForAnotherResource_With401() { var n = Guid.NewGuid().ToString("N")[..8]; await SeedScopeAsync($"e2e-aud-{n}", $"https://api-{n}.example"); var (clientId, secret) = await SeedClientAsync($"e2e-aud-rs-{n}", $"e2e-aud-{n}"); var foreignToken = await IssueClientCredentialsToken(clientId, secret, $"e2e-aud-{n}"); var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", foreignToken); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, "a token whose aud names only another API is invalid here (401), not merely under-scoped (403)"); } [Fact] public async Task ManagementApi_StillAcceptsItsOwnManagementToken() { var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); var resp = await _fx.Http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, "the identity:manage token carries the OP's own audience and must keep working"); } // ───────────────────────────────────────────────────────────────────────── // helpers // ───────────────────────────────────────────────────────────────────────── private static string[] ReadAudiences(string accessToken) { var jwt = new JsonWebTokenHandler().ReadJsonWebToken(accessToken); return jwt.Audiences.ToArray(); } private async Task SeedScopeAsync(string scopeName, string? resource) { var manager = _fx.ServiceProvider.GetRequiredService(); var descriptor = new OpenIddictScopeDescriptor { Name = scopeName, DisplayName = scopeName }; if (resource is not null) descriptor.Resources.Add(resource); await manager.CreateAsync(descriptor); } private async Task<(string ClientId, string Secret)> SeedClientAsync(string clientId, params string[] scopes) { var secret = $"secret-{Guid.NewGuid():N}"; var descriptor = new OpenIddictApplicationDescriptor { ClientId = clientId, ClientSecret = secret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = clientId, Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, } }; foreach (var scope in scopes) descriptor.Permissions.Add(OpenIddictConstants.Permissions.Prefixes.Scope + scope); var manager = _fx.ServiceProvider.GetRequiredService(); await manager.CreateAsync(descriptor); return (clientId, secret); } private Task IssuePasswordToken(string clientId, string secret, string scope) => IssueToken(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["client_id"] = clientId, ["client_secret"] = secret, ["scope"] = scope, }); private Task IssueClientCredentialsToken(string clientId, string secret, string scope) => IssueToken(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = clientId, ["client_secret"] = secret, ["scope"] = scope, }); private async Task IssueToken(Dictionary form) { var resp = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(form)); var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.OK, "token issuance must succeed: {0}", body); return JsonDocument.Parse(body).RootElement.GetProperty("access_token").GetString()!; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackAccountRegistrationTests.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/FullStackAccountRegistrationTests.cs ---- using System; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; using System.Threading.Tasks; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using redb.Identity.Contracts.Users; using redb.Identity.Core.Configuration; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// N-3 (sub-step N3-7): full-stack E2E tests for the anonymous self-service /// account-registration flow. Path: HTTP \u2192 Kestrel \u2192 AccountRegistrationController /// (no auth) \u2192 direct-vm \u2192 AccountRegisterProcessor \u2192 IUserProvider + redb /// stores. Asserts the happy-path user creation + ROPC sign-in, the duplicate-login /// 409 contract, the weak-password 400 rejection, and the feature-gate 403 when /// is flipped off. /// [Collection("ProductionHttp")] public class FullStackAccountRegistrationTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; private const string ClientId = ProductionHttpFixture.TestClientId; private const string ClientSecret = ProductionHttpFixture.TestClientSecret; public FullStackAccountRegistrationTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } private static string UniqueLogin(string tag) => $"reg-{tag}-{Guid.NewGuid():N}".Substring(0, 24); private static string UniqueEmail(string tag) => $"reg-{tag}-{Guid.NewGuid():N}@example.invalid"; private async Task PostRegisterAsync(object body) => await _http.PostAsJsonAsync("/api/v1/identity/account/register", body); private async Task TryPasswordGrantAsync(string username, string password) { var content = new FormUrlEncodedContent(new System.Collections.Generic.Dictionary { ["grant_type"] = "password", ["username"] = username, ["password"] = password, ["client_id"] = ClientId, ["client_secret"] = ClientSecret, ["scope"] = "openid" }); return await _http.PostAsync("/connect/token", content); } // \u2550\u2550 Happy path \u2550\u2550 [Fact] public async Task Register_HappyPath_CreatesUser_AndPasswordGrantSucceeds() { var login = UniqueLogin("ok"); var email = UniqueEmail("ok"); var password = $"E2E@Reg-{Guid.NewGuid():N}!"; var resp = await PostRegisterAsync(new { login, email, password, displayName = "E2E Self Sign-Up", }); resp.StatusCode.Should().Be(HttpStatusCode.OK, "happy-path register must succeed: {0}", await resp.Content.ReadAsStringAsync()); var body = await resp.Content.ReadFromJsonAsync(); body.GetProperty("success").GetBoolean().Should().BeTrue(); body.GetProperty("login").GetString().Should().Be(login); body.GetProperty("userId").GetInt64().Should().BeGreaterThan(0); // The new credentials must be immediately usable via the ROPC token endpoint. using var grant = await TryPasswordGrantAsync(login, password); grant.StatusCode.Should().Be(HttpStatusCode.OK, "newly registered user must be able to sign in via password grant: {0}", await grant.Content.ReadAsStringAsync()); } // \u2550\u2550 Duplicate login / e-mail \u2550\u2550 [Fact] public async Task Register_DuplicateLogin_Returns409() { var login = UniqueLogin("dup"); var password = $"E2E@Reg-{Guid.NewGuid():N}!"; using (var first = await PostRegisterAsync(new { login, email = UniqueEmail("dup1"), password, })) { first.StatusCode.Should().Be(HttpStatusCode.OK, "seed-create must succeed: {0}", await first.Content.ReadAsStringAsync()); } using var second = await PostRegisterAsync(new { login, email = UniqueEmail("dup2"), password = $"E2E@Reg-{Guid.NewGuid():N}!", }); second.StatusCode.Should().Be(HttpStatusCode.Conflict, "duplicate login must surface 409 (NOT anti-enumeration): {0}", await second.Content.ReadAsStringAsync()); var body = await second.Content.ReadFromJsonAsync(); body.GetProperty("success").GetBoolean().Should().BeFalse(); body.GetProperty("error").GetString().Should().Be("duplicate"); } [Fact] public async Task Register_DuplicateEmail_Returns409() { var email = UniqueEmail("emaildup"); var password = $"E2E@Reg-{Guid.NewGuid():N}!"; using (var first = await PostRegisterAsync(new { login = UniqueLogin("ed1"), email, password })) first.StatusCode.Should().Be(HttpStatusCode.OK, "seed-create must succeed: {0}", await first.Content.ReadAsStringAsync()); // Different login, SAME email → must be rejected when RequireUniqueEmail is on. using var second = await PostRegisterAsync(new { login = UniqueLogin("ed2"), email, password }); second.StatusCode.Should().Be(HttpStatusCode.Conflict, "duplicate email must surface 409: {0}", await second.Content.ReadAsStringAsync()); var body = await second.Content.ReadFromJsonAsync(); body.GetProperty("error").GetString().Should().Be("duplicate"); } [Fact] public async Task Register_DuplicateEmail_CaseInsensitive_Returns409() { // Email is case-insensitive in practice; the server normalises to lower-invariant, so an // upper-case retry of an existing address must collide, not create a second identity. var local = $"reg-caseemail-{Guid.NewGuid():N}"; var password = $"E2E@Reg-{Guid.NewGuid():N}!"; using (var first = await PostRegisterAsync(new { login = UniqueLogin("ci1"), email = $"{local}@example.invalid", password })) first.StatusCode.Should().Be(HttpStatusCode.OK, "seed-create must succeed: {0}", await first.Content.ReadAsStringAsync()); using var second = await PostRegisterAsync(new { login = UniqueLogin("ci2"), email = $"{local.ToUpperInvariant()}@EXAMPLE.INVALID", password }); second.StatusCode.Should().Be(HttpStatusCode.Conflict, "an upper-case variant of an existing email must collide: {0}", await second.Content.ReadAsStringAsync()); } [Fact] public async Task Register_ConcurrentSameEmail_OnlyOneWins() { // The TOCTOU test: fire N registrations of the SAME email at once. The advisory // GetUsersAsync check cannot serialise them — only the UX_users_email unique index can. // Exactly one must win (200); the rest must lose atomically (409), never a 500 and never // two users under one email. var email = UniqueEmail("race"); var password = $"E2E@Reg-{Guid.NewGuid():N}!"; const int n = 6; var tasks = Enumerable.Range(0, n).Select(i => PostRegisterAsync(new { login = UniqueLogin($"race{i}"), email, password })).ToArray(); var responses = await Task.WhenAll(tasks); try { var ok = responses.Count(r => r.StatusCode == HttpStatusCode.OK); var conflict = responses.Count(r => r.StatusCode == HttpStatusCode.Conflict); ok.Should().Be(1, "exactly one concurrent registration of the same email may succeed"); conflict.Should().Be(n - 1, "every other concurrent attempt must lose with 409, not 500"); } finally { foreach (var r in responses) r.Dispose(); } } // \u2550\u2550 Weak password \u2550\u2550 [Fact] public async Task Register_WeakPassword_Returns400() { using var resp = await PostRegisterAsync(new { login = UniqueLogin("weak"), email = UniqueEmail("weak"), // "12345678" is the canonical complexity-policy failure case (length-ok but no diversity). password = "12345678", }); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest, "weak password must be rejected: {0}", await resp.Content.ReadAsStringAsync()); var body = await resp.Content.ReadFromJsonAsync(); body.GetProperty("success").GetBoolean().Should().BeFalse(); body.GetProperty("error").GetString().Should().Be("weak_password"); } // \u2550\u2550 Feature-gate off \u2550\u2550 [Fact] public async Task Register_WhenDisabled_Returns403() { var opts = _fx.ServiceProvider.GetRequiredService>().Value; var original = opts.Registration.Enabled; opts.Registration.Enabled = false; try { using var resp = await PostRegisterAsync(new { login = UniqueLogin("off"), email = UniqueEmail("off"), password = $"E2E@Reg-{Guid.NewGuid():N}!", }); resp.StatusCode.Should().Be(HttpStatusCode.Forbidden, "register must be denied when feature gate is off: {0}", await resp.Content.ReadAsStringAsync()); var body = await resp.Content.ReadFromJsonAsync(); body.GetProperty("success").GetBoolean().Should().BeFalse(); body.GetProperty("error").GetString().Should().Be("registration_disabled"); } finally { opts.Registration.Enabled = original; } } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackBrowserFlowTests.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/FullStackBrowserFlowTests.cs ---- using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E tests for the interactive browser-based flows: /// login → authorize → (consent) → callback, and logout. /// Uses real HTTP with cookie handling to simulate browser behavior. /// [Collection("ProductionHttp")] public class FullStackBrowserFlowTests { private readonly ProductionHttpFixture _fx; public FullStackBrowserFlowTests(ProductionHttpFixture fx) { _fx = fx; } // ══════════════════════════════════════════════ // Login page // ══════════════════════════════════════════════ [Fact] public async Task LoginPage_Get_RendersForm() { using var client = CreateBrowserClient(); var resp = await client.GetAsync("/login"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var body = await resp.Content.ReadAsStringAsync(); body.Should().Contain("username", "login page must have a username field"); body.Should().Contain("password", "login page must have a password field"); body.Should().Contain(" { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword }); var resp = await client.PostAsync("/login", loginForm); cookies.Count.Should().BeGreaterThan(0, "login must set a session cookie"); var body = await resp.Content.ReadAsStringAsync(); body.Should().Contain("Login successful"); } [Fact] public async Task Login_Post_WithReturnUrl_SetsCookieAndRedirects() { var cookies = new CookieContainer(); using var client = CreateBrowserClient(cookies, allowRedirect: false); var loginForm = new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["returnUrl"] = "/connect/authorize" }); var resp = await client.PostAsync("/login", loginForm); // Should redirect with Set-Cookie resp.StatusCode.Should().Be(HttpStatusCode.Redirect); resp.Headers.Location?.ToString().Should().Be("/connect/authorize"); } [Fact] public async Task Login_Post_InvalidCredentials_ReRendersForm() { using var client = CreateBrowserClient(); var loginForm = new FormUrlEncodedContent(new Dictionary { ["username"] = "wrong-user", ["password"] = "wrong-password" }); var resp = await client.PostAsync("/login", loginForm); resp.StatusCode.Should().Be(HttpStatusCode.OK); var body = await resp.Content.ReadAsStringAsync(); body.Should().Contain("username", "error page should re-render the login form"); body.Should().Contain(" { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid", ["code_challenge"] = challenge, ["code_challenge_method"] = "S256" }); var resp = await client.PostAsync("/connect/authorize", form); // Without session: either 302 to /login or an error status if (resp.StatusCode == HttpStatusCode.Redirect) { resp.Headers.Location?.ToString().Should().StartWith("/login"); } else { // OpenIddict returns login_required which maps to 400 ((int)resp.StatusCode).Should().BeGreaterThanOrEqualTo(400); } } [Fact] public async Task Authorize_Post_AfterLogin_ImplicitConsent_ReturnsCode() { var (verifier, challenge) = GeneratePkce(); var cookies = new CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; // Step 1: Login (same pattern as existing AuthorizeViaHttp) var loginForm = new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword }); await client.PostAsync("/login", loginForm); cookies.Count.Should().BeGreaterThan(0, "login must set a session cookie"); // Step 2: POST to authorize with implicit consent client var form = new FormUrlEncodedContent(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid", ["code_challenge"] = challenge, ["code_challenge_method"] = "S256" }); var resp = await client.PostAsync("/connect/authorize", form); // The authorize endpoint may return a 302 redirect or JSON with the code string? code = null; if (resp.StatusCode == HttpStatusCode.Redirect) { var location = resp.Headers.Location?.ToString(); location.Should().NotBeNull(); code = ExtractQueryParam(location!, "code"); } else { resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.TryGetProperty("code", out var c).Should().BeTrue("response should contain code"); code = c.GetString(); } code.Should().NotBeNullOrEmpty("authorization code must be returned"); // Exchange code for tokens to verify it's valid var tokenContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code!, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["code_verifier"] = verifier }); var tokenResp = await _fx.Http.PostAsync("/connect/token", tokenContent); tokenResp.StatusCode.Should().Be(HttpStatusCode.OK, "token exchange failed: {0}", await tokenResp.Content.ReadAsStringAsync()); var tokenJson = await ParseJson(tokenResp); tokenJson.TryGetProperty("access_token", out _).Should().BeTrue(); } // ══════════════════════════════════════════════ // Explicit consent flow // ══════════════════════════════════════════════ [Fact] public async Task Authorize_Post_ExplicitConsent_RedirectsToConsentPage() { var (_, challenge) = GeneratePkce(); var cookies = new CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; // Step 1: Login var loginForm = new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword }); await client.PostAsync("/login", loginForm); cookies.Count.Should().BeGreaterThan(0); // Step 2: POST to authorize with explicit-consent client var form = new FormUrlEncodedContent(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestConsentClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid profile", ["code_challenge"] = challenge, ["code_challenge_method"] = "S256" }); var resp = await client.PostAsync("/connect/authorize", form); // Should redirect to consent page or return consent_required if (resp.StatusCode == HttpStatusCode.Redirect) { var location = resp.Headers.Location?.ToString(); location.Should().NotBeNull(); location.Should().Contain("consent", "explicit consent client should redirect to consent page"); } else { // May return consent_required error as JSON var json = await ParseJson(resp); json.TryGetProperty("error", out var err).Should().BeTrue(); err.GetString().Should().Be("consent_required"); } } [Fact] public async Task ConsentPage_Get_RendersForm() { // The consent page renders only from the server-signed ticket the authorize endpoint // hands out (/consent?ct=…) — never from query parameters a link could carry. So the // page is reached the way a browser reaches it: log in, start an authorize request for // an explicit-consent client, follow the 302. var (_, challenge) = GeneratePkce(); var cookies = new CookieContainer(); using var client = CreateBrowserClient(cookies, allowRedirect: false); var loginForm = new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword }); await client.PostAsync("/login", loginForm); cookies.Count.Should().BeGreaterThan(0, "login must set a session cookie"); var authorize = await client.GetAsync("/connect/authorize?response_type=code" + $"&client_id={ProductionHttpFixture.TestConsentClientId}" + $"&redirect_uri={Uri.EscapeDataString(ProductionHttpFixture.TestRedirectUri)}" + "&scope=openid%20profile" + $"&code_challenge={challenge}&code_challenge_method=S256"); authorize.StatusCode.Should().Be(HttpStatusCode.Redirect, "an explicit-consent client is sent to the consent page"); var location = authorize.Headers.Location!.ToString(); location.Should().StartWith("/consent?ct=", "consent parameters travel in a signed ticket, not as query fields"); var resp = await client.GetAsync(location); resp.StatusCode.Should().Be(HttpStatusCode.OK); var body = await resp.Content.ReadAsStringAsync(); body.Should().Contain("E2E Explicit Consent App", "the app name comes from the client record via the ticket"); body.Should().Contain(" { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword }); await client.PostAsync("/login", loginForm); cookies.Count.Should().BeGreaterThan(0); // Step 2: Verify session is valid — authorize should succeed var (_, challenge) = GeneratePkce(); var form = new FormUrlEncodedContent(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid", ["code_challenge"] = challenge, ["code_challenge_method"] = "S256" }); var authResp = await client.PostAsync("/connect/authorize", form); // Should succeed (302 redirect or 200 JSON with code) ((int)authResp.StatusCode).Should().BeOneOf([200, 302], "authorize should succeed with valid session"); // Step 3: Logout — without an id_token_hint the OP asks the browser to confirm; post the state back. await LogoutFlow.ConfirmAsync(client, await client.PostAsync("/connect/logout", new FormUrlEncodedContent([]))); // Step 4: Authorize again — session should be invalidated var (_, challenge2) = GeneratePkce(); var form2 = new FormUrlEncodedContent(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid", ["code_challenge"] = challenge2, ["code_challenge_method"] = "S256" }); var resp2 = await client.PostAsync("/connect/authorize", form2); // After logout, should NOT get a code — either redirect to login or error if (resp2.StatusCode == HttpStatusCode.Redirect) { resp2.Headers.Location?.ToString().Should().StartWith("/login", "authorize after logout should redirect to login"); } else { // login_required error (mapped to 400+) ((int)resp2.StatusCode).Should().BeGreaterThanOrEqualTo(400, "authorize after logout should fail"); } } // ══════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════ private HttpClient CreateBrowserClient(CookieContainer? cookies = null, bool allowRedirect = true) { cookies ??= new CookieContainer(); var handler = new HttpClientHandler { AllowAutoRedirect = allowRedirect, CookieContainer = cookies, UseCookies = true }; return new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; } private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } private static string? ExtractQueryParam(string url, string param) { var idx = url.IndexOf('?'); if (idx < 0) return null; var query = url[(idx + 1)..]; foreach (var pair in query.Split('&')) { var kv = pair.Split('=', 2); if (kv[0] == param) return Uri.UnescapeDataString(kv[1]); } return null; } private static (string verifier, string challenge) GeneratePkce() { var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); var verifier = Convert.ToBase64String(bytes) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = SHA256.HashData(Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackClaimMappersTests.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/FullStackClaimMappersTests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using Microsoft.IdentityModel.JsonWebTokens; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E regression tests for H5 (v1.0 DoD §5): declarative ClaimMappers must /// flow through the real OpenIddict ProcessSignInContext pipeline and end up /// in the issued access_token JWT. /// /// These tests also guard against the order-bug discovered during B0.1 work: the /// AttachClaimMapperClaims handler was scheduled at int.MaxValue - 200_000, /// AFTER the built-in Exchange.ApplyTokenResponse<ProcessSignInContext> /// (fixed order 500_000) had already short-circuited the dispatcher via /// IsRequestHandled. Result: ClaimMappers were silently dropped from every issued /// token in production. Existing unit tests called the resolver directly and missed it. /// Pre-existing unit tests in ClaimMappersIntegrationTests remain valuable but /// only cover the resolver in isolation. /// /// /// Each test uses a unique claim_type suffix to avoid cross-test contamination. /// /// [Collection("ProductionHttp")] public class FullStackClaimMappersTests { private readonly ProductionHttpFixture _fx; public FullStackClaimMappersTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task GlobalConstantMapper_AppearsInAccessToken() { var claimType = $"e2e_global_{Guid.NewGuid():N}".Substring(0, 32); const string constantValue = "engineering"; await _fx.UseRedbAsync(redb => SeedGlobalMapper( redb, claimType, sourceKind: "Constant", constantValue: constantValue, destinations: new[] { "access_token" })); var token = await IssuePasswordToken("openid profile"); var claim = ReadClaim(token, claimType); claim.Should().Be(constantValue, "global Constant mapper must flow through the OpenIddict pipeline into the JWT access_token. " + "If this fails, AttachClaimMapperClaims is being skipped — verify it runs BEFORE order 500_000."); } [Fact] public async Task UserPropsMapper_ReadsGivenName_FromSeededAdmin() { // The admin user seeded by ProductionHttpFixture has UserProps.GivenName = "E2E". var claimType = $"e2e_given_{Guid.NewGuid():N}".Substring(0, 32); await _fx.UseRedbAsync(redb => SeedGlobalMapper( redb, claimType, sourceKind: "UserProps", sourcePath: "GivenName", destinations: new[] { "access_token" })); var token = await IssuePasswordToken("openid profile"); var claim = ReadClaim(token, claimType); claim.Should().Be("E2E", "UserProps mapper must resolve the seeded GivenName into the access_token"); } [Fact] public async Task ScopeFilteredMapper_OmittedWhenScopeNotRequested() { // Mapper requires scope "profile" — a request without it must NOT include the claim. var claimType = $"e2e_scoped_{Guid.NewGuid():N}".Substring(0, 32); await _fx.UseRedbAsync(redb => SeedGlobalMapper( redb, claimType, sourceKind: "Constant", constantValue: "should_not_appear", requiredScopes: new[] { "profile" }, destinations: new[] { "access_token" })); // Issue token WITHOUT "profile" scope. var token = await IssuePasswordToken("openid"); var jwt = new JsonWebTokenHandler().ReadJsonWebToken(token); jwt.TryGetPayloadValue(claimType, out _).Should().BeFalse( "scope-filtered mapper must be skipped when its RequiredScopes are not requested"); } // ───────────────────────────────────────────────────────────────────────── // helpers // ───────────────────────────────────────────────────────────────────────── private async Task IssuePasswordToken(string scope) { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = scope, }); var resp = await _fx.Http.PostAsync("/connect/token", content); var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.OK, "token issuance must succeed for non-gated test scope: {0}", body); var json = JsonDocument.Parse(body).RootElement; return json.GetProperty("access_token").GetString()!; } private static string? ReadClaim(string accessToken, string claimType) { var jwt = new JsonWebTokenHandler().ReadJsonWebToken(accessToken); return jwt.TryGetPayloadValue(claimType, out var value) ? value : null; } private static async Task SeedGlobalMapper( IRedbService redb, string claimType, string sourceKind, string? sourcePath = null, string? constantValue = null, string[]? requiredScopes = null, string[]? destinations = null, bool required = false, int order = 0) { var mapper = new RedbObject(new ClaimMapperProps { ClaimType = claimType, SourceKind = sourceKind, SourcePath = sourcePath, ConstantValue = constantValue, RequiredScopes = requiredScopes, Destinations = destinations, Required = required, Order = order, Enabled = true, }); mapper.Name = $"e2e:{sourceKind}->{claimType}"; // parent_id null → global mapper (applied to every token) await redb.SaveAsync(mapper); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackConsentTests.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/FullStackConsentTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E tests for consent management via HTTP. /// Complete path: HTTP → Kestrel → bearer auth → controller → direct-vm:// → processor → PG. /// [Collection("ProductionHttp")] public class FullStackConsentTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public FullStackConsentTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } private HttpRequestMessage WithAuth(HttpRequestMessage request) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return request; } [Fact] public async Task Consents_ListEmpty_ViaHttp() { // Use a random userId that has no consents var userId = Random.Shared.NextInt64(900_000, 999_999); var req = WithAuth(new HttpRequestMessage(HttpMethod.Get, $"/api/v1/identity/consents?userId={userId}")); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.ValueKind.Should().Be(JsonValueKind.Array); json.GetArrayLength().Should().Be(0); } [Fact] public async Task Consents_GrantThenList_ViaHttp() { // All test-side DB access must go through UseRedbAsync — _fx.Redb is captive and // would race with the audit-sink / OpenIddict pipeline that run on their own scopes. var (coreUserId, appId) = await _fx.UseRedbAsync(async redb => { var consentService = new ConsentService(redb); var coreUser = await redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername) ?? throw new Exception("Test user not found"); var app = await redb.Query() .Where(p => p.ClientId == ProductionHttpFixture.TestClientId) .FirstOrDefaultAsync(); app.Should().NotBeNull(); await consentService.GrantAsync(coreUser.Id, app!.id, ["openid", "profile"]); return (coreUser.Id, app.id); }); try { var req = WithAuth(new HttpRequestMessage(HttpMethod.Get, $"/api/v1/identity/consents?userId={coreUserId}")); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.ValueKind.Should().Be(JsonValueKind.Array); json.GetArrayLength().Should().BeGreaterThan(0); // Find the consent we just created var found = false; foreach (var item in json.EnumerateArray()) { if (item.GetProperty("applicationId").GetInt64() == appId) { item.GetProperty("userId").GetInt64().Should().Be(coreUserId); item.GetProperty("clientId").GetString().Should().Be(ProductionHttpFixture.TestClientId); item.GetProperty("status").GetString().Should().Be("valid"); found = true; break; } } found.Should().BeTrue("should find the granted consent in the list"); } finally { // Cleanup in its own scope await _fx.UseRedbAsync(async redb => { var consentService = new ConsentService(redb); await consentService.RevokeAsync(coreUserId, appId); }); } } [Fact] public async Task Consents_RevokeViaHttp() { var (coreUserId, appId) = await _fx.UseRedbAsync(async redb => { var consentService = new ConsentService(redb); var coreUser = await redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername) ?? throw new Exception("Test user not found"); var app = await redb.Query() .Where(p => p.ClientId == ProductionHttpFixture.TestClientId) .FirstOrDefaultAsync(); await consentService.GrantAsync(coreUser.Id, app!.id, ["openid"]); return (coreUser.Id, app.id); }); // Revoke via HTTP var req = WithAuth(new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/identity/consents?userId={coreUserId}&applicationId={appId}")); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.GetProperty("success").GetBoolean().Should().BeTrue(); json.GetProperty("revoked").GetInt32().Should().BeGreaterThanOrEqualTo(1); // Verify revoked in its own scope await _fx.UseRedbAsync(async redb => { var consentService = new ConsentService(redb); var check = await consentService.CheckAsync(coreUserId, appId, ["openid"]); check.Should().BeNull(); }); } [Fact] public async Task Consents_RevokeAllViaHttp() { var coreUserId = await _fx.UseRedbAsync(async redb => { var consentService = new ConsentService(redb); var coreUser = await redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername) ?? throw new Exception("Test user not found"); var app1 = await redb.Query() .Where(p => p.ClientId == ProductionHttpFixture.TestClientId) .FirstOrDefaultAsync(); var app2 = await redb.Query() .Where(p => p.ClientId == ProductionHttpFixture.TestPublicClientId) .FirstOrDefaultAsync(); await consentService.GrantAsync(coreUser.Id, app1!.id, ["openid"]); await consentService.GrantAsync(coreUser.Id, app2!.id, ["openid", "profile"]); return coreUser.Id; }); // Revoke all via HTTP var req = WithAuth(new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/identity/consents/all?userId={coreUserId}")); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.GetProperty("success").GetBoolean().Should().BeTrue(); // Verify all revoked in its own scope await _fx.UseRedbAsync(async redb => { var consentService = new ConsentService(redb); var list = await consentService.ListAsync(coreUserId); list.Should().BeEmpty(); }); } [Fact] public async Task Consents_NoBearerToken_Returns401() { var resp = await _http.GetAsync("/api/v1/identity/consents?userId=1"); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); } private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackDeviceCodeTests.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/FullStackDeviceCodeTests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E tests for RFC 8628 Device Code flow via HTTP. /// Path: HTTP → Kestrel → HTTP facade → direct-vm:// → OpenIddict → redb stores → PostgreSQL. /// [Collection("ProductionHttp")] public class FullStackDeviceCodeTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public FullStackDeviceCodeTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } // ══════════════════════════════════════════════ // Device Authorization — happy path // ══════════════════════════════════════════════ [Fact] public async Task DeviceAuthorization_ReturnsDeviceAndUserCodes() { var content = new FormUrlEncodedContent(new Dictionary { ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["scope"] = "openid profile" }); var resp = await _http.PostAsync("/connect/deviceauthorization", content); resp.StatusCode.Should().Be(HttpStatusCode.OK, "device authorization failed: {0}", await resp.Content.ReadAsStringAsync()); var json = await ParseJson(resp); json.TryGetProperty("device_code", out var dc).Should().BeTrue("response must contain device_code"); dc.GetString().Should().NotBeNullOrEmpty(); json.TryGetProperty("user_code", out var uc).Should().BeTrue("response must contain user_code"); uc.GetString().Should().NotBeNullOrEmpty(); json.TryGetProperty("verification_uri", out _).Should().BeTrue("response must contain verification_uri"); json.TryGetProperty("expires_in", out var exp).Should().BeTrue("response must contain expires_in"); exp.GetInt32().Should().BeGreaterThan(0); } // ══════════════════════════════════════════════ // Token polling — authorization_pending // ══════════════════════════════════════════════ [Fact] public async Task DeviceCode_Poll_BeforeApproval_ReturnsAuthorizationPending() { // Step 1: Obtain device code var authContent = new FormUrlEncodedContent(new Dictionary { ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["scope"] = "openid" }); var authResp = await _http.PostAsync("/connect/deviceauthorization", authContent); authResp.StatusCode.Should().Be(HttpStatusCode.OK); var authJson = await ParseJson(authResp); var deviceCode = authJson.GetProperty("device_code").GetString()!; // Step 2: Poll token endpoint — should get authorization_pending var tokenContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "urn:ietf:params:oauth:grant-type:device_code", ["device_code"] = deviceCode, ["client_id"] = ProductionHttpFixture.TestPublicClientId }); var tokenResp = await _http.PostAsync("/connect/token", tokenContent); tokenResp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var tokenJson = await ParseJson(tokenResp); tokenJson.GetProperty("error").GetString().Should().Be("authorization_pending"); } // ══════════════════════════════════════════════ // Error paths // ══════════════════════════════════════════════ [Fact] public async Task DeviceAuthorization_UnknownClient_ReturnsError() { var content = new FormUrlEncodedContent(new Dictionary { ["client_id"] = "nonexistent-client-id", ["scope"] = "openid" }); var resp = await _http.PostAsync("/connect/deviceauthorization", content); resp.IsSuccessStatusCode.Should().BeFalse("unknown client should be rejected"); var json = await ParseJson(resp); json.TryGetProperty("error", out _).Should().BeTrue(); } [Fact] public async Task DeviceAuthorization_MissingClientId_ReturnsError() { var content = new FormUrlEncodedContent(new Dictionary { ["scope"] = "openid" }); var resp = await _http.PostAsync("/connect/deviceauthorization", content); resp.IsSuccessStatusCode.Should().BeFalse("missing client_id should be rejected"); var json = await ParseJson(resp); json.TryGetProperty("error", out _).Should().BeTrue(); } [Fact] public async Task DeviceAuthorization_ClientWithoutPermission_ReturnsError() { // Management client has no device code permissions var content = new FormUrlEncodedContent(new Dictionary { ["client_id"] = ProductionHttpFixture.TestMgmtClientId, ["client_secret"] = ProductionHttpFixture.TestMgmtSecret, ["scope"] = "openid" }); var resp = await _http.PostAsync("/connect/deviceauthorization", content); resp.IsSuccessStatusCode.Should().BeFalse("client without device_code permission should be rejected"); } [Fact] public async Task DeviceCode_Poll_InvalidDeviceCode_ReturnsError() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "urn:ietf:params:oauth:grant-type:device_code", ["device_code"] = "invalid-device-code-12345", ["client_id"] = ProductionHttpFixture.TestPublicClientId }); var resp = await _http.PostAsync("/connect/token", content); resp.IsSuccessStatusCode.Should().BeFalse(); var json = await ParseJson(resp); json.TryGetProperty("error", out _).Should().BeTrue(); } // ══════════════════════════════════════════════ // Discovery — device code in discovery // ══════════════════════════════════════════════ [Fact] public async Task Discovery_ContainsDeviceAuthorizationEndpoint() { var resp = await _http.GetAsync("/.well-known/openid-configuration"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.TryGetProperty("device_authorization_endpoint", out var ep).Should() .BeTrue("discovery must include device_authorization_endpoint when enabled"); ep.GetString().Should().Contain("/connect/deviceauthorization"); // grant_types_supported should include device_code var grants = json.GetProperty("grant_types_supported"); grants.EnumerateArray().Select(g => g.GetString()) .Should().Contain("urn:ietf:params:oauth:grant-type:device_code"); } // ══════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════ private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackDynamicRegistrationTests.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/FullStackDynamicRegistrationTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E tests for Dynamic Client Registration (RFC 7591). /// Complete path: HTTP POST /connect/register → Kestrel → HTTP facade → ExtractBearerToken /// → direct-vm://identity-dynamic-register → Throttle → DynamicRegistrationProcessor /// → redb stores → PostgreSQL → HTTP 201 response. /// Then: dynamically registered client authenticates via /connect/token. /// [Collection("ProductionHttp")] public class FullStackDynamicRegistrationTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public FullStackDynamicRegistrationTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } // ══════════════════════════════════════════════ // Happy path // ══════════════════════════════════════════════ [Fact] public async Task Register_MinimalRequest_Returns201WithClientId() { var req = DynRegRequest(new { redirect_uris = new[] { "http://localhost/callback" }, client_name = "E2E Minimal" }); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Created, "register failed: {0}", await resp.Content.ReadAsStringAsync()); var json = await ParseJson(resp); json.TryGetProperty("client_id", out var cid).Should().BeTrue("response must contain client_id"); cid.GetString().Should().NotBeNullOrWhiteSpace(); json.TryGetProperty("client_secret", out _).Should().BeTrue("confidential by default → secret returned"); json.GetProperty("token_endpoint_auth_method").GetString().Should().Be("client_secret_basic"); json.TryGetProperty("client_id_issued_at", out _).Should().BeTrue(); } [Fact] public async Task Register_PublicClient_NoSecretReturned() { var req = DynRegRequest(new { redirect_uris = new[] { "http://localhost/callback" }, token_endpoint_auth_method = "none", client_name = "E2E Public" }); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Created); var json = await ParseJson(resp); json.GetProperty("token_endpoint_auth_method").GetString().Should().Be("none"); // Public clients should NOT have a secret if (json.TryGetProperty("client_secret", out var secret)) secret.ValueKind.Should().Be(JsonValueKind.Null); } [Fact] public async Task Register_ConfidentialClient_CanObtainToken() { // Step 1: Register a new confidential client var regReq = DynRegRequest(new { redirect_uris = new[] { "http://localhost/callback" }, grant_types = new[] { "client_credentials" }, client_name = "E2E Token Test", scope = "openid" }); var regResp = await _http.SendAsync(regReq); regResp.StatusCode.Should().Be(HttpStatusCode.Created, "register failed: {0}", await regResp.Content.ReadAsStringAsync()); var regJson = await ParseJson(regResp); var clientId = regJson.GetProperty("client_id").GetString()!; var clientSecret = regJson.GetProperty("client_secret").GetString()!; // Step 2: Use the registered client to obtain an access token var tokenContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = clientId, ["client_secret"] = clientSecret }); var tokenResp = await _http.PostAsync("/connect/token", tokenContent); tokenResp.StatusCode.Should().Be(HttpStatusCode.OK, "token request with dynamically registered client failed: {0}", await tokenResp.Content.ReadAsStringAsync()); var tokenJson = await ParseJson(tokenResp); tokenJson.TryGetProperty("access_token", out _).Should().BeTrue( "dynamically registered client should receive an access_token"); tokenJson.GetProperty("token_type").GetString().Should().Be("Bearer"); } [Fact] public async Task Register_WithRefreshAndAuthCode_HasCorrectPermissions() { var req = DynRegRequest(new { redirect_uris = new[] { "http://localhost/callback" }, grant_types = new[] { "authorization_code", "refresh_token" }, response_types = new[] { "code" }, scope = "openid profile email", client_name = "E2E Full OIDC" }); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Created); var json = await ParseJson(resp); json.GetProperty("client_id").GetString().Should().NotBeNullOrWhiteSpace(); json.GetProperty("client_secret").GetString().Should().NotBeNullOrWhiteSpace(); var grantTypes = json.GetProperty("grant_types"); grantTypes.GetArrayLength().Should().Be(2); } // ══════════════════════════════════════════════ // Initial access token enforcement // ══════════════════════════════════════════════ [Fact] public async Task Register_WithoutAccessToken_Returns401() { // No Bearer token → should be rejected var req = new HttpRequestMessage(HttpMethod.Post, "/connect/register") { Content = JsonContent.Create(new { redirect_uris = new[] { "http://localhost/callback" }, client_name = "No Token" }) }; var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_token"); } [Fact] public async Task Register_WithWrongAccessToken_Returns401() { var req = new HttpRequestMessage(HttpMethod.Post, "/connect/register") { Content = JsonContent.Create(new { redirect_uris = new[] { "http://localhost/callback" }, client_name = "Wrong Token" }) }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "completely-wrong-token"); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_token"); } // ══════════════════════════════════════════════ // Validation errors // ══════════════════════════════════════════════ [Fact] public async Task Register_InvalidGrantType_Returns400() { var req = DynRegRequest(new { redirect_uris = new[] { "http://localhost/callback" }, grant_types = new[] { "urn:ietf:params:oauth:grant-type:device_code" }, // not in allowed list client_name = "Bad Grant" }); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_client_metadata"); json.GetProperty("error_description").GetString().Should().Contain("not allowed"); } [Fact] public async Task Register_DisallowedScope_Returns400() { var req = DynRegRequest(new { redirect_uris = new[] { "http://localhost/callback" }, scope = "openid identity:manage", // identity:manage is forbidden client_name = "Scope Escalation" }); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_client_metadata"); json.GetProperty("error_description").GetString().Should().Contain("not allowed"); } [Fact] public async Task Register_MissingRedirectUris_Returns400() { // authorization_code requires redirect_uris var req = DynRegRequest(new { grant_types = new[] { "authorization_code" }, client_name = "No URIs" }); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_redirect_uri"); } [Fact] public async Task Register_InvalidBody_Returns400() { var req = new HttpRequestMessage(HttpMethod.Post, "/connect/register") { Content = new StringContent("not json at all", System.Text.Encoding.UTF8, "application/json") }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ProductionHttpFixture.DynamicRegAccessToken); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_client_metadata"); } [Fact] public async Task Register_UnsupportedAuthMethod_Returns400() { // RFC 7591 §2 token_endpoint_auth_method values we currently support: // none, client_secret_basic, client_secret_post, private_key_jwt // (the test originally used "private_key_jwt" — but DynamicRegistrationProcessor now // accepts it as a confidential client and routes through the jwks-required branch, // so a request with that method + no jwks yields a SPECIFIC // "private_key_jwt requires `jwks`" error rather than the generic Unsupported one // the test name asks for.) `client_secret_jwt` is RFC 7523 §2.2 but our processor // doesn't implement it, so it correctly falls into the Unsupported else-branch. var req = DynRegRequest(new { redirect_uris = new[] { "http://localhost/callback" }, token_endpoint_auth_method = "client_secret_jwt", client_name = "Bad Auth Method" }); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_client_metadata"); json.GetProperty("error_description").GetString().Should().Contain("Unsupported"); } [Fact] public async Task Register_InvalidApplicationType_Returns400() { var req = DynRegRequest(new { redirect_uris = new[] { "http://localhost/callback" }, application_type = "desktop", client_name = "Bad App Type" }); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_client_metadata"); } // ══════════════════════════════════════════════ // Discovery integration // ══════════════════════════════════════════════ [Fact] public async Task Discovery_ContainsRegistrationEndpoint_WhenEnabled() { var resp = await _http.GetAsync("/.well-known/openid-configuration"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.TryGetProperty("registration_endpoint", out var regEndpoint).Should().BeTrue( "registration_endpoint must appear in discovery when EnableDynamicRegistration=true"); var expected = $"http://localhost:{_fx.Port}/connect/register"; regEndpoint.GetString().Should().Be(expected); } // ══════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════ /// /// Creates a POST /connect/register request with valid initial access token. /// private static HttpRequestMessage DynRegRequest(object body) { var req = new HttpRequestMessage(HttpMethod.Post, "/connect/register") { Content = JsonContent.Create(body) }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ProductionHttpFixture.DynamicRegAccessToken); return req; } private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackEmailVerificationSmtpTests.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/FullStackEmailVerificationSmtpTests.cs ---- using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using AwesomeAssertions; using MailKit.Net.Imap; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Configuration; using redb.Identity.Core.Services; using redb.Route.Components; using redb.Route.Core; using redb.Route.Mail; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.FullStack; /// /// N-4 (Session C, N4-6): SMTP integration test for the email-verification template. /// Mirrors but exercises the e-mail /// verification template () end-to-end /// through against the GreenMail container. /// Verifies that the rendered HTML body embeds the supplied verifyLink substitution /// and that the multipart text/plain alternative survives the round-trip. /// [Trait("Category", "Integration")] [Trait("Requires", "Greenmail")] public sealed class FullStackEmailVerificationSmtpTests { private const string GreenmailHost = "127.0.0.1"; private const int GreenmailSmtpPort = 3025; private const int GreenmailImapPort = 3143; private const string ApiBase = "http://127.0.0.1:8080"; private readonly ITestOutputHelper _output; public FullStackEmailVerificationSmtpTests(ITestOutputHelper output) => _output = output; [Fact] public async Task SmtpEmailNotificationChannel_EmailVerificationTemplate_LandsInGreenmailInbox() { SkipIfGreenmailUnavailable(); var recipientUser = $"e2e-verify-{Guid.NewGuid():N}"; var recipient = $"{recipientUser}@localhost"; await ProvisionGreenmailUserAsync(recipientUser, "secret"); var sc = new ServiceCollection(); sc.AddSingleton(); await using var sp = sc.BuildServiceProvider(); await using var ctx = new RouteContext(sp); ctx.AddComponent(new SmtpComponent()); ctx.AddRoutes(r => { r.From(IdentityEndpoints.EmailSend) .RouteId(IdentityEndpoints.RouteIds.EmailSend) .To(Smtp.Send(GreenmailHost) .Port(GreenmailSmtpPort) .Security("None") .From("noreply@redb.local") .ContentType("text/html") .AlternativeBody()); }); await ctx.Start(); var options = Options.Create(new RedbIdentityOptions { Smtp = new SmtpOptions { Enabled = true, Host = GreenmailHost, Port = GreenmailSmtpPort, Security = "None", FromAddress = "noreply@redb.local", } }); var registry = new InlineEmailTemplateRegistry(); using var channel = new SmtpEmailNotificationChannel(ctx, registry, options, NullLoggerFactory.Instance); var verifyToken = Guid.NewGuid().ToString("N"); var verifyLink = $"https://app.redb.local/verify-email?jti=verify-jti&token={verifyToken}"; var vars = new Dictionary(StringComparer.Ordinal) { ["userName"] = recipient, ["verifyLink"] = verifyLink, ["ttlHours"] = "24", }; await channel.SendTemplateAsync(recipient, IdentityEmailTemplates.EmailVerification, vars); var (subject, htmlBody, textBody) = await ReadFirstMessageAsync(recipientUser, "secret"); _output.WriteLine($"Subject: {subject}"); _output.WriteLine($"HTML body length: {htmlBody?.Length ?? 0}"); subject.Should().NotBeNullOrWhiteSpace("the channel must populate redbMail.Subject from the rendered template"); htmlBody.Should().NotBeNull("the channel sets ContentType=text/html so the body is rendered as HTML alternative"); htmlBody!.Should().Contain(verifyToken, "the rendered HTML must embed the {verifyLink} substitution"); textBody.Should().NotBeNullOrWhiteSpace("the rendered text body should be included as the multipart text/plain alternative"); } // ── Helpers (verbatim from FullStackPasswordRecoverySmtpTests; kept inline so each // integration test file is self-contained and can be removed independently) ── private static void SkipIfGreenmailUnavailable() { var reachable = false; try { using var probe = new TcpClient(); var task = probe.ConnectAsync(GreenmailHost, GreenmailSmtpPort); reachable = task.Wait(TimeSpan.FromMilliseconds(500)) && probe.Connected; } catch { /* fall through — reachable stays false */ } Assert.True(reachable, $"Greenmail not reachable on {GreenmailHost}:{GreenmailSmtpPort}. " + "Start with: docker compose -f redb.Route/docker-compose.tests.yml up greenmail -d, " + "or filter this test out via `--filter Category!=Integration`."); } private static async Task ProvisionGreenmailUserAsync(string login, string password) { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(3) }; var json = $"{{\"email\":\"{login}@localhost\",\"login\":\"{login}\",\"password\":\"{password}\"}}"; using var content = new StringContent(json, Encoding.UTF8, "application/json"); try { using var _ = await http.PostAsync($"{ApiBase}/api/user", content); } catch { /* greenmail REST is best-effort here — SMTP listener creates the account on delivery anyway. */ } } private static async Task<(string? Subject, string? HtmlBody, string? TextBody)> ReadFirstMessageAsync( string login, string password) { Exception? lastError = null; for (var attempt = 0; attempt < 15; attempt++) { try { using var imap = new ImapClient(); await imap.ConnectAsync(GreenmailHost, GreenmailImapPort, MailKit.Security.SecureSocketOptions.None); await imap.AuthenticateAsync(login, password); var inbox = imap.Inbox; await inbox.OpenAsync(MailKit.FolderAccess.ReadOnly); if (inbox.Count > 0) { var msg = await inbox.GetMessageAsync(0); await imap.DisconnectAsync(true); return (msg.Subject, msg.HtmlBody, msg.TextBody); } await imap.DisconnectAsync(true); } catch (Exception ex) { lastError = ex; } await Task.Delay(200); } throw new Xunit.Sdk.XunitException( $"No message arrived in {login}@localhost INBOX within 3 s. Last error: {lastError?.Message}"); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackFacadeFormHardeningTests.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/FullStackFacadeFormHardeningTests.cs ---- using System.Net; using System.Net.Http.Headers; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using System.Security.Cryptography; using System.Text; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Http.Processors; using redb.Identity.Http.Security; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Hardening of the HTTP facade's own HTML forms (login, consent, MFA), end to end. /// /// Three findings of 2026-09-09, all previously absent from the facade while present in /// the web console: (1) no browser-protection headers, so every facade page could be framed /// (clickjacking on the consent "Allow" button); (2) the consent POST trusted a hidden /// user_id field over the session and ReadSessionCookie let cookie-less /// requests through, so an anonymous cross-site POST recorded any user's consent for any /// client; (3) no cross-site request check on any form POST (login CSRF). The web console's /// BFF and the demo scripts post these forms without a browser — hence the Origin/Referer /// model rather than a form token: a request that announces no origin is let through, one /// that announces a foreign origin is refused. /// /// [Collection("ProductionHttp")] public class FullStackFacadeFormHardeningTests { private readonly ProductionHttpFixture _fx; public FullStackFacadeFormHardeningTests(ProductionHttpFixture fx) => _fx = fx; // ───────────────────────────────────────────────────────────────────────── // (1) browser-protection headers // ───────────────────────────────────────────────────────────────────────── [Theory] [InlineData("/login")] [InlineData("/consent?client_id=e2e-explicit-consent&scopes=openid")] [InlineData("/.well-known/openid-configuration")] public async Task FacadeResponses_CarryFrameAndSniffProtection(string path) { var resp = await Anonymous().GetAsync(path); HeaderValue(resp, "X-Frame-Options").Should().Be("DENY", "the facade renders login/consent/MFA pages itself and none may be framed"); HeaderValue(resp, "Content-Security-Policy").Should().Contain("frame-ancestors 'none'"); HeaderValue(resp, "X-Content-Type-Options").Should().Be("nosniff"); HeaderValue(resp, "Referrer-Policy").Should().NotBeNullOrEmpty(); } // ───────────────────────────────────────────────────────────────────────── // (2) consent is bound to the session, never to a form field // ───────────────────────────────────────────────────────────────────────── [Fact] public async Task ConsentPost_WithoutSession_Is401_AndRecordsNothing() { var victim = Random.Shared.NextInt64(1_000_000_000, long.MaxValue); var appId = await AppObjectIdAsync(ProductionHttpFixture.TestConsentClientId); var resp = await Anonymous().PostAsync("/consent", new FormUrlEncodedContent(new Dictionary { ["client_id"] = ProductionHttpFixture.TestConsentClientId, ["user_id"] = victim.ToString(), ["scopes"] = "openid profile", ["decision"] = "allow", ["returnUrl"] = "/connect/authorize?client_id=x", })); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized, "a consent decision without a session cookie is not a decision anyone made; body: {0}", await resp.Content.ReadAsStringAsync()); HeaderValue(resp, "X-Frame-Options").Should().Be("DENY", "rejections carry the same headers"); (await ConsentsOfAsync(victim, appId)).Should().BeEmpty( "before the fix this anonymous POST recorded a permanent authorization for the victim"); } [Fact] public async Task ConsentPost_IgnoresFormUserId_AndGrantsForTheSessionUser() { var forged = Random.Shared.NextInt64(1_000_000_000, long.MaxValue); var clientId = await SeedExplicitConsentClientAsync(); var appId = await AppObjectIdAsync(clientId); var cookies = new CookieContainer(); using var browser = CreateBrowserClient(cookies); await LoginAsync(browser); var resp = await browser.PostAsync("/consent", new FormUrlEncodedContent(new Dictionary { ["client_id"] = clientId, ["user_id"] = forged.ToString(), ["scopes"] = "openid profile", ["decision"] = "allow", ["returnUrl"] = "/connect/authorize?client_id=" + clientId, })); resp.StatusCode.Should().BeOneOf(new[] { HttpStatusCode.Found, HttpStatusCode.SeeOther }, "a logged-in user's decision is accepted and redirected back to the authorize URL"); (await ConsentsOfAsync(forged, appId)).Should().BeEmpty("the form's user_id is not who consented"); var recorded = await _fx.UseRedbAsync(async redb => await redb.Query() .Where(a => a.ApplicationObjectId == appId) .ToListAsync()); recorded.Should().ContainSingle("exactly one grant — the session user's — exists for a fresh client") .Which.key.Should().NotBe(forged); } [Fact] public async Task ConsentPage_NoLongerEmbedsAUserId() { var resp = await Anonymous().GetAsync("/consent?client_id=e2e-explicit-consent&scopes=openid&user_id=42"); var html = await resp.Content.ReadAsStringAsync(); html.Should().NotContain("name=\"user_id\"", "the consenting user is the session's, so the form has nothing to say about it"); } [Fact] public async Task ConsentPage_WithoutTicket_IsRefused_NotRenderedFromQuery() { // The phishing link: a crafted /consent URL naming the attacker's client under a // familiar app name. Before the fix the page rendered app_name straight from the query. var resp = await Anonymous().GetAsync( "/consent?client_id=e2e-attacker&app_name=Your%20Bank&scopes=openid%20profile"); var html = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest, "the consent page renders only from a server-signed ticket, never from query parameters"); html.Should().NotContain("Your Bank", "the attacker-supplied display name must never reach the operator's trusted UI"); } [Fact] public async Task ConsentPost_WithTicketForAnotherUser_Is403() { // Same DataProtection provider (and purpose) as the facade's own instance, so the server // accepts the signature — the fixture constructs its ticket service inline, not via DI. var ticketService = new SessionTicketService( _fx.ServiceProvider.GetRequiredService()); var otherUser = Random.Shared.NextInt64(1_000_000_000, long.MaxValue); var ticket = ticketService.ProtectConsent(new ConsentTicket( UserId: otherUser, ClientId: ProductionHttpFixture.TestConsentClientId, AppName: "App", Scopes: "openid", ReturnUrl: "/connect/authorize?client_id=x")); var cookies = new CookieContainer(); using var browser = CreateBrowserClient(cookies); await LoginAsync(browser); var req = new HttpRequestMessage(HttpMethod.Post, "/consent") { Content = new FormUrlEncodedContent(new Dictionary { ["ct"] = ticket, ["decision"] = "allow", }) }; req.Headers.TryAddWithoutValidation("Origin", _fx.BaseUrl); var resp = await browser.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Forbidden, "a ticket minted for another user cannot be replayed under this session"); } // ───────────────────────────────────────────────────────────────────────── // (4) session identity is never trusted from an HTTP header // ───────────────────────────────────────────────────────────────────────── [Fact] public async Task Authorize_WithForgedSessionHeader_DoesNotAuthenticate() { var victim = Random.Shared.NextInt64(1_000_000_000, long.MaxValue); var (verifier, challenge) = Pkce(); var url = "/connect/authorize?response_type=code" + $"&client_id={ProductionHttpFixture.TestPublicClientId}" + $"&redirect_uri={Uri.EscapeDataString(ProductionHttpFixture.TestRedirectUri)}" + "&scope=openid" + $"&code_challenge={challenge}&code_challenge_method=S256"; var req = new HttpRequestMessage(HttpMethod.Get, url); req.Headers.TryAddWithoutValidation("session_user_id", victim.ToString()); req.Headers.TryAddWithoutValidation("session_username", "victim"); var resp = await Anonymous().SendAsync(req); // The property under test: the forged header does NOT authenticate. Before the fix this // request was answered with a 302 to the client's redirect_uri carrying a code for the // victim. Unauthenticated, the facade sends the browser to /login (or answers with an // OAuth error) — never to the redirect_uri, never with a code. var location = resp.Headers.Location?.ToString() ?? ""; location.Should().NotStartWith(ProductionHttpFixture.TestRedirectUri, "a session_user_id sent as an HTTP header must NOT mint an authorization code — " + "before the fix the header was copied into the exchange and trusted as the principal"); location.Should().NotContain("code="); resp.Headers.Contains("Set-Cookie").Should().BeFalse("no session is established by a header"); if (resp.StatusCode is HttpStatusCode.Found or HttpStatusCode.SeeOther) location.Should().StartWith("/login", "an unauthenticated authorize request goes to the login page"); else ((int)resp.StatusCode).Should().BeGreaterThanOrEqualTo(400, "or is refused as login_required"); } [Fact] public async Task AuditLog_IgnoresForgedAttributionHeaders_AndRecordsTheRealClient() { // EventDispatchProcessor reads user_id / ip_address / user_agent from the WireTap copy // of the business exchange — the same In.Headers the HTTP consumer fills from the // request. Before the fix a client could sign the security log with someone else's // user id, a fabricated address and a fabricated agent. // Revocation is one of the WireTap-audited routes reachable over HTTP (TokenRevoked). var realAgent = $"hardening-probe/{Guid.NewGuid():N}"; const string forgedIp = "203.0.113.77"; const string forgedAgent = "forged-agent/1.0"; const long forgedUser = 987_654_321L; var token = await IssueClientCredentialsTokenAsync(); var req = new HttpRequestMessage(HttpMethod.Post, "/connect/revocation") { Content = new FormUrlEncodedContent(new Dictionary { ["token"] = token, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, }) }; req.Headers.TryAddWithoutValidation("User-Agent", realAgent); req.Headers.TryAddWithoutValidation("ip_address", forgedIp); req.Headers.TryAddWithoutValidation("user_agent", forgedAgent); req.Headers.TryAddWithoutValidation("user_id", forgedUser.ToString()); var resp = await Anonymous().SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, "RFC 7009: revocation answers 200: {0}", await resp.Content.ReadAsStringAsync()); var row = await FindAuditRowAsync("TokenRevoked", i => AgentOf(i) == realAgent || AgentOf(i) == forgedAgent); row.Should().NotBeNull("the revocation must be audited; newest TokenRevoked rows seen: {0}", await DescribeAuditRowsAsync("TokenRevoked")); AgentOf(row!.Value).Should().Be(realAgent, "the audited agent is the real User-Agent, not the forged internal header"); var ip = Field(row.Value, "ipAddress", "ip_address"); ip.Should().NotBe(forgedIp, "the audited address is the transport's, not a header the client typed"); ip.Should().NotBeNullOrEmpty("HTTP-originated events fall back to the proxy-sanitized remote address"); var userId = NumberField(row.Value, "userId", "user_id"); userId.Should().NotBe(forgedUser, "a client-credentials token has no end-user; the audited user id must not be the header the client typed"); // Attribution the row must carry: the form-authenticated client (client_id used to be a header // only for Basic auth, so form-auth clients were audited as NULL) and a real timestamp (the // SQLite audit table declared TEXT while the provider writes Julian REAL, so it read back as // 0001-01-01 and date filters compared text to a number). Field(row.Value, "clientId", "client_id").Should().Be(ProductionHttpFixture.TestClientId, "the revoking client authenticated with form credentials and must be attributed"); var ts = Field(row.Value, "timestamp", "timestamp"); ts.Should().NotBeNullOrEmpty(); DateTimeOffset.Parse(ts!, System.Globalization.CultureInfo.InvariantCulture).Should() .BeCloseTo(DateTimeOffset.UtcNow, TimeSpan.FromMinutes(10), "the audit timestamp must round-trip through the provider's datetime encoding"); } private async Task IssueClientCredentialsTokenAsync() { var resp = await Anonymous().PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, })); var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.OK, "token issuance must succeed: {0}", body); return System.Text.Json.JsonDocument.Parse(body).RootElement.GetProperty("access_token").GetString()!; } [Fact] public void StripReservedInboundHeaders_RemovesInternalIdentityHeaders() { var ex = new redb.Route.Core.Exchange(new redb.Route.Core.Message()); ex.In.Headers["session_user_id"] = "42"; ex.In.Headers["session_id"] = "100"; ex.In.Headers["access_token"] = "forged"; ex.In.Headers["operation"] = "delete"; ex.In.Headers["X-Correlation-Id"] = "keep-me"; redb.Identity.Http.Processors.HttpIdentityProcessors.StripReservedInboundHeaders(ex); ex.In.Headers.ContainsKey("session_user_id").Should().BeFalse(); ex.In.Headers.ContainsKey("session_id").Should().BeFalse(); ex.In.Headers.ContainsKey("access_token").Should().BeFalse(); ex.In.Headers.ContainsKey("operation").Should().BeFalse("over HTTP the operation is derived from method and path"); ex.In.Headers.ContainsKey("X-Correlation-Id").Should().BeTrue("only reserved internal names are stripped"); } // ───────────────────────────────────────────────────────────────────────── // (3) cross-site form posts are refused, origin-less callers are not // ───────────────────────────────────────────────────────────────────────── [Theory] [InlineData("Origin", "https://evil.example")] [InlineData("Referer", "https://evil.example/phish.html")] [InlineData("Origin", "null")] public async Task LoginPost_FromForeignOrigin_Is403_AndSetsNoSession(string header, string value) { var req = new HttpRequestMessage(HttpMethod.Post, "/login") { Content = CredentialsForm() }; req.Headers.TryAddWithoutValidation(header, value); var resp = await Anonymous().SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Forbidden, "a browser form submitted from another site announces it and is refused before credentials are read"); resp.Headers.Contains("Set-Cookie").Should().BeFalse("no session may be planted by a cross-site login"); } [Fact] public async Task LoginPost_FromOwnOrigin_IsProcessed() { var req = new HttpRequestMessage(HttpMethod.Post, "/login") { Content = CredentialsForm() }; req.Headers.TryAddWithoutValidation("Origin", _fx.BaseUrl); var resp = await Anonymous().SendAsync(req); resp.StatusCode.Should().NotBe(HttpStatusCode.Forbidden, "the facade's own page posting to itself is the normal case"); resp.Headers.Contains("Set-Cookie").Should().BeTrue("a same-origin login still produces the session"); } [Fact] public async Task LoginPost_WithoutOriginOrReferer_IsProcessed() { var resp = await Anonymous().PostAsync("/login", CredentialsForm()); resp.StatusCode.Should().NotBe(HttpStatusCode.Forbidden, "the web console's BFF, the demo scripts and API clients post without a browser origin"); resp.Headers.Contains("Set-Cookie").Should().BeTrue(); } [Fact] public async Task ConsentPost_FromForeignOrigin_Is403_EvenWithASession() { var cookies = new CookieContainer(); using var browser = CreateBrowserClient(cookies); await LoginAsync(browser); var req = new HttpRequestMessage(HttpMethod.Post, "/consent") { Content = new FormUrlEncodedContent(new Dictionary { ["client_id"] = ProductionHttpFixture.TestConsentClientId, ["scopes"] = "openid", ["decision"] = "allow", }) }; req.Headers.TryAddWithoutValidation("Origin", "https://evil.example"); var resp = await browser.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Forbidden, "a cross-site form carrying the victim's cookie is exactly the CSRF the guard exists for"); } [Theory] [InlineData("https://op.example", "https://op.example/", null, true)] [InlineData("https://op.example:443", "https://op.example/", null, true)] [InlineData("https://OP.example", "https://op.example/", null, true)] [InlineData("https://evil.example", "https://op.example/", null, false)] [InlineData("https://op.example.evil.net", "https://op.example/", null, false)] [InlineData("null", "https://op.example/", null, false)] [InlineData("garbage", "https://op.example/", null, false)] [InlineData("https://internal-name:8443", "https://op.example/", "internal-name:8443", true)] [InlineData("https://internal-name", "https://op.example/", "internal-name:443", true)] [InlineData("https://evil.example", "https://op.example/", "internal-name:8443", false)] public void IsOwnOrigin_MatchesIssuerOrAddressedHost(string announced, string issuer, string? host, bool expected) { AntiForgeryProcessors.IsOwnOrigin(announced, new Uri(issuer), host).Should().Be(expected); } // ───────────────────────────────────────────────────────────────────────── // helpers // ───────────────────────────────────────────────────────────────────────── private static string? HeaderValue(HttpResponseMessage resp, string name) => resp.Headers.TryGetValues(name, out var v) ? string.Join(",", v) : resp.Content.Headers.TryGetValues(name, out var cv) ? string.Join(",", cv) : null; /// /// A fresh client per call: no cookie jar (so a login in one test can never lend its /// session to an "anonymous" request in another) and no redirect following (so a 302 to /// the client's redirect_uri is observed, not chased to a dead port). /// private HttpClient Anonymous() => new(new HttpClientHandler { UseCookies = false, AllowAutoRedirect = false }) { BaseAddress = new Uri(_fx.BaseUrl) }; // The management API serialises audit items in camelCase (the DTO attributes say snake_case, // the facade serialiser wins) — read the field by either name. private static string? Field(System.Text.Json.JsonElement item, string camel, string snake) => item.TryGetProperty(camel, out var c) && c.ValueKind == System.Text.Json.JsonValueKind.String ? c.GetString() : item.TryGetProperty(snake, out var s) && s.ValueKind == System.Text.Json.JsonValueKind.String ? s.GetString() : null; private static string? AgentOf(System.Text.Json.JsonElement item) => Field(item, "userAgent", "user_agent"); private static long NumberField(System.Text.Json.JsonElement item, string camel, string snake) => item.TryGetProperty(camel, out var c) && c.ValueKind == System.Text.Json.JsonValueKind.Number ? c.GetInt64() : item.TryGetProperty(snake, out var s) && s.ValueKind == System.Text.Json.JsonValueKind.Number ? s.GetInt64() : 0; /// /// The audit sink is fed by a WireTap and flushes asynchronously; poll the management /// audit query until the row appears (or give up after a few seconds). /// private async Task FindAuditRowAsync( string eventType, Func match) { for (var attempt = 0; attempt < 20; attempt++) { using var req = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/identity/audit?eventType={eventType}&count=100"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); var resp = await Anonymous().SendAsync(req); if (resp.IsSuccessStatusCode) { var doc = System.Text.Json.JsonDocument.Parse(await resp.Content.ReadAsStringAsync()); foreach (var item in doc.RootElement.GetProperty("items").EnumerateArray()) if (match(item)) return item.Clone(); } await Task.Delay(250); } return null; } private async Task DescribeAuditRowsAsync(string eventType) { using var req = new HttpRequestMessage(HttpMethod.Get, $"/api/v1/identity/audit?eventType={eventType}&count=5"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); var resp = await Anonymous().SendAsync(req); var body = await resp.Content.ReadAsStringAsync(); if (!resp.IsSuccessStatusCode) return $"{(int)resp.StatusCode}: {body}"; return body.Length > 1500 ? body[..1500] : body; } private static (string verifier, string challenge) Pkce() { var verifier = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); var challenge = Convert.ToBase64String(SHA256.HashData(Encoding.ASCII.GetBytes(verifier))) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } private static FormUrlEncodedContent CredentialsForm() => new(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, }); private HttpClient CreateBrowserClient(CookieContainer cookies) { var handler = new HttpClientHandler { CookieContainer = cookies, AllowAutoRedirect = false, UseCookies = true }; return new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; } private static async Task LoginAsync(HttpClient browser) { var resp = await browser.PostAsync("/login", CredentialsForm()); resp.Headers.Contains("Set-Cookie").Should().BeTrue("login must establish the session: {0}", await resp.Content.ReadAsStringAsync()); } private async Task SeedExplicitConsentClientAsync() { var clientId = $"e2e-form-consent-{Guid.NewGuid():N}"[..40]; var manager = _fx.ServiceProvider.GetRequiredService(); await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = clientId, ClientType = OpenIddictConstants.ClientTypes.Public, ConsentType = OpenIddictConstants.ConsentTypes.Explicit, DisplayName = clientId, RedirectUris = { new Uri(ProductionHttpFixture.TestRedirectUri) }, Permissions = { OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.ResponseTypes.Code, OpenIddictConstants.Permissions.Prefixes.Scope + "openid", OpenIddictConstants.Permissions.Scopes.Profile, } }); return clientId; } private Task AppObjectIdAsync(string clientId) => _fx.UseRedbAsync(async redb => (await redb.GetByUniqueAsync(p => p.ClientId, clientId))!.Id); private Task>> ConsentsOfAsync(long userId, long appId) => _fx.UseRedbAsync(async redb => await redb.Query() .WhereRedb(o => o.Key == userId) .Where(a => a.ApplicationObjectId == appId) .ToListAsync()); } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackGroupTests.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/FullStackGroupTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E tests for Group Management REST API. /// Complete path: HTTP request → Kestrel → bearer auth → GroupsController /// → direct-vm://identity-manage-groups → GroupManagementProcessor → GroupService /// → redb PROPS → PostgreSQL → response → HTTP. /// [Collection("ProductionHttp")] public class FullStackGroupTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; private readonly ITestOutputHelper _output; public FullStackGroupTests(ProductionHttpFixture fx, ITestOutputHelper output) { _fx = fx; _http = fx.Http; _output = output; } private HttpRequestMessage WithAuth(HttpRequestMessage request) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return request; } // ══════════════════════════════════════════════ // Auth guardrails // ══════════════════════════════════════════════ [Fact] public async Task Groups_WithoutBearer_Returns401() { var resp = await _http.GetAsync("/api/v1/identity/groups"); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); } [Fact] public async Task GroupMembers_WithoutBearer_Returns401() { var resp = await _http.GetAsync("/api/v1/identity/groups/1/members"); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); } // ══════════════════════════════════════════════ // Group CRUD — full lifecycle // ══════════════════════════════════════════════ [Fact] public async Task Groups_CreateReadUpdateDelete_FullCycle() { // CREATE var createResp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpOrg1", groupType = "organization", description = "E2E org" }); createResp.StatusCode.Should().Be(HttpStatusCode.OK, "create failed: {0}", await createResp.Content.ReadAsStringAsync()); var created = await ParseJson(createResp); var id = created.GetProperty("id").GetInt64(); id.Should().BeGreaterThan(0); created.GetProperty("name").GetString().Should().Be("HttpOrg1"); created.GetProperty("groupType").GetString().Should().Be("organization"); _output.WriteLine($"Created group {id}"); // READ var readResp = await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{id}"); readResp.StatusCode.Should().Be(HttpStatusCode.OK); var read = await ParseJson(readResp); read.GetProperty("id").GetInt64().Should().Be(id); read.GetProperty("description").GetString().Should().Be("E2E org"); // UPDATE var updateResp = await SendJson(HttpMethod.Put, $"/api/v1/identity/groups/{id}", new { name = "HttpOrg1Updated", description = "Updated desc" }); updateResp.StatusCode.Should().Be(HttpStatusCode.OK); // Verify update via re-read var reReadResp = await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{id}"); var reRead = await ParseJson(reReadResp); reRead.GetProperty("name").GetString().Should().Be("HttpOrg1Updated"); reRead.GetProperty("description").GetString().Should().Be("Updated desc"); // DELETE var deleteResp = await SendAuth(HttpMethod.Delete, $"/api/v1/identity/groups/{id}"); deleteResp.StatusCode.Should().Be(HttpStatusCode.OK); // Verify deleted — should return error var afterDelete = await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{id}"); var afterBody = await ParseJson(afterDelete); afterBody.TryGetProperty("error", out _).Should().BeTrue("deleted group should return error"); } [Fact] public async Task Groups_List_Returns200() { // Ensure at least one group exists await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpListGroup", groupType = "team" }); var resp = await SendAuth(HttpMethod.Get, "/api/v1/identity/groups"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.ValueKind.Should().Be(JsonValueKind.Array); json.GetArrayLength().Should().BeGreaterThan(0); } // ══════════════════════════════════════════════ // Tree operations — hierarchy E2E // ══════════════════════════════════════════════ [Fact] public async Task Groups_CreateChild_And_GetTree() { // Create parent org var parentResp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpTreeOrg", groupType = "organization" }); var parentId = (await ParseJson(parentResp)).GetProperty("id").GetInt64(); // Create child team under parent var childResp = await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{parentId}/children", new { name = "HttpTreeTeam", groupType = "team" }); childResp.StatusCode.Should().Be(HttpStatusCode.OK); var childId = (await ParseJson(childResp)).GetProperty("id").GetInt64(); childId.Should().BeGreaterThan(0); // GET tree var treeResp = await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{parentId}/tree"); treeResp.StatusCode.Should().Be(HttpStatusCode.OK); var tree = await ParseJson(treeResp); tree.GetProperty("id").GetInt64().Should().Be(parentId); tree.GetProperty("children").GetArrayLength().Should().BeGreaterThan(0); _output.WriteLine($"Tree root {parentId}, child {childId}"); } [Fact] public async Task Groups_Children_ReturnsDirectChildren() { var parentResp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpChildrenOrg", groupType = "organization" }); var parentId = (await ParseJson(parentResp)).GetProperty("id").GetInt64(); await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{parentId}/children", new { name = "HttpChild1", groupType = "team" }); await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{parentId}/children", new { name = "HttpChild2", groupType = "department" }); var childrenResp = await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{parentId}/children"); childrenResp.StatusCode.Should().Be(HttpStatusCode.OK); var children = await ParseJson(childrenResp); children.ValueKind.Should().Be(JsonValueKind.Array); children.GetArrayLength().Should().BeGreaterThanOrEqualTo(2); } [Fact] public async Task Groups_Path_ReturnsAncestors() { var orgResp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpPathOrg", groupType = "organization" }); var orgId = (await ParseJson(orgResp)).GetProperty("id").GetInt64(); var deptResp = await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{orgId}/children", new { name = "HttpPathDept", groupType = "department" }); var deptId = (await ParseJson(deptResp)).GetProperty("id").GetInt64(); var teamResp = await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{deptId}/children", new { name = "HttpPathTeam", groupType = "team" }); var teamId = (await ParseJson(teamResp)).GetProperty("id").GetInt64(); var pathResp = await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{teamId}/path"); pathResp.StatusCode.Should().Be(HttpStatusCode.OK); var path = await ParseJson(pathResp); path.ValueKind.Should().Be(JsonValueKind.Array); path.GetArrayLength().Should().BeGreaterThanOrEqualTo(2, "path should include ancestors"); _output.WriteLine($"Path for team {teamId}: {path.GetArrayLength()} ancestors"); } [Fact] public async Task Groups_Move_ChangesParent() { var org1Resp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpMoveOrg1", groupType = "organization" }); var org1Id = (await ParseJson(org1Resp)).GetProperty("id").GetInt64(); var org2Resp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpMoveOrg2", groupType = "organization" }); var org2Id = (await ParseJson(org2Resp)).GetProperty("id").GetInt64(); var teamResp = await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{org1Id}/children", new { name = "HttpMoveTeam", groupType = "team" }); var teamId = (await ParseJson(teamResp)).GetProperty("id").GetInt64(); // Move team from org1 to org2 var moveResp = await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{teamId}/move", new { newParentGroupId = org2Id }); moveResp.StatusCode.Should().Be(HttpStatusCode.OK); // Verify via children of org2 var children2 = await ParseJson(await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{org2Id}/children")); children2.GetArrayLength().Should().BeGreaterThan(0, "team should be under org2 after move"); } // ══════════════════════════════════════════════ // Membership — full lifecycle // ══════════════════════════════════════════════ [Fact] public async Task Members_AddListUpdateRemove_FullCycle() { // Create group var groupResp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpMemberGroup", groupType = "team" }); var groupId = (await ParseJson(groupResp)).GetProperty("id").GetInt64(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // ADD MEMBER var addResp = await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{groupId}/members", new { userId, role = "member" }); addResp.StatusCode.Should().Be(HttpStatusCode.OK, "add member failed: {0}", await addResp.Content.ReadAsStringAsync()); var addResult = await ParseJson(addResp); addResult.GetProperty("success").GetBoolean().Should().BeTrue(); // LIST MEMBERS var listResp = await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{groupId}/members"); listResp.StatusCode.Should().Be(HttpStatusCode.OK); var members = await ParseJson(listResp); members.ValueKind.Should().Be(JsonValueKind.Array); members.GetArrayLength().Should().BeGreaterThan(0); // UPDATE MEMBER ROLE var updateResp = await SendJson(HttpMethod.Put, $"/api/v1/identity/groups/{groupId}/members/{userId}", new { role = "admin" }); updateResp.StatusCode.Should().Be(HttpStatusCode.OK); // REMOVE MEMBER var removeResp = await SendAuth(HttpMethod.Delete, $"/api/v1/identity/groups/{groupId}/members/{userId}"); removeResp.StatusCode.Should().Be(HttpStatusCode.OK); // Verify removed var afterRemove = await ParseJson( await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{groupId}/members")); // Should be empty or not contain userId if (afterRemove.ValueKind == JsonValueKind.Array) { foreach (var m in afterRemove.EnumerateArray()) { if (m.TryGetProperty("UserId", out var uid) || m.TryGetProperty("userId", out uid)) uid.GetInt64().Should().NotBe(userId, "removed member should not appear"); } } _output.WriteLine($"Member lifecycle complete for group {groupId}"); } [Fact] public async Task UserGroups_ReturnsGroupsForUser() { var groupResp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpUserGroupsTeam", groupType = "team" }); var groupId = (await ParseJson(groupResp)).GetProperty("id").GetInt64(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{groupId}/members", new { userId, role = "viewer" }); var resp = await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/users/{userId}/groups"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var groups = await ParseJson(resp); groups.ValueKind.Should().Be(JsonValueKind.Array); groups.GetArrayLength().Should().BeGreaterThan(0); } [Fact] public async Task GroupWithNameOnly_UserGroupsAndReadsWork() { // No groupType, no description: redb stores no props rows for this group. var groupResp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpNameOnly-" + Guid.NewGuid().ToString("N")[..8] }); groupResp.StatusCode.Should().Be(HttpStatusCode.OK); var groupId = (await ParseJson(groupResp)).GetProperty("id").GetInt64(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); (await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{groupId}/members", new { userId })).StatusCode.Should().Be(HttpStatusCode.OK); var userGroupsResp = await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/users/{userId}/groups"); var userGroupsBody = await userGroupsResp.Content.ReadAsStringAsync(); userGroupsResp.StatusCode.Should().Be(HttpStatusCode.OK, "user-groups: {0}", userGroupsBody); var userGroups = JsonDocument.Parse(userGroupsBody).RootElement; userGroups.ValueKind.Should().Be(JsonValueKind.Array, "user-groups: {0}", userGroupsBody); userGroups.EnumerateArray().Should().Contain(g => g.GetProperty("groupId").GetInt64() == groupId); var read = await ParseJson(await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{groupId}")); read.TryGetProperty("error", out _).Should().BeFalse("get: {0}", read.ToString()); read.GetProperty("id").GetInt64().Should().Be(groupId); var tree = await ParseJson(await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{groupId}/tree")); tree.TryGetProperty("error", out _).Should().BeFalse("tree: {0}", tree.ToString()); (await SendJson(HttpMethod.Put, $"/api/v1/identity/groups/{groupId}", new { groupType = "team" })).StatusCode.Should().Be(HttpStatusCode.OK); var reRead = await ParseJson(await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{groupId}")); reRead.GetProperty("groupType").GetString().Should().Be("team"); } [Fact] public async Task IsMember_Check_ReturnsCorrectResult() { var groupResp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpIsMemberGroup", groupType = "team" }); var groupId = (await ParseJson(groupResp)).GetProperty("id").GetInt64(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // Not a member yet var check1 = await ParseJson( await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{groupId}/members/{userId}/check")); check1.GetProperty("isMember").GetBoolean().Should().BeFalse(); // Add member await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{groupId}/members", new { userId, role = "member" }); // Now is a member var check2 = await ParseJson( await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{groupId}/members/{userId}/check")); check2.GetProperty("isMember").GetBoolean().Should().BeTrue(); _output.WriteLine($"IsMember check passed for group {groupId}, user {userId}"); } // ══════════════════════════════════════════════ // Ancestor membership — RFC/RBAC correctness // ══════════════════════════════════════════════ [Fact] public async Task IsMember_ViaAncestor_InheritsMembership() { // Create hierarchy: org → dept → team var orgResp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpAncOrg", groupType = "organization" }); var orgId = (await ParseJson(orgResp)).GetProperty("id").GetInt64(); var deptResp = await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{orgId}/children", new { name = "HttpAncDept", groupType = "department" }); var deptId = (await ParseJson(deptResp)).GetProperty("id").GetInt64(); var teamResp = await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{deptId}/children", new { name = "HttpAncTeam", groupType = "team" }); var teamId = (await ParseJson(teamResp)).GetProperty("id").GetInt64(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // Add member to ORG level await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{orgId}/members", new { userId, role = "admin" }); // Should be member of team via ancestor traversal var check = await ParseJson( await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{teamId}/members/{userId}/check")); check.GetProperty("isMember").GetBoolean().Should().BeTrue( "member of ancestor org should be member of descendant team"); _output.WriteLine($"Ancestor membership: org {orgId} → dept {deptId} → team {teamId}"); } // ══════════════════════════════════════════════ // Cascade delete — subtree + memberships // ══════════════════════════════════════════════ [Fact] public async Task Delete_CascadesSubtreeAndMemberships() { var orgResp = await SendJson(HttpMethod.Post, "/api/v1/identity/groups", new { name = "HttpCascadeOrg", groupType = "organization" }); var orgId = (await ParseJson(orgResp)).GetProperty("id").GetInt64(); var teamResp = await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{orgId}/children", new { name = "HttpCascadeTeam", groupType = "team" }); var teamId = (await ParseJson(teamResp)).GetProperty("id").GetInt64(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await SendJson(HttpMethod.Post, $"/api/v1/identity/groups/{teamId}/members", new { userId, role = "member" }); // Delete org — should cascade delete team + memberships var deleteResp = await SendAuth(HttpMethod.Delete, $"/api/v1/identity/groups/{orgId}"); deleteResp.StatusCode.Should().Be(HttpStatusCode.OK); // Team should be gone var teamRead = await ParseJson( await SendAuth(HttpMethod.Get, $"/api/v1/identity/groups/{teamId}")); teamRead.TryGetProperty("error", out _).Should().BeTrue("child team should be deleted"); _output.WriteLine($"Cascade delete: org {orgId} → team {teamId} both removed"); } // ══════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════ private async Task SendAuth(HttpMethod method, string path) { var req = WithAuth(new HttpRequestMessage(method, path)); return await _http.SendAsync(req); } private async Task SendJson(HttpMethod method, string path, object body) { var req = WithAuth(new HttpRequestMessage(method, path) { Content = JsonContent.Create(body) }); return await _http.SendAsync(req); } private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackManagementTests.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/FullStackManagementTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E tests for the Management REST API. /// Complete path: HTTP request → Kestrel → bearer auth → controller dispatch /// → direct-vm:// → management processor → redb stores → PostgreSQL → response → HTTP. /// Uses PRODUCTION OpenIddict (real stores, no degraded mode). /// [Collection("ProductionHttp")] public class FullStackManagementTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public FullStackManagementTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } private HttpRequestMessage WithAuth(HttpRequestMessage request) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return request; } // ══════════════════════════════════════════════ // Applications CRUD // ══════════════════════════════════════════════ [Fact] public async Task Applications_CreateReadDelete_ViaHttp() { var clientId = $"e2e-crud-{Guid.NewGuid():N}"; // Create var createReq = WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/applications") { Content = JsonContent.Create(new { clientId, clientSecret = "crud-test-secret", displayName = "E2E CRUD App" }) }); var createResp = await _http.SendAsync(createReq); createResp.StatusCode.Should().Be(HttpStatusCode.OK, "create failed: {0}", await createResp.Content.ReadAsStringAsync()); var created = await ParseJson(createResp); // List — should contain the created app var listReq = WithAuth(new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications")); var listResp = await _http.SendAsync(listReq); listResp.StatusCode.Should().Be(HttpStatusCode.OK); // Delete var id = GetId(created); id.Should().NotBeNullOrEmpty("created app should have an id"); var deleteReq = WithAuth(new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/identity/applications/{id}")); var deleteResp = await _http.SendAsync(deleteReq); deleteResp.StatusCode.Should().Be(HttpStatusCode.OK); } // ══════════════════════════════════════════════ // Users CRUD // ══════════════════════════════════════════════ [Fact] public async Task Users_CreateAndList_ViaHttp() { var login = $"e2e-user-{Guid.NewGuid():N}"; // Create var createReq = WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/users") { Content = JsonContent.Create(new { login, password = "Str0ng!Passw0rd" }) }); var createResp = await _http.SendAsync(createReq); createResp.StatusCode.Should().Be(HttpStatusCode.OK, "create user failed: {0}", await createResp.Content.ReadAsStringAsync()); // List — should return 200 var listReq = WithAuth(new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/users")); var listResp = await _http.SendAsync(listReq); listResp.StatusCode.Should().Be(HttpStatusCode.OK); } // ══════════════════════════════════════════════ // Scopes CRUD // ══════════════════════════════════════════════ [Fact] public async Task Scopes_CreateAndList_ViaHttp() { var scopeName = $"e2e-scope-{Guid.NewGuid():N}"; // Create var createReq = WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/scopes") { Content = JsonContent.Create(new { name = scopeName, displayName = "E2E Test Scope" }) }); var createResp = await _http.SendAsync(createReq); createResp.StatusCode.Should().Be(HttpStatusCode.OK, "create scope failed: {0}", await createResp.Content.ReadAsStringAsync()); // List var listReq = WithAuth(new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/scopes")); var listResp = await _http.SendAsync(listReq); listResp.StatusCode.Should().Be(HttpStatusCode.OK); } // ══════════════════════════════════════════════ // Tokens // ══════════════════════════════════════════════ [Fact] public async Task Tokens_ListAndPrune_ViaHttp() { // List var listReq = WithAuth(new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/tokens")); var listResp = await _http.SendAsync(listReq); listResp.StatusCode.Should().Be(HttpStatusCode.OK); // Prune var pruneReq = WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/tokens/prune")); var pruneResp = await _http.SendAsync(pruneReq); pruneResp.StatusCode.Should().Be(HttpStatusCode.OK); } // ══════════════════════════════════════════════ // Bearer token enforcement // ══════════════════════════════════════════════ [Fact] public async Task ManagementApi_NoBearerToken_Returns401() { var resp = await _http.GetAsync("/api/v1/identity/applications"); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); } [Fact] public async Task ManagementApi_InvalidBearerToken_Returns401() { var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "garbage-invalid-token"); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); } // ══════════════════════════════════════════════ // 404 — Not Found (non-existent resources) // ══════════════════════════════════════════════ [Fact] public async Task Applications_GetNonExistent_ReturnsNotFound() { var resp = await SendAuth(HttpMethod.Get, "/api/v1/identity/applications/999999"); resp.StatusCode.Should().Be(HttpStatusCode.NotFound); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("not_found"); } [Fact] public async Task Users_GetNonExistent_ReturnsNotFound() { var resp = await SendAuth(HttpMethod.Get, "/api/v1/identity/users/999999"); resp.StatusCode.Should().Be(HttpStatusCode.NotFound); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("not_found"); } [Fact] public async Task Scopes_GetNonExistent_ReturnsNotFound() { var resp = await SendAuth(HttpMethod.Get, "/api/v1/identity/scopes/999999"); resp.StatusCode.Should().Be(HttpStatusCode.NotFound); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("not_found"); } [Fact] public async Task Groups_GetNonExistent_ReturnsNotFound() { var resp = await SendAuth(HttpMethod.Get, "/api/v1/identity/groups/999999"); resp.StatusCode.Should().Be(HttpStatusCode.NotFound); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("not_found"); } // ══════════════════════════════════════════════ // Duplicates // ══════════════════════════════════════════════ [Fact] public async Task Applications_CreateDuplicate_ReturnsDuplicateError() { var clientId = $"e2e-dup-{Guid.NewGuid():N}"; // First create await SendAuth(HttpMethod.Post, "/api/v1/identity/applications", new { clientId, displayName = "Dup Test" }); // Second create with same clientId var resp = await SendAuth(HttpMethod.Post, "/api/v1/identity/applications", new { clientId, displayName = "Dup Test 2" }); resp.StatusCode.Should().Be(HttpStatusCode.Conflict); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("duplicate"); } [Fact] public async Task Users_CreateDuplicate_ReturnsDuplicateError() { var login = $"e2e-dup-{Guid.NewGuid():N}"; // First create await SendAuth(HttpMethod.Post, "/api/v1/identity/users", new { login, password = "Str0ng!Passw0rd" }); // Second create with same login var resp = await SendAuth(HttpMethod.Post, "/api/v1/identity/users", new { login, password = "Str0ng!Passw0rd2" }); resp.StatusCode.Should().Be(HttpStatusCode.Conflict); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("duplicate"); } [Fact] public async Task Scopes_CreateDuplicate_ReturnsDuplicateError() { var name = $"e2e-dup-{Guid.NewGuid():N}"; // First create await SendAuth(HttpMethod.Post, "/api/v1/identity/scopes", new { name, displayName = "Dup Test" }); // Second create with same name var resp = await SendAuth(HttpMethod.Post, "/api/v1/identity/scopes", new { name, displayName = "Dup Test 2" }); resp.StatusCode.Should().Be(HttpStatusCode.Conflict); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("duplicate"); } // ══════════════════════════════════════════════ // Validation errors // ══════════════════════════════════════════════ [Fact] public async Task Applications_CreateMissingClientId_ReturnsValidationError() { var resp = await SendAuth(HttpMethod.Post, "/api/v1/identity/applications", new { displayName = "No ClientId" }); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("validation_error"); } [Fact] public async Task Users_CreateEmptyLogin_ReturnsValidationError() { var resp = await SendAuth(HttpMethod.Post, "/api/v1/identity/users", new { login = "", password = "Str0ng!Passw0rd" }); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("validation_error"); } [Fact] public async Task Users_CreateEmptyPassword_ReturnsValidationError() { var resp = await SendAuth(HttpMethod.Post, "/api/v1/identity/users", new { login = "empty-pass-user", password = "" }); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("validation_error"); } [Fact] public async Task Scopes_CreateMissingName_ReturnsValidationError() { var resp = await SendAuth(HttpMethod.Post, "/api/v1/identity/scopes", new { displayName = "No Name" }); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("validation_error"); } [Fact] public async Task Tokens_RevokeNonExistent_ReturnsNotFound() { var resp = await SendAuth(HttpMethod.Delete, "/api/v1/identity/tokens/999999"); resp.StatusCode.Should().Be(HttpStatusCode.NotFound); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("not_found"); } // ══════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════ private async Task SendAuth(HttpMethod method, string url, object? body = null) { var req = new HttpRequestMessage(method, url); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); if (body is not null) req.Content = JsonContent.Create(body); return await _http.SendAsync(req); } private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } private static string? GetId(JsonElement element) { if (element.TryGetProperty("id", out var id)) return id.ToString(); if (element.TryGetProperty("Id", out id)) return id.ToString(); return null; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackMfaEmailSmtpTests.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/FullStackMfaEmailSmtpTests.cs ---- using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using AwesomeAssertions; using MailKit.Net.Imap; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Configuration; using redb.Identity.Core.Services; using redb.Route.Components; using redb.Route.Core; using redb.Route.Mail; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.FullStack; /// /// The one-time code of e-mail MFA over a real SMTP server: on top of /// delivers the message to the /// GreenMail container, and the code is in the HTML and the text part. The enrollment itself over HTTP, with the /// in-memory e-mail channel of the test host, is covered by . /// [Trait("Category", "Integration")] [Trait("Requires", "Greenmail")] public sealed class FullStackMfaEmailSmtpTests { private const string GreenmailHost = "127.0.0.1"; private const int GreenmailSmtpPort = 3025; private const int GreenmailImapPort = 3143; private const string ApiBase = "http://127.0.0.1:8080"; private readonly ITestOutputHelper _output; public FullStackMfaEmailSmtpTests(ITestOutputHelper output) => _output = output; [Fact] public async Task The_mfa_code_lands_in_the_greenmail_inbox() { SkipIfGreenmailUnavailable(); var recipientUser = $"e2e-mfa-{Guid.NewGuid():N}"; var recipient = $"{recipientUser}@localhost"; await ProvisionGreenmailUserAsync(recipientUser, "secret"); var sc = new ServiceCollection(); sc.AddSingleton(); await using var sp = sc.BuildServiceProvider(); await using var ctx = new RouteContext(sp); ctx.AddComponent(new SmtpComponent()); ctx.AddRoutes(r => { r.From(IdentityEndpoints.EmailSend) .RouteId(IdentityEndpoints.RouteIds.EmailSend) .To(Smtp.Send(GreenmailHost) .Port(GreenmailSmtpPort) .Security("None") .From("noreply@redb.local") .ContentType("text/html") .AlternativeBody()); }); await ctx.Start(); var options = Options.Create(new RedbIdentityOptions { Smtp = new SmtpOptions { Enabled = true, Host = GreenmailHost, Port = GreenmailSmtpPort, Security = "None", FromAddress = "noreply@redb.local", } }); using var mail = new SmtpEmailNotificationChannel(ctx, new InlineEmailTemplateRegistry(), options, NullLoggerFactory.Instance); var channel = new EmailMfaDeliveryChannel(mail, TimeSpan.FromMinutes(5)); await channel.SendCodeAsync(recipient, "482913"); var (subject, htmlBody, textBody) = await ReadFirstMessageAsync(recipientUser, "secret"); _output.WriteLine($"Subject: {subject}"); subject.Should().Be("Your verification code"); htmlBody.Should().Contain("482913"); textBody.Should().Contain("482913").And.Contain("5 minutes"); } // ── Helpers (verbatim from FullStackPasswordRecoverySmtpTests; kept inline so each // integration test file is self-contained and can be removed independently) ── private static void SkipIfGreenmailUnavailable() { var reachable = false; try { using var probe = new TcpClient(); var task = probe.ConnectAsync(GreenmailHost, GreenmailSmtpPort); reachable = task.Wait(TimeSpan.FromMilliseconds(500)) && probe.Connected; } catch { /* fall through — reachable stays false */ } Assert.True(reachable, $"Greenmail not reachable on {GreenmailHost}:{GreenmailSmtpPort}. " + "Start with: docker compose -f redb.Route/docker-compose.tests.yml up greenmail -d, " + "or filter this test out via `--filter Category!=Integration`."); } private static async Task ProvisionGreenmailUserAsync(string login, string password) { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(3) }; var json = $"{{\"email\":\"{login}@localhost\",\"login\":\"{login}\",\"password\":\"{password}\"}}"; using var content = new StringContent(json, Encoding.UTF8, "application/json"); try { using var _ = await http.PostAsync($"{ApiBase}/api/user", content); } catch { /* greenmail REST is best-effort here — SMTP listener creates the account on delivery anyway. */ } } private static async Task<(string? Subject, string? HtmlBody, string? TextBody)> ReadFirstMessageAsync( string login, string password) { Exception? lastError = null; for (var attempt = 0; attempt < 15; attempt++) { try { using var imap = new ImapClient(); await imap.ConnectAsync(GreenmailHost, GreenmailImapPort, MailKit.Security.SecureSocketOptions.None); await imap.AuthenticateAsync(login, password); var inbox = imap.Inbox; await inbox.OpenAsync(MailKit.FolderAccess.ReadOnly); if (inbox.Count > 0) { var msg = await inbox.GetMessageAsync(0); await imap.DisconnectAsync(true); return (msg.Subject, msg.HtmlBody, msg.TextBody); } await imap.DisconnectAsync(true); } catch (Exception ex) { lastError = ex; } await Task.Delay(200); } throw new Xunit.Sdk.XunitException( $"No message arrived in {login}@localhost INBOX within 3 s. Last error: {lastError?.Message}"); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackMfaHangDiagnosticTests.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/FullStackMfaHangDiagnosticTests.cs ---- using System.Net; using System.Net.Http; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using OtpNet; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.FullStack; /// /// Diagnostic-only: reproduce the sequential-test hang in a single method so we can /// inspect server logs without fighting the xUnit scheduler. Does NOT assert flow /// correctness — its purpose is to expose the hang/not-hang boundary. /// [Collection("ProductionHttp")] public class FullStackMfaHangDiagnosticTests { private readonly ProductionHttpFixture _fx; private readonly ITestOutputHelper _out; /// /// These tests detect a HANG — a request that never completes — not latency. Three sequential /// Argon2id logins take ~7 s on this bench in isolation, so the former 10 s budget left no room /// for the provider suites the owner runs side by side (a PG run tripped it at exactly 10 s while /// the MSSQL suite was loading the same machine). A real hang never completes and still fails. /// private static readonly TimeSpan HangBudget = TimeSpan.FromSeconds(60); public FullStackMfaHangDiagnosticTests(ProductionHttpFixture fx, ITestOutputHelper output) { _fx = fx; _out = output; } private HttpClient NewClient() { var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = new CookieContainer(), UseCookies = true }; return new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; } [Fact] public async Task TwoSequentialLogins_ShouldNotHang() { using var cts = new CancellationTokenSource(HangBudget); _out.WriteLine("=== first POST /login ==="); using (var c1 = NewClient()) { var r1 = await c1.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = "nonexistent-user-1", ["password"] = "wrong" }), cts.Token); _out.WriteLine($"first status={r1.StatusCode}"); } _out.WriteLine("=== second POST /login ==="); using (var c2 = NewClient()) { var r2 = await c2.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = "nonexistent-user-2", ["password"] = "wrong" }), cts.Token); _out.WriteLine($"second status={r2.StatusCode}"); } _out.WriteLine("=== third POST /login ==="); using (var c3 = NewClient()) { var r3 = await c3.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = "nonexistent-user-3", ["password"] = "wrong" }), cts.Token); _out.WriteLine($"third status={r3.StatusCode}"); } } [Fact] public async Task TwoSequentialMfaPosts_ShouldNotHang() { using var cts = new CancellationTokenSource(HangBudget); _out.WriteLine("=== first POST /mfa ==="); using (var c1 = NewClient()) { var r1 = await c1.PostAsync("/mfa", new FormUrlEncodedContent(new Dictionary { ["code"] = "000000" }), cts.Token); _out.WriteLine($"first status={r1.StatusCode}"); } _out.WriteLine("=== second POST /mfa ==="); using (var c2 = NewClient()) { var r2 = await c2.PostAsync("/mfa", new FormUrlEncodedContent(new Dictionary { ["code"] = "000000" }), cts.Token); _out.WriteLine($"second status={r2.StatusCode}"); } } /// /// Reproduces the suspected shape of the sequential-test hang: two consecutive /// (seed MFA user → POST /login → POST /mfa) flows in ONE test, each with its /// own cookie jar. /// [Fact] public async Task TwoFullMfaFlows_InOneTest_ShouldNotHang() { using var cts = new CancellationTokenSource(HangBudget); async Task RunOne(string label) { _out.WriteLine($"=== flow {label}: seeding user ==="); var (login, password, secret) = await SeedMfaUserAsync(); using var client = NewClient(); _out.WriteLine($"=== flow {label}: POST /login ==="); var r1 = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = login, ["password"] = password }), cts.Token); _out.WriteLine($"flow {label}: login={r1.StatusCode}"); var code = GenerateValidTotp(secret); _out.WriteLine($"=== flow {label}: POST /mfa ==="); var r2 = await client.PostAsync("/mfa", new FormUrlEncodedContent(new Dictionary { ["code"] = code }), cts.Token); _out.WriteLine($"flow {label}: verify={r2.StatusCode}"); } await RunOne("A"); await RunOne("B"); } /// /// Variant: only POST /login (skip /mfa). If this passes but the full flow hangs, /// the culprit is the verify step itself (tx / LockForUpdate / SessionService.CreateAsync). /// [Fact] public async Task TwoLoginsWithMfaSeed_NoVerify_ShouldNotHang() { using var cts = new CancellationTokenSource(HangBudget); async Task RunOne(string label) { var (login, password, _) = await SeedMfaUserAsync(); using var client = NewClient(); _out.WriteLine($"=== flow {label}: POST /login ==="); var r1 = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = login, ["password"] = password }), cts.Token); _out.WriteLine($"flow {label}: login={r1.StatusCode}"); } await RunOne("A"); await RunOne("B"); } // ── helpers (copied minimal subset from FullStackMfaTests) ── private async Task<(string login, string password, string secret)> SeedMfaUserAsync() { var login = $"diag-{Guid.NewGuid():N}".Substring(0, 20); var password = "Diag@Test123!"; var secret = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(20)); var coreUser = await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = login, Password = password, Name = login, Email = $"{login}@example.com", Phone = "+1999000111", Enabled = true }); var protector = _fx.ServiceProvider.GetRequiredService(); var mfaObj = new RedbObject(new MfaProps { Enabled = true, DefaultMethod = "totp", TotpSecret = protector.Protect(secret), TotpConfirmed = true }); mfaObj.name = login; mfaObj.key = coreUser.Id; await _fx.Redb.SaveAsync(mfaObj); return (login, password, secret); } private static string GenerateValidTotp(string secret) { var totp = new Totp(Base32Encoding.ToBytes(secret), step: 30, totpSize: 6); return totp.ComputeTotp(); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackMfaTests.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/FullStackMfaTests.cs ---- using System.Net; using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using OtpNet; using redb.Core; 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.FullStack; /// /// Full-stack E2E tests for the interactive MFA browser flow: /// login (with MFA-enabled user) → 302 to /mfa → POST verify code → session cookie set. /// Covers TOTP success, invalid code re-render, and recovery code usage. /// Each test uses a freshly seeded MFA-enabled user so the shared /// stays MFA-free for the other browser flow tests. /// [Collection("ProductionHttp")] public class FullStackMfaTests { private readonly ProductionHttpFixture _fx; public FullStackMfaTests(ProductionHttpFixture fx) { _fx = fx; } // ══════════════════════════════════════════════════════════════════ // Login → MFA challenge redirect // ══════════════════════════════════════════════════════════════════ [Fact] public async Task Login_WithMfaEnabledUser_RedirectsToMfaPage() { var (login, password, _) = await SeedMfaUserAsync(); var cookies = new CookieContainer(); using var client = CreateBrowserClient(cookies, allowRedirect: false); var resp = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = login, ["password"] = password })); resp.StatusCode.Should().Be(HttpStatusCode.Redirect, "MFA-enabled login must redirect to /mfa"); var location = resp.Headers.Location?.ToString() ?? ""; location.Should().StartWith("/mfa"); // B3 §4: mfa_state is NO LONGER echoed into the URL — transported via HttpOnly cookie. location.Should().NotContain("mfa_state="); // B9 / BUG-9: mfa_methods is NO LONGER echoed into the URL — the MFA page derives // the methods server-side from the encrypted state. location.Should().NotContain("mfa_methods="); // MFA challenge MUST NOT set the session cookie yet — full auth requires the second factor. // (An MFA-state cookie IS set, but it is not a session.) HasSessionCookie(cookies).Should().BeFalse( "no session cookie may be issued before MFA verification succeeds"); HasMfaStateCookie(cookies).Should().BeTrue( "MFA challenge must issue the HttpOnly mfa-state cookie (B3 §4)"); } // ══════════════════════════════════════════════════════════════════ // POST /mfa with valid TOTP → session cookie // ══════════════════════════════════════════════════════════════════ [Fact] public async Task Mfa_Verify_WithValidTotpCode_SetsSessionCookie() { var (login, password, secretBase32) = await SeedMfaUserAsync(); var cookies = new CookieContainer(); using var client = CreateBrowserClient(cookies, allowRedirect: false); // Step 1 — login → 302 /mfa, mfa-state cookie set var loginResp = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = login, ["password"] = password })); HasMfaStateCookie(cookies).Should().BeTrue(); // Step 2 — POST /mfa with valid TOTP code (mfa-state cookie sent automatically) var code = GenerateValidTotp(secretBase32); var verifyResp = await client.PostAsync("/mfa", new FormUrlEncodedContent(new Dictionary { ["code"] = code })); // Session cookie MUST be set on successful verification HasSessionCookie(cookies).Should().BeTrue( "successful MFA verification must issue the session cookie"); } // ══════════════════════════════════════════════════════════════════ // POST /mfa with invalid code → form re-render, no cookie // ══════════════════════════════════════════════════════════════════ [Fact] public async Task Mfa_Verify_WithInvalidTotpCode_DoesNotSetCookie() { var (login, password, _) = await SeedMfaUserAsync(); var cookies = new CookieContainer(); using var client = CreateBrowserClient(cookies, allowRedirect: false); var loginResp = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = login, ["password"] = password })); HasMfaStateCookie(cookies).Should().BeTrue(); var verifyResp = await client.PostAsync("/mfa", new FormUrlEncodedContent(new Dictionary { ["code"] = "000000" })); HasSessionCookie(cookies).Should().BeFalse( "invalid MFA code must NOT issue a session cookie"); } // ══════════════════════════════════════════════════════════════════ // POST /mfa/recovery with valid recovery code → session cookie // ══════════════════════════════════════════════════════════════════ [Fact] public async Task MfaRecovery_WithValidCode_SetsSessionCookie() { var (login, password, _, plainRecoveryCode) = await SeedMfaUserWithRecoveryAsync(); var cookies = new CookieContainer(); using var client = CreateBrowserClient(cookies, allowRedirect: false); var loginResp = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = login, ["password"] = password })); HasMfaStateCookie(cookies).Should().BeTrue(); var resp = await client.PostAsync("/mfa/recovery", new FormUrlEncodedContent(new Dictionary { ["recovery_code"] = plainRecoveryCode })); HasSessionCookie(cookies).Should().BeTrue( "valid recovery code must issue the session cookie"); } // ══════════════════════════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════════════════════════ private HttpClient CreateBrowserClient(CookieContainer? cookies = null, bool allowRedirect = true) { cookies ??= new CookieContainer(); var handler = new HttpClientHandler { AllowAutoRedirect = allowRedirect, CookieContainer = cookies, UseCookies = true }; return new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; } private bool HasSessionCookie(CookieContainer cookies) { foreach (System.Net.Cookie c in cookies.GetCookies(new Uri(_fx.BaseUrl))) { // Bare or __Host- prefixed session cookie if (c.Name.EndsWith("redb.identity.session", StringComparison.Ordinal)) return true; } return false; } private bool HasMfaStateCookie(CookieContainer cookies) { foreach (System.Net.Cookie c in cookies.GetCookies(new Uri(_fx.BaseUrl))) { if (c.Name.EndsWith("redb.identity.mfa", StringComparison.Ordinal) && !string.IsNullOrEmpty(c.Value)) return true; } return false; } private static string? ExtractQueryParam(string url, string param) { var idx = url.IndexOf('?'); if (idx < 0) return null; var query = url[(idx + 1)..]; foreach (var pair in query.Split('&')) { var kv = pair.Split('=', 2); if (kv.Length == 2 && kv[0] == param) return Uri.UnescapeDataString(kv[1]); } return null; } private static string GenerateValidTotp(string base32Secret) { var key = Base32Encoding.ToBytes(base32Secret); var totp = new Totp(key, step: 30, totpSize: 6); return totp.ComputeTotp(); } /// /// Seeds (or reuses) a dedicated MFA-enabled test user with a confirmed TOTP secret. /// Each test gets its own login (so failure counters / lockouts don't leak across tests). /// Returns (login, password, base32 secret). /// private async Task<(string Login, string Password, string SecretBase32)> SeedMfaUserAsync() { var login = $"mfa-e2e-{Guid.NewGuid():N}".Substring(0, 24); var password = "Mfa@E2E#Test123!"; var secretBase32 = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(20)); await CreateUserAndMfaPropsAsync(login, password, secretBase32, recoveryHashes: null); return (login, password, secretBase32); } /// Seeds an MFA-enabled user plus a single recovery code; returns the plaintext code too. private async Task<(string Login, string Password, string SecretBase32, string RecoveryCode)> SeedMfaUserWithRecoveryAsync() { var login = $"mfa-rec-{Guid.NewGuid():N}".Substring(0, 24); var password = "Mfa@E2E#Test123!"; var secretBase32 = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(20)); var plainRecovery = $"REC-{Guid.NewGuid():N}".Substring(0, 16).ToUpperInvariant(); var hash = HashRecoveryCode(plainRecovery); await CreateUserAndMfaPropsAsync(login, password, secretBase32, new List { hash }); return (login, password, secretBase32, plainRecovery); } private async Task CreateUserAndMfaPropsAsync( string login, string password, string secretBase32, List? recoveryHashes) { // 1. Core user via UserProvider var coreUser = await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = login, Password = password, Name = login, Email = $"{login}@example.com", Phone = "+1999000111", Enabled = true }); // 2. MfaProps with confirmed TOTP — uses the SAME DataProtection key ring as the running server // so the encrypted secret can be decrypted by the server's MfaSecretProtector. var protector = _fx.ServiceProvider.GetRequiredService(); var mfaObj = new RedbObject(new MfaProps { Enabled = true, DefaultMethod = "totp", TotpSecret = protector.Protect(secretBase32), TotpConfirmed = true, RecoveryCodes = recoveryHashes }); mfaObj.name = login; mfaObj.key = coreUser.Id; await _fx.Redb.SaveAsync(mfaObj); } /// /// Hashes a recovery code using the same algorithm as MfaService.HashCode: /// strip dashes, uppercase, SHA-256, hex (lowercase). /// private static string HashRecoveryCode(string code) { var normalized = code.Replace("-", "", StringComparison.Ordinal).ToUpperInvariant(); var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(normalized)); return Convert.ToHexString(hash).ToLowerInvariant(); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackPasswordFlowTests.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/FullStackPasswordFlowTests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E tests for the Resource Owner Password Credentials (ROPC) flow via HTTP. /// Path: HTTP → Kestrel → HTTP facade → direct-vm:// → OpenIddict → redb stores → PostgreSQL. /// [Collection("ProductionHttp")] public class FullStackPasswordFlowTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public FullStackPasswordFlowTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } // ══════════════════════════════════════════════ // Happy path — password grant → tokens // ══════════════════════════════════════════════ [Fact] public async Task PasswordGrant_ValidCredentials_ReturnsTokens() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid profile email" }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.OK, "password grant failed: {0}", await resp.Content.ReadAsStringAsync()); var json = await ParseJson(resp); json.TryGetProperty("access_token", out var at).Should().BeTrue(); at.GetString()!.Split('.').Should().HaveCount(3, "access_token should be a JWT"); json.GetProperty("token_type").GetString().Should().Be("Bearer"); } [Fact] public async Task PasswordGrant_WithOfflineAccess_ReturnsRefreshToken() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid offline_access" }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.OK, "password grant failed: {0}", await resp.Content.ReadAsStringAsync()); var json = await ParseJson(resp); json.TryGetProperty("access_token", out _).Should().BeTrue(); json.TryGetProperty("refresh_token", out _).Should().BeTrue( "offline_access scope should yield a refresh_token"); } // ══════════════════════════════════════════════ // Error paths // ══════════════════════════════════════════════ [Fact] public async Task PasswordGrant_WrongPassword_ReturnsError() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = "completely-wrong-password", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid" }); var resp = await _http.PostAsync("/connect/token", content); resp.IsSuccessStatusCode.Should().BeFalse(); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("access_denied"); } [Fact] public async Task PasswordGrant_NonExistentUser_ReturnsError() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = "nonexistent-user-12345", ["password"] = "SomePassword123!", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid" }); var resp = await _http.PostAsync("/connect/token", content); resp.IsSuccessStatusCode.Should().BeFalse(); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("access_denied"); } [Fact] public async Task PasswordGrant_MissingUsername_ReturnsError() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["password"] = "SomePassword123!", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid" }); var resp = await _http.PostAsync("/connect/token", content); resp.IsSuccessStatusCode.Should().BeFalse(); var json = await ParseJson(resp); json.TryGetProperty("error", out _).Should().BeTrue(); } [Fact] public async Task PasswordGrant_ClientWithoutPermission_ReturnsError() { // Management client has no password grant permission var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["client_id"] = ProductionHttpFixture.TestMgmtClientId, ["client_secret"] = ProductionHttpFixture.TestMgmtSecret, ["scope"] = "openid" }); var resp = await _http.PostAsync("/connect/token", content); resp.IsSuccessStatusCode.Should().BeFalse(); var json = await ParseJson(resp); json.TryGetProperty("error", out _).Should().BeTrue(); } // ══════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════ private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackPasswordRecoverySmtpTests.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/FullStackPasswordRecoverySmtpTests.cs ---- using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using AwesomeAssertions; using MailKit.Net.Imap; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Configuration; using redb.Identity.Core.Services; using redb.Route.Components; using redb.Route.Core; using redb.Route.Mail; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.FullStack; /// /// N-4 (Session C): SMTP integration test for . /// Drives the channel end-to-end through the real redb.Route.Mail SMTP producer against /// the GreenMail container shipped in redb.Route/docker-compose.tests.yml /// (SMTP 127.0.0.1:3025, IMAP 127.0.0.1:3143). Verifies that: /// /// the direct-vm://identity-email-send route + Smtp.Send(...) DSL wire correctly; /// the channel populates redbMail.To/Subject/From/ContentType/TextBody headers /// such that SmtpProducer.BuildMimeMessage sends a proper multipart message; /// the rendered password-reset template lands in the recipient mailbox with the /// reset link substituted from the supplied variables. /// /// /// The test is gated on greenmail port reachability — when greenmail is not running the test /// is skipped (not failed) so local CI runs without the container still pass. /// /// [Trait("Category", "Integration")] [Trait("Requires", "Greenmail")] public sealed class FullStackPasswordRecoverySmtpTests { private const string GreenmailHost = "127.0.0.1"; private const int GreenmailSmtpPort = 3025; private const int GreenmailImapPort = 3143; private const string ApiBase = "http://127.0.0.1:8080"; private readonly ITestOutputHelper _output; public FullStackPasswordRecoverySmtpTests(ITestOutputHelper output) => _output = output; [Fact] public async Task SmtpEmailNotificationChannel_PasswordResetTemplate_LandsInGreenmailInbox() { SkipIfGreenmailUnavailable(); // Each run uses a unique recipient so we don't depend on inbox cleanup. Greenmail // creates the account on first delivery when -Dgreenmail.setup.test.all is set. var recipientUser = $"e2e-recovery-{Guid.NewGuid():N}"; var recipient = $"{recipientUser}@localhost"; await ProvisionGreenmailUserAsync(recipientUser, "secret"); // direct-vm:// endpoints need a SharedVmRegistry singleton in the route // context's service provider — production wires it in AddRedbRoute(); for the // standalone test we register it manually. var sc = new ServiceCollection(); sc.AddSingleton(); await using var sp = sc.BuildServiceProvider(); await using var ctx = new RouteContext(sp); ctx.AddComponent(new SmtpComponent()); ctx.AddRoutes(r => { // 1:1 mirror of IdentityCoreRouteBuilder's EmailSend route. Kept inline so this // test does not pull in the whole IdentityCoreRouteBuilder graph (OpenIddict, // EF, etc.) — the unit under test is the channel + route wiring, not the full // identity host. r.From(IdentityEndpoints.EmailSend) .RouteId(IdentityEndpoints.RouteIds.EmailSend) .To(Smtp.Send(GreenmailHost) .Port(GreenmailSmtpPort) .Security("None") .From("noreply@redb.local") .ContentType("text/html") .AlternativeBody()); }); await ctx.Start(); var options = Options.Create(new RedbIdentityOptions { Smtp = new SmtpOptions { Enabled = true, Host = GreenmailHost, Port = GreenmailSmtpPort, Security = "None", FromAddress = "noreply@redb.local", } }); var registry = new InlineEmailTemplateRegistry(); using var channel = new SmtpEmailNotificationChannel(ctx, registry, options, NullLoggerFactory.Instance); var resetToken = Guid.NewGuid().ToString("N"); var resetLink = $"https://app.redb.local/reset?jti=test-jti&token={resetToken}"; var vars = new Dictionary(StringComparer.Ordinal) { ["userName"] = recipient, ["resetLink"] = resetLink, ["ttlMinutes"] = "30", }; await channel.SendTemplateAsync(recipient, IdentityEmailTemplates.PasswordReset, vars); // Greenmail is in-process for the SMTP listener but the delivery + indexing is // async; a small grace window prevents a flaky read of an empty INBOX. var (subject, htmlBody, textBody) = await ReadFirstMessageAsync(recipientUser, "secret"); _output.WriteLine($"Subject: {subject}"); _output.WriteLine($"HTML body length: {htmlBody?.Length ?? 0}"); subject.Should().NotBeNullOrWhiteSpace("the channel must populate redbMail.Subject from the rendered template"); htmlBody.Should().NotBeNull("the channel sets ContentType=text/html so the body is rendered as HTML alternative"); htmlBody!.Should().Contain(resetToken, "the rendered HTML must embed the {resetLink} substitution"); // The default registry ships a plain-text alternative; assert it survived the round-trip. textBody.Should().NotBeNullOrWhiteSpace("the rendered text body should be included as the multipart text/plain alternative"); } // ── Helpers ────────────────────────────────────────────────────────── private static void SkipIfGreenmailUnavailable() { var reachable = false; try { using var probe = new TcpClient(); var task = probe.ConnectAsync(GreenmailHost, GreenmailSmtpPort); reachable = task.Wait(TimeSpan.FromMilliseconds(500)) && probe.Connected; } catch { /* fall through — reachable stays false */ } // xUnit 2.9 does not have first-class test-skipping; this integration test // (Trait Category=Integration, Requires=Greenmail) MUST be filtered out when // greenmail is not running. Failing loudly is the correct behaviour for the // CI lane that opts in to the Integration category — silently passing would // hide a broken SMTP wiring. Assert.True(reachable, $"Greenmail not reachable on {GreenmailHost}:{GreenmailSmtpPort}. " + "Start with: docker compose -f redb.Route/docker-compose.tests.yml up greenmail -d, " + "or filter this test out via `--filter Category!=Integration`."); } private static async Task ProvisionGreenmailUserAsync(string login, string password) { // Idempotent — greenmail returns 200 on first create and 409/400 on duplicate; both fine. using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(3) }; var json = $"{{\"email\":\"{login}@localhost\",\"login\":\"{login}\",\"password\":\"{password}\"}}"; using var content = new StringContent(json, Encoding.UTF8, "application/json"); try { using var _ = await http.PostAsync($"{ApiBase}/api/user", content); } catch { /* greenmail REST is best-effort here — the SMTP listener creates the account on delivery anyway. */ } } private static async Task<(string? Subject, string? HtmlBody, string? TextBody)> ReadFirstMessageAsync( string login, string password) { // Poll up to ~3 s for the message to be indexed by greenmail's IMAP listener. Exception? lastError = null; for (var attempt = 0; attempt < 15; attempt++) { try { using var imap = new ImapClient(); await imap.ConnectAsync(GreenmailHost, GreenmailImapPort, MailKit.Security.SecureSocketOptions.None); await imap.AuthenticateAsync(login, password); var inbox = imap.Inbox; await inbox.OpenAsync(MailKit.FolderAccess.ReadOnly); if (inbox.Count > 0) { var msg = await inbox.GetMessageAsync(0); await imap.DisconnectAsync(true); return (msg.Subject, msg.HtmlBody, msg.TextBody); } await imap.DisconnectAsync(true); } catch (Exception ex) { lastError = ex; } await Task.Delay(200); } throw new Xunit.Sdk.XunitException( $"No message arrived in {login}@localhost INBOX within 3 s. Last error: {lastError?.Message}"); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackPasswordRecoveryTests.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/FullStackPasswordRecoveryTests.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http.Json; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Contracts.Users; using redb.Identity.Core.Models; using redb.Identity.Core.PasswordReset; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// N-4 (Session C): full-stack E2E tests for the anonymous password-recovery flow. /// Path: HTTP → Kestrel → PasswordRecoveryController (no auth) → direct-vm → processor → /// IPasswordResetTokenStore + InMemoryEmailNotificationChannel + redb stores. /// /// Asserts the anti-enumeration contract (always 200, no e-mail sent on misses), the /// single-use token guarantee, the per-client URL whitelist, and the post-reset session /// revocation effect (old password rejected, new password accepted). /// /// [Collection("ProductionHttp")] public class FullStackPasswordRecoveryTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; private const string ResetEmail = "e2e@example.com"; private const string ResetUrl = "http://localhost/reset-password"; private const string ResetUrlNotWhitelisted = "http://attacker.example/reset"; private const string ClientId = ProductionHttpFixture.TestClientId; public FullStackPasswordRecoveryTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } // ══════════════════════════════════════════════════════════════════ // Test setup helpers // ══════════════════════════════════════════════════════════════════ /// /// Ensures the test client carries on its /// ApplicationProps.PasswordResetUris whitelist. Idempotent — adds the URL /// only if it is not already present. /// private async Task EnsureWhitelistedAsync(string resetUrl) { await _fx.UseRedbAsync(async redb => { var app = await redb.Query() .Where(p => p.ClientId == ClientId) .FirstOrDefaultAsync(); app.Should().NotBeNull("seed for {0} must exist", ClientId); var existing = app!.Props.PasswordResetUris ?? Array.Empty(); if (existing.Contains(resetUrl, StringComparer.Ordinal)) return; app.Props.PasswordResetUris = existing.Concat(new[] { resetUrl }).ToArray(); await redb.SaveAsync(app); }); } private static (string jti, string token) ExtractResetParams(string html) { // BuildResetLink writes …?token=&jti= var jtiMatch = Regex.Match(html, @"jti=([0-9a-fA-F]{32})"); var tokenMatch = Regex.Match(html, @"token=([A-Za-z0-9\-_%]+)"); jtiMatch.Success.Should().BeTrue("reset e-mail must carry jti=… ; body was: {0}", html); tokenMatch.Success.Should().BeTrue("reset e-mail must carry token=… ; body was: {0}", html); return (jtiMatch.Groups[1].Value, Uri.UnescapeDataString(tokenMatch.Groups[1].Value)); } private async Task PostForgotAsync(string email, string callerResetUrl, string clientId = ClientId) => await _http.PostAsJsonAsync("/api/v1/identity/password/forgot", new { email, clientId, callerResetUrl }); private async Task PostResetAsync(string jti, string token, string newPassword) => await _http.PostAsJsonAsync("/api/v1/identity/password/reset", new { jti, token, newPassword }); private async Task TryPasswordGrantAsync(string username, string password) { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = username, ["password"] = password, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid" }); return await _http.PostAsync("/connect/token", content); } /// /// Restore the seeded password so other tests in the ProductionHttp collection keep /// working regardless of execution order. Direct store call via the IUserProvider — /// bypasses the password-history check the public flow enforces. /// private async Task RestoreSeedPasswordAsync() { await _fx.UseRedbAsync(async redb => { var user = await redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername); if (user is null) return; await redb.UserProvider.SetPasswordAsync(user, ProductionHttpFixture.TestPassword); }); } // ══════════════════════════════════════════════════════════════════ // Happy path — token issued, e-mail captured, reset succeeds // ══════════════════════════════════════════════════════════════════ [Fact] public async Task ForgotReset_HappyPath_IssuesEmail_AcceptsReset_RevokesOldPassword() { await EnsureWhitelistedAsync(ResetUrl); _fx.Emails.Clear(); // 1. Initiate recovery var forgotResp = await PostForgotAsync(ResetEmail, ResetUrl); forgotResp.StatusCode.Should().Be(HttpStatusCode.OK); var forgotJson = await forgotResp.Content.ReadFromJsonAsync(); forgotJson.GetProperty("success").GetBoolean().Should().BeTrue(); // 2. Captured e-mail must contain a reset link var captured = _fx.Emails.ForRecipient(ResetEmail); captured.Should().HaveCount(1, "the happy-path forgot call must dispatch exactly one reset e-mail"); var msg = captured[0]; msg.TemplateId.Should().Be(IdentityEmailTemplates.PasswordReset); msg.HtmlBody.Should().Contain(ResetUrl); var (jti, token) = ExtractResetParams(msg.HtmlBody); // 3. Consume the token to set a new password. Suffix with a fresh GUID so reruns // against the same DB are not blocked by the password-history ("last N passwords") rule. var newPassword = $"E2E@NewPwd-{Guid.NewGuid():N}!"; try { var resetResp = await PostResetAsync(jti, token, newPassword); resetResp.StatusCode.Should().Be(HttpStatusCode.OK, "happy-path reset must succeed: {0}", await resetResp.Content.ReadAsStringAsync()); var resetJson = await resetResp.Content.ReadFromJsonAsync(); resetJson.GetProperty("success").GetBoolean().Should().BeTrue(); // 4. Old password must no longer work… using (var oldAttempt = await TryPasswordGrantAsync(ProductionHttpFixture.TestUsername, ProductionHttpFixture.TestPassword)) { oldAttempt.StatusCode.Should().NotBe(HttpStatusCode.OK, "old password must be rejected after a successful reset"); } // 5. …and the new password must. using var newAttempt = await TryPasswordGrantAsync(ProductionHttpFixture.TestUsername, newPassword); newAttempt.StatusCode.Should().Be(HttpStatusCode.OK, "new password must be accepted by the ROPC flow: {0}", await newAttempt.Content.ReadAsStringAsync()); } finally { await RestoreSeedPasswordAsync(); } } // ══════════════════════════════════════════════════════════════════ // Anti-enumeration — unknown e-mail returns success, no e-mail sent // ══════════════════════════════════════════════════════════════════ [Fact] public async Task Forgot_UnknownEmail_ReturnsSuccess_NoEmailSent() { await EnsureWhitelistedAsync(ResetUrl); _fx.Emails.Clear(); var resp = await PostForgotAsync("nobody-here-please-ignore@example.invalid", ResetUrl); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await resp.Content.ReadFromJsonAsync(); json.GetProperty("success").GetBoolean().Should().BeTrue(); _fx.Emails.Messages.Should().BeEmpty( "anti-enumeration: unknown e-mail must not trigger any dispatch"); } // ══════════════════════════════════════════════════════════════════ // Anti-enumeration — non-whitelisted callerResetUrl is silently dropped // ══════════════════════════════════════════════════════════════════ [Fact] public async Task Forgot_CallerResetUrlNotWhitelisted_ReturnsSuccess_NoEmailSent() { await EnsureWhitelistedAsync(ResetUrl); _fx.Emails.Clear(); var resp = await PostForgotAsync(ResetEmail, ResetUrlNotWhitelisted); resp.StatusCode.Should().Be(HttpStatusCode.OK); _fx.Emails.ForRecipient(ResetEmail).Should().BeEmpty( "open-redirect protection: a non-whitelisted CallerResetUrl must drop the request silently"); } // ══════════════════════════════════════════════════════════════════ // Anti-enumeration — unknown client_id returns success, no e-mail sent // ══════════════════════════════════════════════════════════════════ [Fact] public async Task Forgot_UnknownClient_ReturnsSuccess_NoEmailSent() { _fx.Emails.Clear(); var resp = await PostForgotAsync(ResetEmail, ResetUrl, clientId: "no-such-client-id"); resp.StatusCode.Should().Be(HttpStatusCode.OK); _fx.Emails.Messages.Should().BeEmpty( "anti-enumeration: unknown client_id must drop the request silently"); } // ══════════════════════════════════════════════════════════════════ // Single-use guarantee — second reset attempt with the same token fails // ══════════════════════════════════════════════════════════════════ [Fact] public async Task Reset_SecondAttemptWithSameToken_Fails() { await EnsureWhitelistedAsync(ResetUrl); _fx.Emails.Clear(); await PostForgotAsync(ResetEmail, ResetUrl); var captured = _fx.Emails.ForRecipient(ResetEmail); captured.Should().HaveCount(1); var (jti, token) = ExtractResetParams(captured[0].HtmlBody); // Fresh GUID-suffixed password keeps reruns clear of the password-history rule. var newPassword = $"E2E@OnceOnly-{Guid.NewGuid():N}!"; try { using var first = await PostResetAsync(jti, token, newPassword); first.StatusCode.Should().Be(HttpStatusCode.OK, "first consume must succeed"); // Second attempt with the SAME token: row is already marked Consumed. using var second = await PostResetAsync(jti, token, "E2E@WillNotApply-" + Guid.NewGuid().ToString("N") + "!"); second.StatusCode.Should().NotBe(HttpStatusCode.OK, "single-use guarantee: a second reset with the same token must be rejected"); } finally { await RestoreSeedPasswordAsync(); } } // ══════════════════════════════════════════════════════════════════ // Expired token — direct store call with a near-zero TTL, then consume // ══════════════════════════════════════════════════════════════════ [Fact] public async Task Reset_ExpiredToken_Fails() { // Issue directly through the store with a TTL that has already elapsed. // Wait 150 ms past expiry to defeat any clock granularity, then attempt consume. var sp = (IServiceProvider)typeof(ProductionHttpFixture) .GetField("_sp", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! .GetValue(_fx)!; var resetStore = sp.GetRequiredService(); long userId = await _fx.UseRedbAsync(async redb => { var u = await redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername); return u!.Id; }); var issued = await resetStore.IssueAsync(userId, ResetUrl, TimeSpan.FromMilliseconds(1)); await Task.Delay(150); using var resp = await PostResetAsync(issued.Jti.ToString("N"), issued.PlaintextToken, "E2E@WontApply123!"); resp.StatusCode.Should().NotBe(HttpStatusCode.OK, "expired tokens must be rejected by VerifyAndConsumeAsync"); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackProtocolTests.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/FullStackProtocolTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E tests for OIDC protocol endpoints. /// Complete path: HTTP request → Kestrel → HTTP facade → direct-vm:// → OpenIddict pipeline /// → redb stores → PostgreSQL → response → HTTP. /// Uses PRODUCTION OpenIddict (real stores, no degraded mode). /// [Collection("ProductionHttp")] public class FullStackProtocolTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public FullStackProtocolTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } // ══════════════════════════════════════════════ // Client Credentials // ══════════════════════════════════════════════ [Fact] public async Task ClientCredentials_ViaHttp_ReturnsJwt() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.OK, "token request failed: {0}", await resp.Content.ReadAsStringAsync()); var json = await ParseJson(resp); json.TryGetProperty("access_token", out var at).Should().BeTrue(); var jwt = at.GetString()!; jwt.Split('.').Should().HaveCount(3, "access_token should be a JWT"); json.GetProperty("token_type").GetString().Should().Be("Bearer"); } [Fact] public async Task ClientCredentials_JwtContainsCorrectIssuer() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid" }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); var jwt = json.GetProperty("access_token").GetString()!; var payload = DecodeJwtPayload(jwt); payload.GetProperty("iss").GetString().Should().Be($"http://localhost:{_fx.Port}/"); } [Fact] public async Task ClientCredentials_InvalidSecret_ReturnsError() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = "wrong-secret" }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.Unauthorized); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_client"); } // ══════════════════════════════════════════════ // Authorization Code + PKCE // ══════════════════════════════════════════════ [Fact] public async Task AuthCode_PKCE_FullExchange_ViaHttp() { var (verifier, challenge) = GeneratePkce(); // Step 1: Authorize → get code var code = await AuthorizeViaHttp( ProductionHttpFixture.TestPublicClientId, challenge, "openid offline_access"); code.Should().NotBeNullOrEmpty("authorize should return a code"); // Step 2: Exchange code → tokens var tokenContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["code_verifier"] = verifier }); var tokenResp = await _http.PostAsync("/connect/token", tokenContent); tokenResp.StatusCode.Should().Be(HttpStatusCode.OK, "token exchange failed: {0}", await tokenResp.Content.ReadAsStringAsync()); var json = await ParseJson(tokenResp); json.TryGetProperty("access_token", out _).Should().BeTrue(); json.GetProperty("token_type").GetString().Should().Be("Bearer"); json.TryGetProperty("refresh_token", out _).Should().BeTrue( "offline_access scope should yield a refresh_token"); } [Fact] public async Task AuthCode_ConfidentialClient_FullExchange_ViaHttp() { var (verifier, challenge) = GeneratePkce(); var code = await AuthorizeViaHttp( ProductionHttpFixture.TestClientId, challenge, "openid", ProductionHttpFixture.TestClientSecret); code.Should().NotBeNullOrEmpty(); var tokenContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["code_verifier"] = verifier }); var tokenResp = await _http.PostAsync("/connect/token", tokenContent); tokenResp.StatusCode.Should().Be(HttpStatusCode.OK, "token exchange failed: {0}", await tokenResp.Content.ReadAsStringAsync()); var json = await ParseJson(tokenResp); json.TryGetProperty("access_token", out _).Should().BeTrue(); } // ══════════════════════════════════════════════ // Refresh Token Rotation // ══════════════════════════════════════════════ [Fact] public async Task RefreshToken_Rotation_ViaHttp() { // Get initial tokens via auth code flow var (verifier, challenge) = GeneratePkce(); var code = await AuthorizeViaHttp( ProductionHttpFixture.TestPublicClientId, challenge, "openid offline_access"); var exchangeContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code!, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["code_verifier"] = verifier }); var exchangeResp = await _http.PostAsync("/connect/token", exchangeContent); var initial = await ParseJson(exchangeResp); var refreshToken = initial.GetProperty("refresh_token").GetString()!; // Rotate: use refresh_token to get new tokens var refreshContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "refresh_token", ["refresh_token"] = refreshToken, ["client_id"] = ProductionHttpFixture.TestPublicClientId }); var refreshResp = await _http.PostAsync("/connect/token", refreshContent); refreshResp.StatusCode.Should().Be(HttpStatusCode.OK, "refresh failed: {0}", await refreshResp.Content.ReadAsStringAsync()); var rotated = await ParseJson(refreshResp); rotated.TryGetProperty("access_token", out _).Should().BeTrue(); rotated.TryGetProperty("refresh_token", out var newRt).Should().BeTrue(); newRt.GetString().Should().NotBe(refreshToken, "rotation should produce a new refresh token"); } // ══════════════════════════════════════════════ // Introspection (RFC 7662) // ══════════════════════════════════════════════ [Fact] public async Task Introspect_ValidToken_ReturnsActive() { var token = await ObtainAccessToken(); var resp = await _http.PostAsync("/connect/introspect", IntrospectBody(token)); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.GetProperty("active").GetBoolean().Should().BeTrue( "freshly issued token must be active via production store lookup"); } // ══════════════════════════════════════════════ // Revocation → Introspection lifecycle (THE KEY TEST) // ══════════════════════════════════════════════ [Fact] public async Task Revoke_ThenIntrospect_ReturnsInactive() { // 1. Issue token (persisted in PostgreSQL via RedbTokenStore) var token = await ObtainAccessToken(); // 2. Verify active var resp1 = await _http.PostAsync("/connect/introspect", IntrospectBody(token)); resp1.StatusCode.Should().Be(HttpStatusCode.OK); var json1 = await ParseJson(resp1); json1.GetProperty("active").GetBoolean().Should().BeTrue( "token should be active before revocation"); // 3. Revoke (updates status in PostgreSQL) var revokeResp = await _http.PostAsync("/connect/revocation", RevokeBody(token)); revokeResp.StatusCode.Should().Be(HttpStatusCode.OK); // 4. Introspect again — token must NOT be active anymore // OpenIddict may return 200 {active:false} or reject with 401 for revoked tokens var resp2 = await _http.PostAsync("/connect/introspect", IntrospectBody(token)); var tokenStillActive = false; if (resp2.StatusCode == HttpStatusCode.OK) { var json2 = await ParseJson(resp2); if (json2.TryGetProperty("active", out var active)) tokenStillActive = active.GetBoolean(); } tokenStillActive.Should().BeFalse( "revoked token must not be active — verified via production store (PostgreSQL)"); } // ══════════════════════════════════════════════ // Userinfo // ══════════════════════════════════════════════ [Fact] public async Task Userinfo_ViaHttp_ReturnsProfileClaims() { // Get access token with profile scope via auth code flow var (verifier, challenge) = GeneratePkce(); var code = await AuthorizeViaHttp( ProductionHttpFixture.TestClientId, challenge, "openid profile email", ProductionHttpFixture.TestClientSecret); var tokenContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code!, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["code_verifier"] = verifier }); var tokenResp = await _http.PostAsync("/connect/token", tokenContent); var tokenJson = await ParseJson(tokenResp); var accessToken = tokenJson.GetProperty("access_token").GetString()!; // Call userinfo with bearer token var req = new HttpRequestMessage(HttpMethod.Get, "/connect/userinfo"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var userinfoResp = await _http.SendAsync(req); userinfoResp.StatusCode.Should().Be(HttpStatusCode.OK, "userinfo failed: {0}", await userinfoResp.Content.ReadAsStringAsync()); var userinfo = await ParseJson(userinfoResp); userinfo.TryGetProperty("sub", out _).Should().BeTrue("userinfo must contain sub"); userinfo.TryGetProperty("given_name", out var gn).Should().BeTrue(); gn.GetString().Should().Be("E2E"); userinfo.TryGetProperty("family_name", out var fn).Should().BeTrue(); fn.GetString().Should().Be("Tester"); userinfo.TryGetProperty("email", out var em).Should().BeTrue(); em.GetString().Should().Be("e2e@example.com"); } [Fact] public async Task Userinfo_Post_ViaHttp_ReturnsProfileClaims() { // Get access token with profile scope via auth code flow var (verifier, challenge) = GeneratePkce(); var code = await AuthorizeViaHttp( ProductionHttpFixture.TestClientId, challenge, "openid profile email", ProductionHttpFixture.TestClientSecret); var tokenContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code!, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["code_verifier"] = verifier }); var tokenResp = await _http.PostAsync("/connect/token", tokenContent); var tokenJson = await ParseJson(tokenResp); var accessToken = tokenJson.GetProperty("access_token").GetString()!; // Call userinfo via POST with bearer token var req = new HttpRequestMessage(HttpMethod.Post, "/connect/userinfo"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var userinfoResp = await _http.SendAsync(req); userinfoResp.StatusCode.Should().Be(HttpStatusCode.OK, "userinfo POST failed: {0}", await userinfoResp.Content.ReadAsStringAsync()); var userinfo = await ParseJson(userinfoResp); userinfo.TryGetProperty("sub", out _).Should().BeTrue("userinfo must contain sub"); userinfo.TryGetProperty("given_name", out var gn).Should().BeTrue(); gn.GetString().Should().Be("E2E"); } // ══════════════════════════════════════════════ // Discovery & JWKS // ══════════════════════════════════════════════ [Fact] public async Task Discovery_ReturnsFullConfiguration() { var resp = await _http.GetAsync("/.well-known/openid-configuration"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.GetProperty("issuer").GetString().Should().Be($"http://localhost:{_fx.Port}/"); json.TryGetProperty("token_endpoint", out _).Should().BeTrue(); json.TryGetProperty("authorization_endpoint", out _).Should().BeTrue(); json.TryGetProperty("userinfo_endpoint", out _).Should().BeTrue(); json.TryGetProperty("introspection_endpoint", out _).Should().BeTrue(); json.TryGetProperty("revocation_endpoint", out _).Should().BeTrue(); json.TryGetProperty("jwks_uri", out _).Should().BeTrue(); json.TryGetProperty("grant_types_supported", out _).Should().BeTrue(); } [Fact] public async Task Jwks_ReturnsSigningKeys() { var resp = await _http.GetAsync("/.well-known/jwks"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.TryGetProperty("keys", out var keys).Should().BeTrue(); keys.ValueKind.Should().Be(JsonValueKind.Array); keys.GetArrayLength().Should().BeGreaterThan(0); } // ══════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════ private async Task ObtainAccessToken() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.OK, "token request failed: {0}", await resp.Content.ReadAsStringAsync()); var json = await ParseJson(resp); return json.GetProperty("access_token").GetString()!; } /// /// Performs authorization via HTTP POST, handling both redirect (302) and JSON responses. /// First logs in via POST /login to obtain a session cookie, then uses it for authorize. /// Returns the authorization code. /// private async Task AuthorizeViaHttp( string clientId, string codeChallenge, string scope, string? clientSecret = null) { var cookieContainer = new System.Net.CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookieContainer, UseCookies = true }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; // Step 1: Login to obtain session cookie var loginForm = new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword }); var loginResp = await client.PostAsync("/login", loginForm); // Login should set a session cookie (response may be 302 or 200) cookieContainer.Count.Should().BeGreaterThan(0, "login response must set a session cookie"); // Step 2: Authorize with the session cookie var form = new Dictionary { ["response_type"] = "code", ["client_id"] = clientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = scope, ["code_challenge"] = codeChallenge, ["code_challenge_method"] = "S256" }; if (clientSecret is not null) form["client_secret"] = clientSecret; var resp = await client.PostAsync("/connect/authorize", new FormUrlEncodedContent(form)); // The authorize endpoint may return a 302 redirect or a JSON response if (resp.StatusCode == HttpStatusCode.Redirect || resp.StatusCode == HttpStatusCode.Found) { var location = resp.Headers.Location?.ToString(); location.Should().NotBeNull("redirect should have a Location header"); return ExtractQueryParam(location!, "code"); } // Try JSON response (API-first flow returns code in body) var json = await ParseJson(resp); if (json.TryGetProperty("code", out var code)) return code.GetString(); // Propagate error info for diagnostics if (json.TryGetProperty("error", out var err)) throw new InvalidOperationException( $"Authorize returned error: {err.GetString()} — {(json.TryGetProperty("error_description", out var d) ? d.GetString() : "no description")}"); throw new InvalidOperationException( $"Unexpected authorize response ({resp.StatusCode}): {json.GetRawText()}"); } private FormUrlEncodedContent IntrospectBody(string token) => new(new Dictionary { ["token"] = token, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret }); private FormUrlEncodedContent RevokeBody(string token) => new(new Dictionary { ["token"] = token, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret }); private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } private static JsonElement DecodeJwtPayload(string jwt) { var parts = jwt.Split('.'); var padded = parts[1]; switch (padded.Length % 4) { case 2: padded += "=="; break; case 3: padded += "="; break; } var bytes = Convert.FromBase64String(padded.Replace('-', '+').Replace('_', '/')); return JsonDocument.Parse(bytes).RootElement; } private static string? ExtractQueryParam(string url, string param) { var idx = url.IndexOf('?'); if (idx < 0) return null; var query = url[(idx + 1)..]; foreach (var pair in query.Split('&')) { var kv = pair.Split('=', 2); if (kv[0] == param) return Uri.UnescapeDataString(kv[1]); } return null; } private static (string verifier, string challenge) GeneratePkce() { var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); var verifier = Convert.ToBase64String(bytes) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = SHA256.HashData(Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackScopeAuthorizationTests.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/FullStackScopeAuthorizationTests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E tests for B0.1: RestrictScopeByGroupMembershipHandler. /// Validates that selected OAuth scopes (configured via /// ) /// are only granted to users belonging to the required group, while /// client_credentials grants remain unaffected. /// /// Fixture configures: { "identity:admin" → "identity-admins" }. /// Seeds an admin user () /// added to the group, and a regular user () /// not in any group. /// /// [Collection("ProductionHttp")] public class FullStackScopeAuthorizationTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public FullStackScopeAuthorizationTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } // ════════════════════════════════════════════════════════════════ // Password grant — gated scope, gated by group membership // ════════════════════════════════════════════════════════════════ [Fact] public async Task PasswordGrant_GatedScope_NotInGroup_ReturnsAccessDenied() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, // not in identity-admins ["password"] = ProductionHttpFixture.TestPassword, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = $"openid {ProductionHttpFixture.AdminGatedScope}" }); var resp = await _http.PostAsync("/connect/token", content); var bodyText = await resp.Content.ReadAsStringAsync(); resp.IsSuccessStatusCode.Should().BeFalse( "user not in group should be denied the gated scope. Status={0} Body={1}", resp.StatusCode, bodyText); var json = JsonSerializer.Deserialize(bodyText); json.GetProperty("error").GetString().Should().Be("access_denied"); json.TryGetProperty("error_description", out var desc).Should().BeTrue(); desc.GetString().Should().Contain(ProductionHttpFixture.AdminGroupName); } [Fact] public async Task PasswordGrant_GatedScope_InGroup_ReturnsToken() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestAdminUsername, // member of identity-admins ["password"] = ProductionHttpFixture.TestAdminPassword, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = $"openid {ProductionHttpFixture.AdminGatedScope}" }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.OK, "admin user should obtain the gated scope: {0}", await resp.Content.ReadAsStringAsync()); var json = await ParseJson(resp); json.TryGetProperty("access_token", out var at).Should().BeTrue(); at.GetString()!.Split('.').Should().HaveCount(3, "access_token should be a JWT"); } [Fact] public async Task PasswordGrant_NonGatedScope_NotInAnyGroup_StillSucceeds() { // Sanity: handler must not affect requests that don't include a gated scope. var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid profile" }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.OK, "non-gated scopes must remain unaffected: {0}", await resp.Content.ReadAsStringAsync()); } // ════════════════════════════════════════════════════════════════ // client_credentials — NOT gated by group membership // ════════════════════════════════════════════════════════════════ [Fact] public async Task ClientCredentials_GatedScope_Succeeds() { // The management client has no user identity (sub = client_id, non-numeric). // Handler must skip and let the existing scp:* permission be the only gate. var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = ProductionHttpFixture.TestMgmtClientId, ["client_secret"] = ProductionHttpFixture.TestMgmtSecret, ["scope"] = ProductionHttpFixture.AdminGatedScope }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.OK, "client_credentials must not be gated by user-group membership: {0}", await resp.Content.ReadAsStringAsync()); var json = await ParseJson(resp); json.TryGetProperty("access_token", out _).Should().BeTrue(); } // ════════════════════════════════════════════════════════════════ // Refresh token — gated scope must propagate restriction // ════════════════════════════════════════════════════════════════ [Fact] public async Task RefreshToken_AfterAdminGrant_GatedScope_Succeeds() { // Step 1: admin user obtains a refresh token alongside the gated scope. var initialContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestAdminUsername, ["password"] = ProductionHttpFixture.TestAdminPassword, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = $"openid offline_access {ProductionHttpFixture.AdminGatedScope}" }); var initialResp = await _http.PostAsync("/connect/token", initialContent); initialResp.StatusCode.Should().Be(HttpStatusCode.OK, "initial admin grant must succeed: {0}", await initialResp.Content.ReadAsStringAsync()); var initialJson = await ParseJson(initialResp); var refreshToken = initialJson.GetProperty("refresh_token").GetString()!; // Step 2: refresh — handler must re-evaluate group membership and allow. var refreshContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "refresh_token", ["refresh_token"] = refreshToken, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret }); var refreshResp = await _http.PostAsync("/connect/token", refreshContent); refreshResp.StatusCode.Should().Be(HttpStatusCode.OK, "admin still in group should refresh successfully: {0}", await refreshResp.Content.ReadAsStringAsync()); } private static async Task ParseJson(HttpResponseMessage resp) { var stream = await resp.Content.ReadAsStreamAsync(); return await JsonSerializer.DeserializeAsync(stream); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/FullStackSessionTests.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/FullStackSessionTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-stack E2E tests for session management via HTTP. /// Complete path: HTTP → Kestrel → bearer auth → controller → direct-vm:// → processor → PG. /// [Collection("ProductionHttp")] public class FullStackSessionTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public FullStackSessionTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } private HttpRequestMessage WithAuth(HttpRequestMessage request) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return request; } [Fact] public async Task Sessions_ListEmpty_ViaHttp() { var userId = Random.Shared.NextInt64(900_000, 999_999); var req = WithAuth(new HttpRequestMessage(HttpMethod.Get, $"/api/v1/identity/sessions?userId={userId}")); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.ValueKind.Should().Be(JsonValueKind.Array); json.GetArrayLength().Should().Be(0); } [Fact] public async Task Sessions_CreateThenList_ViaHttp() { // Create a session directly var sessionService = new SessionService(_fx.Redb); var coreUser = await _fx.Redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername) ?? throw new Exception("Test user not found"); var app = await _fx.Redb.Query() .Where(p => p.ClientId == ProductionHttpFixture.TestClientId) .FirstOrDefaultAsync(); app.Should().NotBeNull(); var session = await sessionService.CreateAsync(coreUser.Id, app!.id); try { var req = WithAuth(new HttpRequestMessage(HttpMethod.Get, $"/api/v1/identity/sessions?userId={coreUser.Id}")); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.ValueKind.Should().Be(JsonValueKind.Array); json.GetArrayLength().Should().BeGreaterThan(0); // Find the session we just created var found = false; foreach (var item in json.EnumerateArray()) { if (item.TryGetProperty("sessionId", out var sidProp) && sidProp.GetInt64() == session.id) { found = true; item.GetProperty("status").GetString().Should().Be("active"); break; } } found.Should().BeTrue("Session should appear in the management API"); } finally { await sessionService.RevokeAsync(session.id); } } [Fact] public async Task Sessions_Revoke_ViaHttp() { var sessionService = new SessionService(_fx.Redb); var coreUser = await _fx.Redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername) ?? throw new Exception("Test user not found"); var app = await _fx.Redb.Query() .Where(p => p.ClientId == ProductionHttpFixture.TestClientId) .FirstOrDefaultAsync(); var session = await sessionService.CreateAsync(coreUser.Id, app!.id); // Revoke via HTTP var req = WithAuth(new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/identity/sessions?sessionId={session.id}")); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.GetProperty("success").GetBoolean().Should().BeTrue(); json.GetProperty("revoked").GetInt32().Should().Be(1); } [Fact] public async Task Sessions_RevokeAll_ViaHttp() { var sessionService = new SessionService(_fx.Redb); var coreUser = await _fx.Redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername) ?? throw new Exception("Test user not found"); var app = await _fx.Redb.Query() .Where(p => p.ClientId == ProductionHttpFixture.TestClientId) .FirstOrDefaultAsync(); await sessionService.CreateAsync(coreUser.Id, app!.id); await sessionService.CreateAsync(coreUser.Id, app!.id); // Revoke all via HTTP var req = WithAuth(new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/identity/sessions/all?userId={coreUser.Id}")); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.GetProperty("success").GetBoolean().Should().BeTrue(); json.GetProperty("revoked").GetInt32().Should().BeGreaterThanOrEqualTo(2); // Verify list is empty var listReq = WithAuth(new HttpRequestMessage(HttpMethod.Get, $"/api/v1/identity/sessions?userId={coreUser.Id}")); var listResp = await _http.SendAsync(listReq); var listJson = await ParseJson(listResp); listJson.GetArrayLength().Should().Be(0); } [Fact] public async Task Sessions_Logout_ViaHttp() { var sessionService = new SessionService(_fx.Redb); var coreUser = await _fx.Redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername) ?? throw new Exception("Test user not found"); var app = await _fx.Redb.Query() .Where(p => p.ClientId == ProductionHttpFixture.TestClientId) .FirstOrDefaultAsync(); await sessionService.CreateAsync(coreUser.Id, app!.id); // Logout via management HTTP var req = WithAuth(new HttpRequestMessage(HttpMethod.Post, $"/api/v1/identity/sessions/logout?userId={coreUser.Id}")); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.GetProperty("success").GetBoolean().Should().BeTrue(); } private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/GroupNameUniquenessTests.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/GroupNameUniquenessTests.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Logging.Abstractions; using redb.Core.Models.Entities; using redb.Identity.Contracts.Scim; using redb.Identity.Core.Models; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// A group name is unique across the whole tree, compared without case, surrounding whitespace or /// Unicode form: the groups claim, the scope gates and the LDAP and SCIM mappings name a group by it. /// [Collection("ProductionHttp")] public class GroupNameUniquenessTests { private readonly ProductionHttpFixture _fx; public GroupNameUniquenessTests(ProductionHttpFixture fx) => _fx = fx; private static string NewName() => "Unique-" + Guid.NewGuid().ToString("N")[..12]; [Fact] public async Task ASecondGroupWithTheSameNameInAnotherCase_IsRefused409() { var name = NewName(); await CreateAsync(name); using var second = await SendAsync(HttpMethod.Post, "/api/v1/identity/groups", new { name = " " + name.ToLowerInvariant() + " " }); ((int)second.StatusCode).Should().Be(409, await second.Content.ReadAsStringAsync()); } [Fact] public async Task AChildGroupWithATakenName_IsRefused409() { var name = NewName(); var parent = await CreateAsync(NewName()); await CreateAsync(name); using var child = await SendAsync(HttpMethod.Post, $"/api/v1/identity/groups/{parent}/children", new { name = name.ToUpperInvariant() }); ((int)child.StatusCode).Should().Be(409, await child.Content.ReadAsStringAsync()); } [Fact] public async Task RenamingAGroupToATakenName_IsRefused409_AndTheGroupKeepsItsName() { var taken = NewName(); await CreateAsync(taken); var own = NewName(); var id = await CreateAsync(own); using var rename = await SendAsync(HttpMethod.Put, $"/api/v1/identity/groups/{id}", new { name = taken.ToUpperInvariant() }); ((int)rename.StatusCode).Should().Be(409, await rename.Content.ReadAsStringAsync()); using var read = await SendAsync(HttpMethod.Get, $"/api/v1/identity/groups/{id}", null); JsonDocument.Parse(await read.Content.ReadAsStringAsync()).RootElement.GetProperty("name").GetString().Should().Be(own); } [Fact] public async Task ADeletedGroupsName_CanBeTakenAgain() { var name = NewName(); var id = await CreateAsync(name); using var delete = await SendAsync(HttpMethod.Delete, $"/api/v1/identity/groups/{id}", null); ((int)delete.StatusCode).Should().Be(200, await delete.Content.ReadAsStringAsync()); await CreateAsync(name); } [Fact] public async Task AScimGroupWithATakenDisplayName_IsAScimUniquenessError() { var name = NewName(); await CreateAsync(name); var request = new HttpRequestMessage(HttpMethod.Post, "/scim/v2/Groups") { Content = new StringContent(JsonSerializer.Serialize(new ScimGroup { DisplayName = name.ToLowerInvariant() }), Encoding.UTF8, ScimConstants.MediaType), }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ScimToken); using var response = await _fx.Http.SendAsync(request); var answer = await response.Content.ReadAsStringAsync(); ((int)response.StatusCode).Should().Be(409, answer); JsonDocument.Parse(answer).RootElement.GetProperty("scimType").GetString().Should().Be("uniqueness"); } [Fact] public async Task GroupsFromBeforeNamesWereUnique_GetTheirKeyAtStart_OldestFirst_AndADuplicateAfterItsRename() { // Two groups as an older version left them: the same name in two spellings, no key. var name = NewName(); var (olderId, newerId) = await _fx.UseRedbAsync(async redb => { var older = new RedbObject(new GroupProps()) { name = name }; var newer = new RedbObject(new GroupProps()) { name = name.ToUpperInvariant() }; var o = await redb.SaveAsync(older); var n = await redb.SaveAsync(newer); return (o, n); }); // The query UPGRADING.md gives operators finds the pair (PostgreSQL form; the test database is either). if (TestRedbSetup.SelectedProvider == TestRedbSetup.Provider.Postgres) { var listed = await _fx.UseRedbAsync(redb => redb.Context.QueryScalarListAsync( """ SELECT o._id FROM _objects o JOIN _schemes s ON s._id = o._id_scheme WHERE s._name = 'redb.Identity.Core.Models.GroupProps' AND lower(btrim(o._name)) IN ( SELECT lower(btrim(o2._name)) FROM _objects o2 JOIN _schemes s2 ON s2._id = o2._id_scheme WHERE s2._name = 'redb.Identity.Core.Models.GroupProps' GROUP BY lower(btrim(o2._name)) HAVING count(*) > 1) ORDER BY lower(btrim(o._name)), o._id """)); listed.Should().Contain(new[] { olderId, newerId }); } var conflicts = await _fx.UseRedbAsync(redb => GroupNameKeyListener.RunAsync(redb, new GroupService(redb), NullLogger.Instance, CancellationToken.None)); conflicts.Should().BeGreaterThanOrEqualTo(1); await _fx.UseRedbAsync(async redb => { (await redb.LoadAsync(olderId))!.ValueUnique.Should().Be(GroupNames.Key(name), "the oldest keeps the name"); (await redb.LoadAsync(newerId))!.ValueUnique.Should().BeNull("its name is taken"); }); // The operator renames the newer one; the next start gives it its key. var renamed = NewName(); await _fx.UseRedbAsync(async redb => { var newer = (await redb.LoadAsync(newerId))!; newer.name = renamed; await redb.SaveAsync(newer); }); await _fx.UseRedbAsync(redb => GroupNameKeyListener.RunAsync(redb, new GroupService(redb), NullLogger.Instance, CancellationToken.None)); await _fx.UseRedbAsync(async redb => (await redb.LoadAsync(newerId))!.ValueUnique.Should().Be(GroupNames.Key(renamed))); } private async Task CreateAsync(string name) { using var response = await SendAsync(HttpMethod.Post, "/api/v1/identity/groups", new { name }); var answer = await response.Content.ReadAsStringAsync(); ((int)response.StatusCode).Should().BeInRange(200, 299, answer); return JsonDocument.Parse(answer).RootElement.GetProperty("id").ToString(); } private Task SendAsync(HttpMethod method, string path, object? body) { var request = new HttpRequestMessage(method, path); if (body is not null) request.Content = JsonContent.Create(body); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return _fx.Http.SendAsync(request); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/GroupRequestValidationTests.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/GroupRequestValidationTests.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.FullStack; /// /// A group request that lacks a required field is the caller's mistake and is answered 400, and a /// membership request for a group that does not exist is never a server error. /// [Collection("ProductionHttp")] public class GroupRequestValidationTests { private const string MissingId = "987654321012"; private readonly ProductionHttpFixture _fx; private readonly ITestOutputHelper _out; public GroupRequestValidationTests(ProductionHttpFixture fx, ITestOutputHelper output) { _fx = fx; _out = output; } public static IEnumerable IncompleteRequests() => new[] { new object?[] { "POST", "/api/v1/identity/groups", "{}" }, new object?[] { "POST", "/api/v1/identity/groups", null }, new object?[] { "POST", "/api/v1/identity/groups/{group}/children", "{}" }, new object?[] { "POST", "/api/v1/identity/groups/{group}/move", "{}" }, new object?[] { "POST", "/api/v1/identity/groups/{group}/members", "{}" }, new object?[] { "PUT", "/api/v1/identity/groups/{group}/members/1", "{}" }, new object?[] { "PUT", "/api/v1/identity/groups/{group}", null }, }; [Theory] [MemberData(nameof(IncompleteRequests))] public async Task ARequestThatLacksARequiredField_IsAnswered400(string method, string path, string? body) { var groupId = await CreateGroupAsync(); using var response = await SendAsync(method, path.Replace("{group}", groupId), body); var answer = await response.Content.ReadAsStringAsync(); _out.WriteLine($"INCOMPLETE {method} {path} {body ?? "(no body)"} -> [{(int)response.StatusCode}] {(answer.Length > 200 ? answer[..200] : answer)}"); ((int)response.StatusCode).Should().Be(400, answer); } [Fact] public async Task RemovingAMemberOfAGroupThatDoesNotExist_IsNotAServerError() { using var response = await SendAsync("DELETE", $"/api/v1/identity/groups/{MissingId}/members/1", body: null); var answer = await response.Content.ReadAsStringAsync(); _out.WriteLine($"INCOMPLETE DELETE member of a missing group -> [{(int)response.StatusCode}] {answer}"); ((int)response.StatusCode).Should().BeLessThan(500, answer); } [Theory] [InlineData("PUT", """{"role":"member"}""")] [InlineData("DELETE", null)] public async Task AMembershipThatDoesNotExist_IsAnswered404(string method, string? body) { // An existing group, and a user who is not one of its members. var groupId = await CreateGroupAsync(); using var response = await SendAsync(method, $"/api/v1/identity/groups/{groupId}/members/987654321", body); var answer = await response.Content.ReadAsStringAsync(); ((int)response.StatusCode).Should().Be(404, answer); } [Fact] public async Task AnExpiredMembership_CanStillBeRemoved() { // The record exists although the membership no longer counts: it must stay removable. var groupId = long.Parse(await CreateGroupAsync()); const long userId = 987650001; await _fx.UseRedbAsync(redb => new GroupService(redb).AddMemberAsync( groupId, userId, "member", DateTimeOffset.UtcNow.AddDays(-1))); using var response = await SendAsync("DELETE", $"/api/v1/identity/groups/{groupId}/members/{userId}", body: null); ((int)response.StatusCode).Should().Be(200, await response.Content.ReadAsStringAsync()); } [Fact] public async Task AMembershipInheritedFromTheParentGroup_IsNotARecordOfTheChild() { // The user belongs to the parent, so the membership check says yes for the child too, but // there is no record in the child to change: 404, not a server error. const long userId = 987650002; var parentId = long.Parse(await CreateGroupAsync()); var childId = await _fx.UseRedbAsync(async redb => { var groups = new GroupService(redb); await groups.AddMemberAsync(parentId, userId, "member"); var child = await groups.CreateChildGroupAsync(parentId, "validation-child-" + Guid.NewGuid().ToString("N")[..12]); return child.Id; }); using var response = await SendAsync("PUT", $"/api/v1/identity/groups/{childId}/members/{userId}", """{"role":"owner"}"""); ((int)response.StatusCode).Should().Be(404, await response.Content.ReadAsStringAsync()); } private async Task CreateGroupAsync() { using var response = await SendAsync("POST", "/api/v1/identity/groups", JsonSerializer.Serialize(new { name = "validation-" + Guid.NewGuid().ToString("N")[..12] })); var answer = await response.Content.ReadAsStringAsync(); ((int)response.StatusCode).Should().BeInRange(200, 299, answer); using var json = JsonDocument.Parse(answer); return json.RootElement.GetProperty("id").ToString(); } private Task SendAsync(string method, string path, string? body) { var request = new HttpRequestMessage(new HttpMethod(method), path); if (body is not null) request.Content = new StringContent(body, System.Text.Encoding.UTF8, "application/json"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return _fx.Http.SendAsync(request); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/IdempotencyKeyTests.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/IdempotencyKeyTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// E2 — full-stack tests for the Idempotency-Key response cache. /// [Collection("ProductionHttp")] public class IdempotencyKeyTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public IdempotencyKeyTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } private HttpRequestMessage WithAuth(HttpRequestMessage request) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return request; } private static HttpRequestMessage WithIdemKey(HttpRequestMessage request, string key) { request.Headers.Add("Idempotency-Key", key); return request; } private async Task ParseJson(HttpResponseMessage resp) { var s = await resp.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize(s); } private HttpRequestMessage CreateAppRequest(string clientId) => WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/applications") { Content = JsonContent.Create(new { clientId, clientSecret = "idem-test-secret", displayName = "E2 Idem App" }) }); [Fact] public async Task SameKey_TwoCalls_ReplaysCachedResponse_AndDoesNotCreateSecondResource() { var clientId = $"e2e-idem-{Guid.NewGuid():N}"; var idemKey = Guid.NewGuid().ToString("N"); // First call — creates the resource. var resp1 = await _http.SendAsync(WithIdemKey(CreateAppRequest(clientId), idemKey)); resp1.StatusCode.Should().Be(HttpStatusCode.OK, "first create failed: {0}", await resp1.Content.ReadAsStringAsync()); resp1.Headers.TryGetValues("Idempotency-Replayed", out _).Should().BeFalse( "first call must not be marked as replayed"); var body1 = await ParseJson(resp1); // Second call with the SAME idempotency key — must replay (200, identical body), // and MUST NOT create a second application with the same clientId (which would have // failed with a duplicate-clientId error if the cache were bypassed). var resp2 = await _http.SendAsync(WithIdemKey(CreateAppRequest(clientId), idemKey)); resp2.StatusCode.Should().Be(HttpStatusCode.OK, "replay must succeed: {0}", await resp2.Content.ReadAsStringAsync()); resp2.Headers.TryGetValues("Idempotency-Replayed", out var replayedHeader).Should().BeTrue( "second call must surface the Idempotency-Replayed header"); replayedHeader!.Single().Should().Be("true"); var body2 = await ParseJson(resp2); body2.GetRawText().Should().Be(body1.GetRawText(), "replayed body must be byte-identical to the original response"); } [Fact] public async Task DifferentKey_CreatesIndependentResource() { var clientIdA = $"e2e-idem-{Guid.NewGuid():N}"; var clientIdB = $"e2e-idem-{Guid.NewGuid():N}"; var key1 = Guid.NewGuid().ToString("N"); var key2 = Guid.NewGuid().ToString("N"); var respA = await _http.SendAsync(WithIdemKey(CreateAppRequest(clientIdA), key1)); respA.StatusCode.Should().Be(HttpStatusCode.OK); var respB = await _http.SendAsync(WithIdemKey(CreateAppRequest(clientIdB), key2)); respB.StatusCode.Should().Be(HttpStatusCode.OK); respB.Headers.TryGetValues("Idempotency-Replayed", out _).Should().BeFalse( "different key must NOT be served from cache"); var bodyA = await ParseJson(respA); var bodyB = await ParseJson(respB); bodyA.GetRawText().Should().NotBe(bodyB.GetRawText(), "two distinct resources must produce two distinct bodies"); } [Fact] public async Task NoIdempotencyKey_DoesNotCacheAnyResponse() { var clientId = $"e2e-idem-{Guid.NewGuid():N}"; var resp1 = await _http.SendAsync(CreateAppRequest(clientId)); resp1.StatusCode.Should().Be(HttpStatusCode.OK); resp1.Headers.TryGetValues("Idempotency-Replayed", out _).Should().BeFalse(); // Same body, no idempotency key — second call hits the actual processor and the // duplicate clientId surfaces as a normal management-API error (NOT a 200 replay). var resp2 = await _http.SendAsync(CreateAppRequest(clientId)); resp2.Headers.TryGetValues("Idempotency-Replayed", out _).Should().BeFalse( "without Idempotency-Key the response is never replayed"); // We don't assert the exact status code of the duplicate; the contract is only // that no replay header is present and the request is processed normally. } [Fact] public async Task ReplayedResponse_CarriesSameStatusCode() { var clientId = $"e2e-idem-{Guid.NewGuid():N}"; var idemKey = Guid.NewGuid().ToString("N"); var resp1 = await _http.SendAsync(WithIdemKey(CreateAppRequest(clientId), idemKey)); var status1 = resp1.StatusCode; var resp2 = await _http.SendAsync(WithIdemKey(CreateAppRequest(clientId), idemKey)); resp2.StatusCode.Should().Be(status1, "cache must restore the original status code"); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/IdempotencySecretTests.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/IdempotencySecretTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Core.Models; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// An answer that carries a one-time secret (a member marked [OneTimeSecret]) is recorded for its /// Idempotency-Key without its body. The first call answers as before, with the secret. A repeat with the /// same key does not run the operation again and answers {"replayed":true,"secretWithheld":true,...} with /// the status of the first answer. Covered for every secret-bearing operation behind the idempotency cache: /// webhook create and rotate-secret, application rotate-secret, MFA setup; dynamic client registration is not cached. MFA confirm /// and recovery-code regeneration carry their codes through types the marker tests cover (OneTimeSecretsTests). /// [Collection("ProductionHttp")] public class IdempotencySecretTests { private const string Withheld = """{"replayed":true,"secretWithheld":true,"description":"The operation was already carried out for this Idempotency-Key. Its answer carried a secret that is shown only once, so it is not shown again."}"""; private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public IdempotencySecretTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } [Fact] public async Task Webhook_create_shows_the_secret_once_and_a_repeat_creates_nothing() { var key = Guid.NewGuid().ToString("N"); var url = $"http://127.0.0.1:9/idem-{key}"; var request = new { url, displayName = "idem", eventTypeFilter = "UserCreated", enabled = false }; var (status1, first) = await Send(HttpMethod.Post, "/api/v1/identity/webhooks", request, key); status1.Should().Be(HttpStatusCode.OK, first); var secret = Json(first).GetProperty("hmacSecret").GetString(); secret.Should().NotBeNullOrEmpty("the first answer shows the generated secret"); var (status2, second, replayed) = await SendReplay(HttpMethod.Post, "/api/v1/identity/webhooks", request, key); status2.Should().Be(status1); replayed.Should().BeTrue(); second.Should().Be(Withheld); var (_, list) = await Send(HttpMethod.Get, "/api/v1/identity/webhooks"); list.Split(url).Length.Should().Be(2, "the repeat did not create a second subscription"); await RecordShouldHoldNoSecret(key, secret!); } [Fact] public async Task Webhook_rotate_secret_is_not_rotated_again_by_a_repeat() { var (_, created) = await Send(HttpMethod.Post, "/api/v1/identity/webhooks", new { url = "http://127.0.0.1:9/idem-rotate", displayName = "idem-rotate", eventTypeFilter = "UserCreated", enabled = false }); var id = Json(created).GetProperty("id").GetInt64(); var key = Guid.NewGuid().ToString("N"); var (status1, first) = await Send(HttpMethod.Post, $"/api/v1/identity/webhooks/{id}/rotate-secret", null, key); status1.Should().Be(HttpStatusCode.OK, first); var rotated = Json(first).GetProperty("hmacSecret").GetString()!; rotated.Should().NotBeNullOrEmpty(); var (_, second, replayed) = await SendReplay(HttpMethod.Post, $"/api/v1/identity/webhooks/{id}/rotate-secret", null, key); replayed.Should().BeTrue(); second.Should().Be(Withheld); var stored = await _fx.UseRedbAsync(redb => redb.LoadAsync(id)); stored!.Props.HmacSecret.Should().Be(rotated, "the repeat did not rotate the secret again"); await RecordShouldHoldNoSecret(key, rotated); } [Fact] public async Task Application_rotate_secret_is_not_rotated_again_by_a_repeat() { var clientId = $"idem-rotate-{Guid.NewGuid():N}"; var (_, created) = await Send(HttpMethod.Post, "/api/v1/identity/applications", new { clientId, clientSecret = "idem-initial-secret", displayName = "Idem rotate" }); var id = long.Parse(Json(created).GetProperty("id").GetString()!); var key = Guid.NewGuid().ToString("N"); var (status1, first) = await Send(HttpMethod.Post, $"/api/v1/identity/applications/{id}/rotate-secret", null, key); status1.Should().Be(HttpStatusCode.OK, first); var newSecret = Json(first).GetProperty("newSecret").GetString()!; newSecret.Should().NotBeNullOrEmpty(); var hashAfterFirst = await ClientSecretHash(id); var (_, second, replayed) = await SendReplay(HttpMethod.Post, $"/api/v1/identity/applications/{id}/rotate-secret", null, key); replayed.Should().BeTrue(); second.Should().Be(Withheld); (await ClientSecretHash(id)).Should().Be(hashAfterFirst, "the repeat did not rotate the secret again"); await RecordShouldHoldNoSecret(key, newSecret); } [Fact] public async Task Mfa_setup_is_withheld_on_a_repeat() { var userId = await CreateUserAsync(); var key = Guid.NewGuid().ToString("N"); var request = new { userId, username = "idem" }; var (status1, setup) = await Send(HttpMethod.Post, "/api/v1/identity/mfa/totp/setup", request, key); status1.Should().Be(HttpStatusCode.OK, setup); var secret = Json(setup).GetProperty("secret_base32").GetString()!; var setupToken = Json(setup).GetProperty("setup_token").GetString()!; var (status2, repeat, replayed) = await SendReplay(HttpMethod.Post, "/api/v1/identity/mfa/totp/setup", request, key); status2.Should().Be(status1); replayed.Should().BeTrue(); repeat.Should().Be(Withheld); await RecordShouldHoldNoSecret(key, secret); await RecordShouldHoldNoSecret(key, setupToken); } [Fact] public async Task A_second_registrant_with_the_same_key_gets_its_own_registration_and_nothing_of_the_first() { var key = Guid.NewGuid().ToString("N"); var body = new { redirect_uris = new[] { "http://localhost/callback" }, client_name = "Idem DCR" }; var first = await _http.SendAsync(Dcr(body, key)); var firstJson = await first.Content.ReadAsStringAsync(); first.StatusCode.Should().Be(HttpStatusCode.Created, firstJson); var firstClient = Json(firstJson).GetProperty("client_id").GetString()!; var firstSecret = Json(firstJson).GetProperty("client_secret").GetString()!; var firstToken = Json(firstJson).GetProperty("registration_access_token").GetString()!; // Another party holding the same initial access token sends the same Idempotency-Key. var second = await _http.SendAsync(Dcr(body, key)); var secondJson = await second.Content.ReadAsStringAsync(); second.StatusCode.Should().Be(HttpStatusCode.Created, secondJson); second.Headers.Contains("Idempotency-Replayed").Should().BeFalse("registration answers are not replayed"); secondJson.Should().NotContain(firstClient).And.NotContain(firstSecret).And.NotContain(firstToken) .And.NotContain("secretWithheld"); Json(secondJson).GetProperty("client_id").GetString().Should().NotBe(firstClient, "it got a registration of its own"); (await _fx.UseRedbAsync(redb => redb.Query().Where(r => r.IdempotencyKey == key).ToListAsync())) .Should().BeEmpty("no record is kept for a registration"); } [Fact] public async Task An_answer_without_a_secret_is_still_replayed_whole() { var (_, created) = await Send(HttpMethod.Post, "/api/v1/identity/webhooks", new { url = "http://127.0.0.1:9/idem-update", displayName = "idem-update", eventTypeFilter = "UserCreated", enabled = false }); var id = Json(created).GetProperty("id").GetInt64(); var key = Guid.NewGuid().ToString("N"); var (_, first) = await Send(HttpMethod.Put, $"/api/v1/identity/webhooks/{id}", new { displayName = "idem-update-2" }, key); var (_, second, replayed) = await SendReplay(HttpMethod.Put, $"/api/v1/identity/webhooks/{id}", new { displayName = "idem-update-2" }, key); replayed.Should().BeTrue(); second.Should().Be(first); var record = await RecordOf(key); record.Props.SecretWithheld.Should().BeFalse(); record.Props.ResponseBody.Should().Be(first); } [Fact] public async Task The_upgrading_statements_remove_a_record_stored_with_its_secret_by_an_earlier_version() { var request = new { url = "http://127.0.0.1:9/idem-upgrade", displayName = "idem-upgrade", eventTypeFilter = "UserCreated", enabled = false }; var key = Guid.NewGuid().ToString("N"); var (_, first) = await Send(HttpMethod.Post, "/api/v1/identity/webhooks", request, key); // Turn the record into what an earlier version stored: the whole answer, secret included. var record = await RecordOf(key); record.Props.SecretWithheld = false; record.Props.ResponseBody = first; await _fx.UseRedbAsync(redb => redb.SaveAsync(record)); var (_, replayedBefore, _) = await SendReplay(HttpMethod.Post, "/api/v1/identity/webhooks", request, key); replayedBefore.Should().Be(first, "an earlier record replays the secret until it is removed"); foreach (var statement in UpgradingStatements()) await _fx.UseRedbAsync(redb => redb.Context.ExecuteAsync(statement)); (await _fx.UseRedbAsync(redb => redb.Query().Where(r => r.IdempotencyKey == key).ToListAsync())) .Should().BeEmpty("the statements removed the record"); var (status, again, replayed) = await SendReplay(HttpMethod.Post, "/api/v1/identity/webhooks", request, key); status.Should().Be(HttpStatusCode.OK, again); replayed.Should().BeFalse("with the record gone the request runs again"); Json(again).GetProperty("id").GetInt64().Should().NotBe(Json(first).GetProperty("id").GetInt64()); await RecordShouldHoldNoSecret(key, Json(again).GetProperty("hmacSecret").GetString()!); } // The SQL block of the "Idempotency records keep no secrets" section of redb.Identity/UPGRADING.md, as published. private static IEnumerable UpgradingStatements() { var dir = new DirectoryInfo(AppContext.BaseDirectory); while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "redb.Identity", "UPGRADING.md"))) dir = dir.Parent; dir.Should().NotBeNull("the test runs inside the repository"); var text = File.ReadAllText(Path.Combine(dir!.FullName, "redb.Identity", "UPGRADING.md")); var section = text[text.IndexOf("### Idempotency records keep no secrets", StringComparison.Ordinal)..]; var start = section.IndexOf("```sql", StringComparison.Ordinal) + "```sql".Length; var sql = section[start..section.IndexOf("```", start, StringComparison.Ordinal)]; return sql.Split(';').Select(s => s.Trim()).Where(s => s.Length > 0); } private async Task RecordShouldHoldNoSecret(string key, string secret) { var record = await RecordOf(key); record.Props.SecretWithheld.Should().BeTrue(); record.Props.ResponseBody.Should().BeNull(); JsonSerializer.Serialize(record.Props).Should().NotContain(secret, "the record keeps nothing of the secret"); } private async Task> RecordOf(string key) { var records = await _fx.UseRedbAsync(redb => redb.Query() .Where(r => r.IdempotencyKey == key) .ToListAsync()); return records.Should().ContainSingle().Subject; } private async Task ClientSecretHash(long id) { var app = await _fx.UseRedbAsync(redb => redb.LoadAsync(id)); return app!.Props.ClientSecret; } private async Task CreateUserAsync() { var login = "idem-" + Guid.NewGuid().ToString("N")[..10]; var (status, body) = await Send(HttpMethod.Post, "/api/v1/identity/users", new { login, password = "Str0ng!Passw0rd", displayName = login }); status.Should().Be(HttpStatusCode.OK, body); return Json(body).GetProperty("id").GetInt64(); } private async Task<(HttpStatusCode Status, string Body)> Send(HttpMethod method, string path, object? content = null, string? key = null) { var (status, body, _) = await SendReplay(method, path, content, key); return (status, body); } private async Task<(HttpStatusCode Status, string Body, bool Replayed)> SendReplay(HttpMethod method, string path, object? content, string? key) { var request = new HttpRequestMessage(method, path) { Content = content is null ? null : JsonContent.Create(content) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); if (key is not null) request.Headers.Add("Idempotency-Key", key); var response = await _http.SendAsync(request); var replayed = response.Headers.TryGetValues("Idempotency-Replayed", out var values) && values.Single() == "true"; return (response.StatusCode, await response.Content.ReadAsStringAsync(), replayed); } private static HttpRequestMessage Dcr(object body, string key) { var request = new HttpRequestMessage(HttpMethod.Post, "/connect/register") { Content = JsonContent.Create(body) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ProductionHttpFixture.DynamicRegAccessToken); request.Headers.Add("Idempotency-Key", key); return request; } private static JsonElement Json(string body) => JsonDocument.Parse(body).RootElement; } Path: redb-identity/tests/redb.Identity.Tests/FullStack/LogoutG10Tests.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/LogoutG10Tests.cs ---- using System.Net; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using OtpNet; using redb.Core; 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.FullStack; /// /// G10 DoD — HTTP-level pins on session lifecycle & logout semantics (C7 + C8): /// /// Successful MFA verify creates a brand-new row with /// =true — there is no prior session to /// rotate (no session cookie is issued before MFA passes), so "session-id rotation" /// collapses to "session creation gated on the second factor". /// POST /connect/logout with a valid session cookie: /// emits a Max-Age=0 Set-Cookie for the session cookie and flips the /// underlying to "revoked" in the PROPS store. /// /// Authorization/refresh-token cascade is pinned by /// . /// [Collection("ProductionHttp")] public sealed class LogoutG10Tests { private readonly ProductionHttpFixture _fx; public LogoutG10Tests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task MfaVerify_CreatesNewSessionRow_WithMfaVerifiedTrue() { var (login, password, secretBase32, userId) = await SeedMfaUserAsync(); var sessionsBefore = await _fx.Redb.Query() .WhereRedb(o => o.Key == userId) .ToListAsync(); sessionsBefore.Should().BeEmpty( "C7: no server-side session row exists for a user who has only entered a password"); var jar = new CookieContainer(); using var client = CreateClient(jar); await client.PostAsync("/login", Form(new() { ["username"] = login, ["password"] = password })); // Password-only submit must NOT create a session row — the backend only gates a // SessionProps insert on successful MFA verify (see MfaVerifyProcessor). var midFlow = await _fx.Redb.Query() .WhereRedb(o => o.Key == userId) .ToListAsync(); midFlow.Should().BeEmpty("post-password pre-MFA must not create a server-side session"); var code = GenerateValidTotp(secretBase32); await client.PostAsync("/mfa", Form(new() { ["code"] = code })); var afterMfa = await _fx.Redb.Query() .WhereRedb(o => o.Key == userId) .ToListAsync(); afterMfa.Should().HaveCount(1, "MFA verify creates exactly one session row"); afterMfa[0].Props.MfaVerified.Should().BeTrue( "session row must record that the second factor was satisfied"); afterMfa[0].Props.Status.Should().Be("active"); } [Fact] public async Task Logout_ClearsSessionCookie_AndMarksSessionRowRevoked() { var jar = new CookieContainer(); using var client = CreateClient(jar); // Login with the shared MFA-free user — we want a session cookie without the MFA detour. var loginResp = await client.PostAsync("/login", Form(new() { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword })); ((int)loginResp.StatusCode).Should().BeOneOf(200, 302); HasSessionCookie(jar).Should().BeTrue("sanity — login must issue the session cookie"); // Capture the active session row id BEFORE logout so we can verify it was flipped to 'revoked'. // We can resolve userId via TestUserId helper, but the fixture does not expose it — just // query active sessions we newly created (there may be residue from other tests; take the // max id which is guaranteed newer than any previous snapshot). var activeBefore = await _fx.Redb.Query() .Where(s => s.Status == "active") .ToListAsync(); var ourSession = activeBefore.OrderByDescending(s => s.id).FirstOrDefault(); ourSession.Should().NotBeNull("login must have inserted at least one active session row"); // Perform logout via POST /connect/logout (cookie jar auto-forwards the session cookie). Without an // id_token_hint the OP asks the browser to confirm first; LogoutFlow posts the page's state back. var logoutResp = await LogoutFlow.ConfirmAsync(client, await client.PostAsync("/connect/logout", Form(new()))); // The endpoint may either render the Signed-Out page (200) or redirect to the post-logout URI. ((int)logoutResp.StatusCode).Should().BeOneOf(200, 302); // The server must emit a Max-Age=0 Set-Cookie for the session cookie. With the cookie // jar tracking lifetime automatically, the cookie is removed from the jar after expiry. HasSessionCookie(jar).Should().BeFalse( "logout must emit a Max-Age=0 Set-Cookie that evicts the session cookie from the UA"); // And the underlying SessionProps row must be marked revoked (LogoutProcessor → // SessionService.LogoutAsync cascades to all of the user's active sessions). var reloaded = await _fx.Redb.LoadAsync(ourSession!.id); reloaded.Should().NotBeNull(); reloaded!.Props.Status.Should().Be("revoked", "logout must flip SessionProps.Status to 'revoked' for server-side enforcement"); } // ── helpers ── private HttpClient CreateClient(CookieContainer jar) => new(new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = jar, UseCookies = true }) { BaseAddress = new Uri(_fx.BaseUrl) }; private static FormUrlEncodedContent Form(Dictionary kv) => new(kv); private bool HasSessionCookie(CookieContainer jar) { foreach (System.Net.Cookie c in jar.GetCookies(new Uri(_fx.BaseUrl))) { if (c.Name.EndsWith("redb.identity.session", StringComparison.Ordinal) && !string.IsNullOrEmpty(c.Value)) return true; } return false; } private static string GenerateValidTotp(string base32Secret) { var key = Base32Encoding.ToBytes(base32Secret); var totp = new Totp(key, step: 30, totpSize: 6); return totp.ComputeTotp(); } private async Task<(string Login, string Password, string SecretBase32, long UserId)> SeedMfaUserAsync() { var login = $"mfa-g10-{Guid.NewGuid():N}".Substring(0, 24); var password = "Mfa@G10#Test123!"; var secretBase32 = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(20)); var coreUser = await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = login, Password = password, Name = login, Email = $"{login}@example.com", Phone = "+1999000111", Enabled = true }); var protector = _fx.ServiceProvider.GetRequiredService(); var mfaObj = new RedbObject(new MfaProps { Enabled = true, DefaultMethod = "totp", TotpSecret = protector.Protect(secretBase32), TotpConfirmed = true }); mfaObj.name = login; mfaObj.key = coreUser.Id; await _fx.Redb.SaveAsync(mfaObj); return (login, password, secretBase32, coreUser.Id); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/ManagementConflictStatusTests.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/ManagementConflictStatusTests.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.FullStack; /// /// A request that is well formed but cannot be carried out against the current state is a conflict /// and is answered 409 on every management endpoint; a record that does not exist is 404. Neither is /// the 400 of a malformed request. /// [Collection("ProductionHttp")] public class ManagementConflictStatusTests { private readonly ProductionHttpFixture _fx; private readonly ITestOutputHelper _out; public ManagementConflictStatusTests(ProductionHttpFixture fx, ITestOutputHelper output) { _fx = fx; _out = output; } [Fact] public async Task Role_SecondCreateOfTheSameName_Answers409() { var body = new { name = "conflict-role-" + Guid.NewGuid().ToString("N")[..12], audience = "organization" }; using var first = await SendAsync(HttpMethod.Post, "/api/v1/identity/roles", body); ((int)first.StatusCode).Should().BeInRange(200, 299, await first.Content.ReadAsStringAsync()); using var second = await SendAsync(HttpMethod.Post, "/api/v1/identity/roles", body); ((int)second.StatusCode).Should().Be(409, await second.Content.ReadAsStringAsync()); } [Fact] public async Task Role_DeleteOfARoleThatDoesNotExist_Answers404() { using var response = await SendAsync(HttpMethod.Delete, "/api/v1/identity/roles/987654321012", body: null); ((int)response.StatusCode).Should().Be(404, await response.Content.ReadAsStringAsync()); } [Fact] public async Task Role_DeleteOfASystemRole_Answers409() { var name = "conflict-system-role-" + Guid.NewGuid().ToString("N")[..12]; var roleId = await _fx.UseRedbAsync(async redb => { var role = await new RoleService(redb).CreateRoleAsync( name, "organization", applicationId: null, displayName: null, description: null, isSystem: true); return role.Id; }); using var response = await SendAsync(HttpMethod.Delete, $"/api/v1/identity/roles/{roleId}", body: null); ((int)response.StatusCode).Should().Be(409, await response.Content.ReadAsStringAsync()); } [Fact] public async Task ClaimDefinition_SecondCreateOfTheSameClaim_Answers409() { var body = new { claimName = "conflict_claim_" + Guid.NewGuid().ToString("N")[..12], scope = "global", type = "string", required = false, }; using var first = await SendAsync(HttpMethod.Post, "/api/v1/identity/claim-definitions", body); var created = await first.Content.ReadAsStringAsync(); ((int)first.StatusCode).Should().BeInRange(200, 299, created); try { using var second = await SendAsync(HttpMethod.Post, "/api/v1/identity/claim-definitions", body); ((int)second.StatusCode).Should().Be(409, await second.Content.ReadAsStringAsync()); } finally { // A global definition takes part in every registration of the fixture: remove it. using var json = JsonDocument.Parse(created); if (json.RootElement.TryGetProperty("id", out var id)) { using var removed = await SendAsync(HttpMethod.Delete, $"/api/v1/identity/claim-definitions/{id}", body: null); } } } private Task SendAsync(HttpMethod method, string path, object? body) { var request = new HttpRequestMessage(method, path); if (body is not null) request.Content = JsonContent.Create(body); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return _fx.Http.SendAsync(request); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/ManagementDeleteAcrossResourcesTests.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/ManagementDeleteAcrossResourcesTests.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.FullStack; /// /// A management DELETE removes a record of its own resource and nothing else. Given the id of a record /// of another resource it answers 404 and that record stays: the scopes that guard each resource /// (applications.write, groups.write, …) mean nothing if one of them can remove the records of another. /// [Collection("ProductionHttp")] public class ManagementDeleteAcrossResourcesTests { private readonly ProductionHttpFixture _fx; private readonly ITestOutputHelper _out; public ManagementDeleteAcrossResourcesTests(ProductionHttpFixture fx, ITestOutputHelper output) { _fx = fx; _out = output; } [Theory] [InlineData("applications")] [InlineData("scopes")] [InlineData("claim-definitions")] [InlineData("roles")] [InlineData("claim-mappers")] [InlineData("claim-scopes")] public async Task DeletingAGroupsIdThroughAnotherResource_LeavesTheGroup(string resource) { var groupId = await CreateAsync("/api/v1/identity/groups", new { name = "cross-delete-" + Guid.NewGuid().ToString("N")[..12] }); using var delete = await SendAsync(HttpMethod.Delete, $"/api/v1/identity/{resource}/{groupId}", null); var answer = await delete.Content.ReadAsStringAsync(); _out.WriteLine($"DELETE /{resource}/{groupId} (a group) -> [{(int)delete.StatusCode}] {answer}"); using var still = await SendAsync(HttpMethod.Get, $"/api/v1/identity/groups/{groupId}", null); ((int)still.StatusCode).Should().Be(200, $"the group must survive a DELETE on /{resource}"); ((int)delete.StatusCode).Should().Be(404, answer); } [Fact] public async Task DeletingARolesIdThroughGroups_LeavesTheRole() { var roleId = await CreateAsync("/api/v1/identity/roles", new { name = "cross-delete-role-" + Guid.NewGuid().ToString("N")[..12], audience = "organization" }); using var delete = await SendAsync(HttpMethod.Delete, $"/api/v1/identity/groups/{roleId}", null); var answer = await delete.Content.ReadAsStringAsync(); _out.WriteLine($"DELETE /groups/{roleId} (a role) -> [{(int)delete.StatusCode}] {answer}"); using var still = await SendAsync(HttpMethod.Get, $"/api/v1/identity/roles/{roleId}", null); ((int)still.StatusCode).Should().Be(200, "the role must survive a DELETE on /groups"); ((int)delete.StatusCode).Should().Be(404, answer); } private async Task CreateAsync(string path, object body) { using var response = await SendAsync(HttpMethod.Post, path, body); var answer = await response.Content.ReadAsStringAsync(); ((int)response.StatusCode).Should().BeInRange(200, 299, answer); return JsonDocument.Parse(answer).RootElement.GetProperty("id").ToString(); } private Task SendAsync(HttpMethod method, string path, object? body) { var request = new HttpRequestMessage(method, path); if (body is not null) request.Content = JsonContent.Create(body); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return _fx.Http.SendAsync(request); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/ManagementMissingRecordTests.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/ManagementMissingRecordTests.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.FullStack; /// /// A management request that names a record which does not exist is answered 404. It is never a /// server error: the caller asked for something that is not there, the server did not fail. /// [Collection("ProductionHttp")] public class ManagementMissingRecordTests { private const string MissingId = "987654321012"; private readonly ProductionHttpFixture _fx; private readonly ITestOutputHelper _out; public ManagementMissingRecordTests(ProductionHttpFixture fx, ITestOutputHelper output) { _fx = fx; _out = output; } public static IEnumerable Requests() => new[] { new object?[] { "PUT", $"/api/v1/identity/roles/{MissingId}", """{"displayName":"x"}""" }, new object?[] { "PUT", $"/api/v1/identity/groups/{MissingId}", """{"name":"x"}""" }, new object?[] { "POST", $"/api/v1/identity/groups/{MissingId}/children", """{"name":"child-of-nothing"}""" }, new object?[] { "POST", $"/api/v1/identity/groups/{MissingId}/move", """{"newParentGroupId":987654321013}""" }, new object?[] { "GET", $"/api/v1/identity/groups/{MissingId}/path", null }, new object?[] { "GET", $"/api/v1/identity/groups/{MissingId}/children", null }, new object?[] { "POST", $"/api/v1/identity/groups/{MissingId}/members", """{"userId":1}""" }, new object?[] { "GET", $"/api/v1/identity/groups/{MissingId}", null }, new object?[] { "GET", $"/api/v1/identity/groups/{MissingId}/tree", null }, new object?[] { "PUT", $"/api/v1/identity/groups/{MissingId}/members/1", """{"role":"member"}""" }, new object?[] { "GET", $"/api/v1/identity/roles/{MissingId}", null }, new object?[] { "PUT", $"/api/v1/identity/users/{MissingId}", """{"displayName":"x"}""" }, new object?[] { "PUT", $"/api/v1/identity/applications/{MissingId}", """{"displayName":"x"}""" }, new object?[] { "PUT", $"/api/v1/identity/scopes/{MissingId}", """{"displayName":"x"}""" }, new object?[] { "PUT", $"/api/v1/identity/claim-definitions/{MissingId}", """{"displayName":"x"}""" }, new object?[] { "PUT", $"/api/v1/identity/federation-providers/{MissingId}", """{"displayName":"x"}""" }, new object?[] { "DELETE", $"/api/v1/identity/federation-providers/{MissingId}", null }, new object?[] { "DELETE", $"/api/v1/identity/users/{MissingId}", null }, new object?[] { "DELETE", $"/api/v1/identity/applications/{MissingId}", null }, new object?[] { "DELETE", $"/api/v1/identity/scopes/{MissingId}", null }, new object?[] { "DELETE", $"/api/v1/identity/claim-definitions/{MissingId}", null }, new object?[] { "DELETE", $"/api/v1/identity/groups/{MissingId}", null }, new object?[] { "GET", $"/api/v1/identity/groups/{MissingId}/members", null }, new object?[] { "GET", $"/api/v1/identity/groups/{MissingId}/members/1/check", null }, }; [Theory] [MemberData(nameof(Requests))] public async Task ARecordThatDoesNotExist_IsAnswered404(string method, string path, string? body) { using var request = new HttpRequestMessage(new HttpMethod(method), path); if (body is not null) request.Content = new StringContent(body, System.Text.Encoding.UTF8, "application/json"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); using var response = await _fx.Http.SendAsync(request); var answer = await response.Content.ReadAsStringAsync(); _out.WriteLine($"MISSING {method} {path} -> [{(int)response.StatusCode}] {(answer.Length > 200 ? answer[..200] : answer)}"); ((int)response.StatusCode).Should().Be(404, answer); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/ManagementResultWireTests.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/ManagementResultWireTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.RegularExpressions; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// The management API's answers as bytes on the wire, one case per kind of result body: the error document, /// the success answers with their optional members, the revoked count and the token prune results. The /// expected strings are what these routes answered before their bodies became declared types in /// redb.Identity.Contracts; a renamed member, a reordered one or a null that starts being written fails here. /// [Collection("ProductionHttp")] public class ManagementResultWireTests { private readonly ProductionHttpFixture _fx; public ManagementResultWireTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Not_found_is_the_error_document() { var (status, body) = await SendAsync(HttpMethod.Get, "/api/v1/identity/applications/987654321"); status.Should().Be(HttpStatusCode.NotFound); body.Should().Be("""{"error":"not_found","error_description":"Application not found"}"""); } [Fact] public async Task A_validation_refusal_is_the_error_document() { var (status, body) = await SendAsync(HttpMethod.Post, "/api/v1/identity/scopes", new { name = "bad name!" }); status.Should().Be(HttpStatusCode.BadRequest); Regex.IsMatch(body, """^\{"error":"validation_error","error_description":"[^"]+"\}$""").Should().BeTrue(body); } [Fact] public async Task A_missing_token_is_the_error_document_with_its_id() { var (status, body) = await SendAsync(HttpMethod.Delete, "/api/v1/identity/tokens/987654321"); status.Should().Be(HttpStatusCode.NotFound); body.Should().Be("""{"error":"not_found","error_description":"Token 987654321 not found"}"""); } [Fact] public async Task Deleting_a_scope_answers_success_alone() { var name = "wire_" + Guid.NewGuid().ToString("N")[..10]; var (createStatus, created) = await SendAsync(HttpMethod.Post, "/api/v1/identity/scopes", new { name }); createStatus.Should().Be(HttpStatusCode.OK, created); var id = Id(created); var (status, body) = await SendAsync(HttpMethod.Delete, $"/api/v1/identity/scopes/{id}"); status.Should().Be(HttpStatusCode.OK); body.Should().Be("""{"success":true}"""); } [Fact] public async Task Deleting_a_user_answers_success_and_the_sessions_revoked() { var id = await CreateUserAsync(); var (status, body) = await SendAsync(HttpMethod.Delete, $"/api/v1/identity/users/{id}"); status.Should().Be(HttpStatusCode.OK); body.Should().Be("""{"success":true,"sessionsRevoked":0}"""); } [Fact] public async Task Admin_password_reset_answers_success_and_the_sessions_revoked() { var id = await CreateUserAsync(); var (status, body) = await SendAsync(HttpMethod.Post, $"/api/v1/identity/users/{id}/admin-reset-password", new { id = long.Parse(id), newPassword = "Reset1234Pass!x" }); status.Should().Be(HttpStatusCode.OK, body); body.Should().Be("""{"success":true,"sessionsRevoked":0}"""); } [Fact] public async Task Revoking_a_subjects_tokens_answers_the_count() { var id = await CreateUserAsync(); var (status, body) = await SendAsync(HttpMethod.Post, "/api/v1/identity/tokens/revoke-by-subject", new { userId = id }); status.Should().Be(HttpStatusCode.OK, body); body.Should().Be("""{"revokedCount":0}"""); } [Fact] public async Task Revoking_a_consent_answers_success_and_the_count() { var id = await CreateUserAsync(); var (status, body) = await SendAsync(HttpMethod.Delete, $"/api/v1/identity/consents?userId={id}&applicationId=987654321"); status.Should().Be(HttpStatusCode.OK, body); body.Should().Be("""{"success":true,"revoked":0}"""); var (allStatus, all) = await SendAsync(HttpMethod.Delete, $"/api/v1/identity/consents/all?userId={id}"); allStatus.Should().Be(HttpStatusCode.OK, all); all.Should().Be("""{"success":true,"revoked":0}"""); } [Fact] public async Task A_prune_preview_answers_what_it_would_prune() { var (status, body) = await SendAsync(HttpMethod.Post, "/api/v1/identity/tokens/prune?dryRun=true"); status.Should().Be(HttpStatusCode.OK, body); Regex.IsMatch(body, """^\{"dryRun":true,"wouldPruneTokens":\d+,"wouldPruneAuthorizations":\d+,"threshold":"[^"]+"\}$""") .Should().BeTrue(body); } [Fact] public async Task A_prune_answers_what_it_pruned() { var (status, body) = await SendAsync(HttpMethod.Post, "/api/v1/identity/tokens/prune"); status.Should().Be(HttpStatusCode.OK, body); Regex.IsMatch(body, """^\{"prunedTokens":\d+,"prunedAuthorizations":\d+\}$""").Should().BeTrue(body); } private async Task CreateUserAsync() { var login = "wire-" + Guid.NewGuid().ToString("N")[..10]; var (status, body) = await SendAsync(HttpMethod.Post, "/api/v1/identity/users", new { login, password = "Str0ng!Passw0rd", displayName = login }); status.Should().Be(HttpStatusCode.OK, body); return Id(body); } private async Task<(HttpStatusCode Status, string Body)> SendAsync(HttpMethod method, string path, object? content = null) { using var request = new HttpRequestMessage(method, path); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); if (content is not null) request.Content = JsonContent.Create(content); using var response = await _fx.Http.SendAsync(request); return (response.StatusCode, await response.Content.ReadAsStringAsync()); } private static string Id(string json) { using var document = JsonDocument.Parse(json); var id = document.RootElement.GetProperty("id"); return id.ValueKind == JsonValueKind.Number ? id.GetInt64().ToString() : id.GetString()!; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/ManagementTokenStatusTests.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/ManagementTokenStatusTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using OpenIddict.Abstractions; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Core.Stores; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// The management API accepts an access token only while its stored entry is valid: a token revoked at the /// revocation endpoint, or one whose client was deleted, is answered 401 from then on. /// /// The check reads only the token's object row: value_bool is true while the token is valid and false once it /// is not. A row written before that mirror existed (NULL) is checked by the full read of the entry. /// /// [Collection("ProductionHttp")] public class ManagementTokenStatusTests { private const string Secret = "status-secret-value-1234"; private readonly ProductionHttpFixture _fx; public ManagementTokenStatusTests(ProductionHttpFixture fx) => _fx = fx; private async Task<(string ClientId, string Id)> CreateClientAsync() { var clientId = "status-" + Guid.NewGuid().ToString("N")[..12]; using var create = new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/applications") { Content = JsonContent.Create(new { clientId, clientSecret = Secret, clientType = "confidential", displayName = "Token status", permissions = new[] { "ept:token", "ept:revocation", "gt:client_credentials", "scp:identity:read" }, }), }; create.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); using var created = await _fx.Http.SendAsync(create); var body = await created.Content.ReadAsStringAsync(); ((int)created.StatusCode).Should().BeInRange(200, 299, body); return (clientId, JsonDocument.Parse(body).RootElement.GetProperty("id").GetString()!); } private async Task TokenAsync(string clientId) { using var response = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = clientId, ["client_secret"] = Secret, ["scope"] = "identity:read", })); var body = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(HttpStatusCode.OK, body); return JsonDocument.Parse(body).RootElement.GetProperty("access_token").GetString()!; } private async Task ListApplicationsAsync(string token) { using var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications?offset=0&count=1"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); using var response = await _fx.Http.SendAsync(request); return response.StatusCode; } [Fact] public async Task A_revoked_access_token_is_refused_by_the_management_api() { var (clientId, id) = await CreateClientAsync(); var token = await TokenAsync(clientId); (await ListApplicationsAsync(token)).Should().Be(HttpStatusCode.OK); (await TokenRowAsync(id)).value_bool.Should().BeTrue("a valid token's row carries the mirror"); using var revoke = await _fx.Http.PostAsync("/connect/revocation", new FormUrlEncodedContent(new Dictionary { ["token"] = token, ["token_type_hint"] = "access_token", ["client_id"] = clientId, ["client_secret"] = Secret, })); revoke.StatusCode.Should().Be(HttpStatusCode.OK, await revoke.Content.ReadAsStringAsync()); (await TokenRowAsync(id)).value_bool.Should().BeFalse(); (await ListApplicationsAsync(token)).Should().Be(HttpStatusCode.Unauthorized); } [Fact] public async Task A_token_of_a_deleted_client_is_refused_by_the_management_api() { var (clientId, id) = await CreateClientAsync(); var token = await TokenAsync(clientId); (await ListApplicationsAsync(token)).Should().Be(HttpStatusCode.OK); using var delete = new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/identity/applications/{id}"); delete.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); using var deleted = await _fx.Http.SendAsync(delete); ((int)deleted.StatusCode).Should().BeInRange(200, 299, await deleted.Content.ReadAsStringAsync()); (await ListApplicationsAsync(token)).Should().Be(HttpStatusCode.Unauthorized); } // The one access token the client got (client_credentials, one token request per test). private async Task> TokenRowAsync(string applicationId) { var appId = long.Parse(applicationId); var rows = await _fx.Redb.Query().WhereRedb(o => o.ValueLong == appId).ToListAsync(); rows.Should().ContainSingle(); return rows[0]; } [Fact] public async Task A_redeemed_token_is_refused_by_the_management_api() { var (clientId, id) = await CreateClientAsync(); var token = await TokenAsync(clientId); (await ListApplicationsAsync(token)).Should().Be(HttpStatusCode.OK); var row = await TokenRowAsync(id); TokenStatus.Set(row, OpenIddictConstants.Statuses.Redeemed); await _fx.Redb.SaveAsync(row); (await TokenRowAsync(id)).value_bool.Should().BeFalse(); (await ListApplicationsAsync(token)).Should().Be(HttpStatusCode.Unauthorized); } [Fact] public async Task A_deleted_token_entry_is_refused_by_the_management_api() { var (clientId, id) = await CreateClientAsync(); var token = await TokenAsync(clientId); (await ListApplicationsAsync(token)).Should().Be(HttpStatusCode.OK); var row = await TokenRowAsync(id); await IdentityDeletionHelper.DeleteAsync(_fx.Redb, null, row.id); (await ListApplicationsAsync(token)).Should().Be(HttpStatusCode.Unauthorized); } [Fact] public async Task A_row_written_before_the_mirror_is_checked_by_its_status() { var (clientId, id) = await CreateClientAsync(); var token = await TokenAsync(clientId); // As written by a build before the mirror: value_bool NULL, status valid in the values. var row = await TokenRowAsync(id); row.value_bool = null; await _fx.Redb.SaveAsync(row); (await TokenRowAsync(id)).value_bool.Should().BeNull(); (await ListApplicationsAsync(token)).Should().Be(HttpStatusCode.OK); // Revoked by such a build: the status moved, value_bool stayed NULL. The test writes past the helper here on // purpose (the guard scans the product sources only). row = await TokenRowAsync(id); row.Props.Status = OpenIddictConstants.Statuses.Revoked; row.value_bool = null; await _fx.Redb.SaveAsync(row); (await TokenRowAsync(id)).value_bool.Should().BeNull(); (await ListApplicationsAsync(token)).Should().Be(HttpStatusCode.Unauthorized); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/ManagementTokenWithoutIdTests.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/ManagementTokenWithoutIdTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Nodes; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.JsonWebTokens; using Microsoft.IdentityModel.Tokens; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// An access token without the token id claim, validly signed by the server's own key, is not tied to a stored /// entry, so the entry check passes it, as OpenIddict's built-in entry steps pass it (RestoreTokenEntryProperties /// returns when the principal has no token id; ValidateTokenEntry runs only once a token id is resolved). The /// server itself always stores its tokens and puts the id into each one; a token without it can only be made /// with the server's signing key. The same token with its id is refused once the entry is revoked. /// [Collection("ProductionHttp")] public class ManagementTokenWithoutIdTests { private const string Secret = "no-id-secret-value-1234"; private readonly ProductionHttpFixture _fx; public ManagementTokenWithoutIdTests(ProductionHttpFixture fx) => _fx = fx; private async Task CreateClientAsync() { var clientId = "no-id-" + Guid.NewGuid().ToString("N")[..12]; using var create = new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/applications") { Content = JsonContent.Create(new { clientId, clientSecret = Secret, clientType = "confidential", displayName = "Token without id", permissions = new[] { "ept:token", "ept:revocation", "gt:client_credentials", "scp:identity:read" }, }), }; create.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); using var created = await _fx.Http.SendAsync(create); ((int)created.StatusCode).Should().BeInRange(200, 299, await created.Content.ReadAsStringAsync()); return clientId; } private async Task TokenAsync(string clientId) { using var response = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = clientId, ["client_secret"] = Secret, ["scope"] = "identity:read", })); var body = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(HttpStatusCode.OK, body); return JsonDocument.Parse(body).RootElement.GetProperty("access_token").GetString()!; } private async Task ListApplicationsAsync(string token) { using var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications?offset=0&count=1"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); using var response = await _fx.Http.SendAsync(request); return response.StatusCode; } // The issued token's payload signed again with the server's own key, optionally without the token id claim. private string Resign(string issued, bool dropTokenId) { var handler = new JsonWebTokenHandler(); var original = handler.ReadJsonWebToken(issued); var payload = JsonNode.Parse(Base64UrlEncoder.Decode(original.EncodedPayload))!.AsObject(); payload.ContainsKey(OpenIddictConstants.Claims.Private.TokenId).Should().BeTrue("the server puts the id into each token"); if (dropTokenId) payload.Remove(OpenIddictConstants.Claims.Private.TokenId); var options = _fx.ServiceProvider.GetRequiredService>().CurrentValue; var credentials = options.SigningCredentials.FirstOrDefault(c => c.Key.KeyId == original.Kid) ?? options.SigningCredentials.First(); return handler.CreateToken(payload.ToJsonString(), credentials, new Dictionary { [JwtHeaderParameterNames.Typ] = original.Typ }); } [Fact] public async Task A_signed_access_token_without_a_token_id_is_not_checked_against_the_store() { var clientId = await CreateClientAsync(); var issued = await TokenAsync(clientId); var withId = Resign(issued, dropTokenId: false); var withoutId = Resign(issued, dropTokenId: true); (await ListApplicationsAsync(issued)).Should().Be(HttpStatusCode.OK); (await ListApplicationsAsync(withId)).Should().Be(HttpStatusCode.OK, "the server's key signs a token it accepts"); (await ListApplicationsAsync(withoutId)).Should().Be(HttpStatusCode.OK); using var revoke = await _fx.Http.PostAsync("/connect/revocation", new FormUrlEncodedContent(new Dictionary { ["token"] = issued, ["token_type_hint"] = "access_token", ["client_id"] = clientId, ["client_secret"] = Secret, })); revoke.StatusCode.Should().Be(HttpStatusCode.OK, await revoke.Content.ReadAsStringAsync()); (await ListApplicationsAsync(issued)).Should().Be(HttpStatusCode.Unauthorized); (await ListApplicationsAsync(withId)).Should().Be(HttpStatusCode.Unauthorized, "the id ties the token to its revoked entry"); (await ListApplicationsAsync(withoutId)).Should().Be(HttpStatusCode.OK, "a token without an id is not tied to an entry; the built-in entry steps pass it too"); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/MeMfaResultWireTests.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/MeMfaResultWireTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using System.Text.RegularExpressions; using AwesomeAssertions; using OtpNet; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// The self-service MFA answers (/api/v1/identity/me/mfa) as bytes on the wire, for a fresh user with an /// identity:account token: status, TOTP setup, a refused and an accepted confirm, recovery code regeneration /// and disable. Taken on the dictionary answers before they become declared types; the types must write the same. /// [Collection("ProductionHttp")] public class MeMfaResultWireTests { private const string Base = "/api/v1/identity/me/mfa"; private const string Codes = """\["[^"]+"(,"[^"]+"){9}\]"""; private readonly ProductionHttpFixture _fx; public MeMfaResultWireTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task The_self_service_mfa_answers_keep_their_shapes() { var token = await UserTokenAsync(); var (_, status) = await Send(token, HttpMethod.Get, Base, null, HttpStatusCode.OK); status.Should().Be("""{"enabled":false,"methods":[],"recovery_codes_remaining":0}"""); var (_, setup) = await Send(token, HttpMethod.Post, $"{Base}/setup", new { method = "totp" }, HttpStatusCode.OK); Match(setup, """^\{"method":"totp","secret_base32":"[A-Z2-7]+","qr_uri":"otpauth://totp/[^"]+","setup_token":"[^"]+"\}$"""); var secret = Json(setup).GetProperty("secret_base32").GetString()!; var setupToken = Json(setup).GetProperty("setup_token").GetString()!; var (_, refused) = await Send(token, HttpMethod.Post, $"{Base}/confirm", new { method = "totp", code = "000000", setup_token = setupToken }, HttpStatusCode.BadRequest); refused.Should().Be("""{"error":"invalid_code","error_description":"Invalid verification code"}"""); var code = new Totp(Base32Encoding.ToBytes(secret)).ComputeTotp(); var (_, confirmed) = await Send(token, HttpMethod.Post, $"{Base}/confirm", new { method = "totp", code, setup_token = setupToken }, HttpStatusCode.OK); Match(confirmed, $$"""^\{"confirmed":true,"recovery_codes":{{Codes}}\}$"""); var (_, regenerated) = await Send(token, HttpMethod.Post, $"{Base}/recovery-codes", null, HttpStatusCode.OK); Match(regenerated, $$"""^\{"recovery_codes":{{Codes}}\}$"""); var (_, after) = await Send(token, HttpMethod.Get, Base, null, HttpStatusCode.OK); after.Should().Be("""{"enabled":true,"methods":["totp"],"recovery_codes_remaining":10}"""); var (_, disabled) = await Send(token, HttpMethod.Delete, $"{Base}/totp", null, HttpStatusCode.OK); disabled.Should().Be("""{"disabled":true}"""); } [Fact] public async Task The_self_service_email_answers_keep_their_shapes() { var token = await UserTokenAsync(); var address = "memfa-" + Guid.NewGuid().ToString("N")[..8] + "@example.test"; var (_, setup) = await Send(token, HttpMethod.Post, $"{Base}/setup", new { method = "email", destination = address }, HttpStatusCode.OK); Match(setup, """^\{"method":"email","secret_base32":null,"qr_uri":null,"setup_token":"[^"]+","masked_email":"m\*\*\*@example\.test","mfa_state":"[^"]+"\}$"""); var (_, limited) = await Send(token, HttpMethod.Post, $"{Base}/setup", new { method = "email", destination = address }, HttpStatusCode.TooManyRequests); Match(limited, """^\{"error":"rate_limited","error_description":"Too many codes requested; retry after \d+ seconds"\}$"""); var (_, invalid) = await Send(token, HttpMethod.Post, $"{Base}/setup", new { method = "email", destination = "not-an-address" }, HttpStatusCode.BadRequest); invalid.Should().Be("""{"error":"invalid_request","error_description":"Invalid email address"}"""); var code = _fx.Emails.ForRecipient(address).Single().Vars["code"]; var (_, confirmed) = await Send(token, HttpMethod.Post, $"{Base}/confirm", new { method = "email", code, mfa_state = Json(setup).GetProperty("mfa_state").GetString(), setup_token = Json(setup).GetProperty("setup_token").GetString(), }, HttpStatusCode.OK); Match(confirmed, $$"""^\{"confirmed":true,"recovery_codes":{{Codes}}\}$"""); var (_, disabled) = await Send(token, HttpMethod.Delete, $"{Base}/email", null, HttpStatusCode.OK); disabled.Should().Be("""{"disabled":true}"""); } private async Task UserTokenAsync() { var login = "memfa-" + Guid.NewGuid().ToString("N")[..10]; const string password = "Str0ng!Passw0rd"; await Send(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/users", new { login, password, displayName = login }, HttpStatusCode.OK); // A client of this test that may ask for identity:account with the password grant. var clientId = login + "-client"; const string clientSecret = "memfa-client-secret-1234"; await Send(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/applications", new { clientId, clientSecret, displayName = clientId, permissions = new[] { "ept:token", "gt:password", "scp:openid", "scp:identity:account" }, }, HttpStatusCode.OK); var response = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = login, ["password"] = password, ["scope"] = "openid identity:account", ["client_id"] = clientId, ["client_secret"] = clientSecret, })); var body = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(HttpStatusCode.OK, body); return Json(body).GetProperty("access_token").GetString()!; } private async Task<(HttpStatusCode Status, string Body)> Send( string token, HttpMethod method, string path, object? content, HttpStatusCode expected) { using var request = new HttpRequestMessage(method, path) { Content = content is null ? null : JsonContent.Create(content) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); using var response = await _fx.Http.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(expected, $"{method} {path}: {body}"); return (response.StatusCode, body); } private static void Match(string body, string pattern) => Regex.IsMatch(body, pattern).Should().BeTrue(body); private static JsonElement Json(string body) => JsonDocument.Parse(body).RootElement; } Path: redb-identity/tests/redb.Identity.Tests/FullStack/MeSessionsRevokeOthersTests.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/MeSessionsRevokeOthersTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// W6 — full-stack coverage for DELETE /api/v1/identity/me/sessions/others. /// /// Closes the gap called out by : /// the processor-level unit tests can only assert the precondition gates, while the /// happy path (list → revoke-each → audit event) requires the wired SessionService and /// a token carrying the correct sub / sid claims. That can only be exercised /// through the actual HTTP pipeline. /// /// /// Two paths are pinned: /// /// /// A token with a sid claim (issued via the interactive auth code + PKCE flow) /// revokes every session of the caller except the one bound to sid. /// /// /// A token without a sid claim revokes all sessions of the caller — /// the documented contract for non-OIDC-session grants (e.g. password / client_credentials /// style flows). The endpoint must NOT short-circuit with /// 400 sid_unavailable here. /// /// /// /// [Collection("ProductionHttp")] public sealed class MeSessionsRevokeOthersTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public MeSessionsRevokeOthersTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } [Fact] public async Task RevokeOthers_TokenWithSid_KeepsCurrentSessionOnly() { // 1. Obtain a user-bound access token through the interactive auth code + PKCE // flow. AttachSessionPrincipalHandler stamps the resulting principal with a // sid claim → the access token carries sid = current session id. var (accessToken, sessionId) = await IssueAccessTokenWithSidAsync(); sessionId.Should().BeGreaterThan(0, "auth code flow must produce a sid-bound session"); // 2. Seed two extra sessions for the same user so revoke-others has actual work // to do. Direct SessionService.CreateAsync is the standard side-channel used // in FullStackSessionTests and bypasses the OIDC machinery. var sessionService = new SessionService(_fx.Redb); var coreUser = await _fx.Redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername) ?? throw new InvalidOperationException("Test user missing"); var app = await _fx.Redb.Query() .Where(p => p.ClientId == ProductionHttpFixture.TestPublicClientId) .FirstOrDefaultAsync() ?? throw new InvalidOperationException("Public PKCE client not seeded"); var extra1 = await sessionService.CreateAsync(coreUser.Id, app.id); var extra2 = await sessionService.CreateAsync(coreUser.Id, app.id); try { // 3. Verify list endpoint sees all three sessions (current + 2 extras). var beforeIds = await ListSessionIdsAsync(accessToken); beforeIds.Should().Contain(new[] { sessionId, extra1.id, extra2.id }, "all three sessions must be visible before revoke-others is called"); // 4. Fire DELETE /me/sessions/others. Endpoint MUST revoke extra1 + extra2 // while keeping the sid-bound current session alive. using var req = WithAuth( new HttpRequestMessage(HttpMethod.Delete, "/api/v1/identity/me/sessions/others"), accessToken); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, "revoke-others must succeed (got {0}: {1})", resp.StatusCode, await resp.Content.ReadAsStringAsync()); var body = await ParseJsonAsync(resp); body.GetProperty("success").GetBoolean().Should().BeTrue(); body.GetProperty("revoked").GetInt32().Should().BeGreaterThanOrEqualTo(2, "extra1 and extra2 must be counted as revoked; current session must not"); // 5. Verify the post-state: current is still listed, extras are gone. var afterIds = await ListSessionIdsAsync(accessToken); afterIds.Should().Contain(sessionId, "the sid-bound current session must survive revoke-others"); afterIds.Should().NotContain(extra1.id, "extra1 must be revoked by revoke-others"); afterIds.Should().NotContain(extra2.id, "extra2 must be revoked by revoke-others"); } finally { // Best-effort cleanup so subsequent tests start clean even on failure. try { await sessionService.RevokeAsync(extra1.id); } catch { /* already revoked */ } try { await sessionService.RevokeAsync(extra2.id); } catch { /* already revoked */ } try { await sessionService.RevokeAsync(sessionId); } catch { /* may have been collected */ } } } [Fact] public async Task RevokeOthers_TokenWithoutSid_RevokesAllUserSessions() { // Tokens issued via grants that do NOT go through AttachSessionPrincipalHandler // (password grant on the confidential client) carry no sid. Contract: revoke- // others on such a token revokes EVERY session of the caller — never returns // 400 sid_unavailable for the others variant. var accessToken = await IssueAccessTokenViaPasswordGrantAsync(); if (accessToken is null) return; // password grant disabled in this env — soft skip. var sessionService = new SessionService(_fx.Redb); var coreUser = await _fx.Redb.UserProvider.GetUserByLoginAsync(ProductionHttpFixture.TestUsername) ?? throw new InvalidOperationException("Test user missing"); var app = await _fx.Redb.Query() .Where(p => p.ClientId == ProductionHttpFixture.TestPublicClientId) .FirstOrDefaultAsync() ?? throw new InvalidOperationException("Public PKCE client not seeded"); var s1 = await sessionService.CreateAsync(coreUser.Id, app.id); var s2 = await sessionService.CreateAsync(coreUser.Id, app.id); try { using var req = WithAuth( new HttpRequestMessage(HttpMethod.Delete, "/api/v1/identity/me/sessions/others"), accessToken); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, "revoke-others MUST succeed even without sid (got {0}: {1})", resp.StatusCode, await resp.Content.ReadAsStringAsync()); var body = await ParseJsonAsync(resp); body.GetProperty("success").GetBoolean().Should().BeTrue(); body.GetProperty("revoked").GetInt32().Should().BeGreaterThanOrEqualTo(2, "both seeded sessions must be counted as revoked"); var remaining = await ListSessionIdsAsync(accessToken); remaining.Should().NotContain(s1.id, "no-sid revoke-others must revoke s1"); remaining.Should().NotContain(s2.id, "no-sid revoke-others must revoke s2"); } finally { try { await sessionService.RevokeAsync(s1.id); } catch { /* already revoked */ } try { await sessionService.RevokeAsync(s2.id); } catch { /* already revoked */ } } } // ────────────────── helpers ────────────────── private static HttpRequestMessage WithAuth(HttpRequestMessage request, string token) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); return request; } private async Task ListSessionIdsAsync(string accessToken) { using var req = WithAuth( new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/me/sessions"), accessToken); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, "GET /me/sessions must succeed (got {0}: {1})", resp.StatusCode, await resp.Content.ReadAsStringAsync()); var json = await ParseJsonAsync(resp); json.ValueKind.Should().Be(JsonValueKind.Array); var ids = new List(); foreach (var item in json.EnumerateArray()) { if (item.TryGetProperty("sessionId", out var sidProp)) ids.Add(sidProp.GetInt64()); } return ids.ToArray(); } /// /// Drives /login → /connect/authorize → /connect/token with PKCE and the /// identity:account scope so the resulting access token carries both sub /// (caller id) and sid (current session id). /// private async Task<(string accessToken, long sessionId)> IssueAccessTokenWithSidAsync() { var (verifier, challenge) = GeneratePkce(); var code = await AuthorizeAsync( ProductionHttpFixture.TestPublicClientId, challenge, scope: "openid identity:account"); code.Should().NotBeNullOrEmpty("authorize must produce a code"); var resp = await _http.PostAsync("/connect/token", new FormUrlEncodedContent( new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code!, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["code_verifier"] = verifier, })); resp.StatusCode.Should().Be(HttpStatusCode.OK, "token exchange failed: {0}", await resp.Content.ReadAsStringAsync()); var json = await ParseJsonAsync(resp); var accessToken = json.GetProperty("access_token").GetString()!; // Decode the unencrypted access token to read the sid claim. The fixture starts // OpenIddict with DisableAccessTokenEncryption() so the JWT payload is readable. var sid = ExtractSidClaim(accessToken); sid.Should().HaveValue("identity:account access token issued via the auth-code flow MUST carry a sid claim"); return (accessToken, sid!.Value); } private async Task IssueAccessTokenViaPasswordGrantAsync() { var resp = await _http.PostAsync("/connect/token", new FormUrlEncodedContent( new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["scope"] = "openid identity:account", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, })); if (!resp.IsSuccessStatusCode) return null; // password grant not granted to identity:account in this env var json = await ParseJsonAsync(resp); return json.GetProperty("access_token").GetString(); } private async Task AuthorizeAsync(string clientId, string challenge, string scope) { var cookieJar = new System.Net.CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookieJar, UseCookies = true, }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; var loginResp = await client.PostAsync("/login", new FormUrlEncodedContent( new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); cookieJar.Count.Should().BeGreaterThan(0, "login must set a session cookie (got {0}: {1})", loginResp.StatusCode, await loginResp.Content.ReadAsStringAsync()); var form = new Dictionary { ["response_type"] = "code", ["client_id"] = clientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = scope, ["code_challenge"] = challenge, ["code_challenge_method"] = "S256", }; var resp = await client.PostAsync("/connect/authorize", new FormUrlEncodedContent(form)); if (resp.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found) { var location = resp.Headers.Location?.ToString(); location.Should().NotBeNull(); return ExtractQueryParam(location!, "code"); } var json = await ParseJsonAsync(resp); if (json.TryGetProperty("code", out var c)) return c.GetString(); if (json.TryGetProperty("error", out var err)) throw new InvalidOperationException( $"Authorize error: {err.GetString()} — " + (json.TryGetProperty("error_description", out var d) ? d.GetString() : "(no description)")); throw new InvalidOperationException($"Unexpected authorize response: {json.GetRawText()}"); } private static (string verifier, string challenge) GeneratePkce() { var bytes = new byte[32]; System.Security.Cryptography.RandomNumberGenerator.Fill(bytes); var verifier = Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash).TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } private static async Task ParseJsonAsync(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } private static string? ExtractQueryParam(string url, string param) { var idx = url.IndexOf('?'); if (idx < 0) return null; foreach (var pair in url[(idx + 1)..].Split('&')) { var kv = pair.Split('=', 2); if (kv[0] == param) return Uri.UnescapeDataString(kv[1]); } return null; } /// /// Reads the sid claim out of an unencrypted JWT access token by base64url- /// decoding the payload segment. The fixture configures /// DisableAccessTokenEncryption(), so this is sufficient — no key material /// is needed (signature is not verified here, we trust the issuer that just minted it). /// private static long? ExtractSidClaim(string jwt) { var parts = jwt.Split('.'); if (parts.Length < 2) return null; var payload = parts[1].Replace('-', '+').Replace('_', '/'); switch (payload.Length % 4) { case 2: payload += "=="; break; case 3: payload += "="; break; } var json = JsonDocument.Parse(Convert.FromBase64String(payload)).RootElement; if (!json.TryGetProperty("sid", out var sidProp)) return null; return sidProp.ValueKind switch { JsonValueKind.String => long.TryParse(sidProp.GetString(), out var s) ? s : null, JsonValueKind.Number => sidProp.TryGetInt64(out var n) ? n : null, _ => null, }; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/MeWebAuthnAuditEventTests.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/MeWebAuthnAuditEventTests.cs ---- using AwesomeAssertions; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// The audit event a self-service WebAuthn operation leaves on the exchange, with the real MfaService and database of /// the fixture. An operation that records its own event (credential-delete: MfaWebAuthnRevoked) keeps it; the /// generic MfaSelfService:webauthn:* event goes only to operations that record none. Before, the generic event /// overwrote the specific one, so MfaWebAuthnRevoked and MfaWebAuthnRegistered never reached the audit /// from self-service. register-complete takes the same branch; it is not driven here because it needs a real /// authenticator attestation. /// [Collection("ProductionHttp")] public class MeWebAuthnAuditEventTests { private readonly ProductionHttpFixture _fx; public MeWebAuthnAuditEventTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Deleting_a_credential_records_MfaWebAuthnRevoked() { var userId = await SeedCredentialAsync("k1"); var exchange = await RunAsync(userId, "credential-delete", new Dictionary { ["key"] = "k1" }); exchange.Properties["identity-event-type"].Should().Be(IdentityAuditEventIds.MfaWebAuthnRevoked); } [Fact] public async Task Listing_credentials_still_records_the_generic_self_service_event() { var userId = await SeedCredentialAsync("k1"); var exchange = await RunAsync(userId, "credentials", new Dictionary()); exchange.Properties["identity-event-type"].Should().Be("MfaSelfService:webauthn:credentials"); } private async Task RunAsync(long userId, string operation, Dictionary body) { var exchange = new Exchange(new Message { Body = body }); exchange.In.Headers["operation"] = operation; exchange.Properties["identity:management-user-id"] = userId; await new MeWebAuthnProcessor(_fx.ServiceProvider).Process(exchange); return exchange; } private Task SeedCredentialAsync(string key) => _fx.UseRedbAsync(async redb => { var userId = 900_000_000L + Random.Shared.Next(1, 99_999_999); await redb.SaveAsync(new RedbObject(new MfaProps { Enabled = true, DefaultMethod = "webauthn", WebAuthnCredentials = new Dictionary { [key] = new() { CredentialId = [1, 2, 3], PublicKey = [4, 5, 6], DisplayName = "Laptop", RegisteredAt = DateTimeOffset.UtcNow }, }, }) { key = userId, }); return userId; }); } Path: redb-identity/tests/redb.Identity.Tests/FullStack/MfaStateCookieG5Tests.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/MfaStateCookieG5Tests.cs ---- using System.Net; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using OtpNet; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// G5 DoD — HTTP-level checks pinning the B3/B5/B7 transport & single-use contracts: /// /// POST /mfa without the __Host-redb.identity.mfa cookie never issues a session. /// Same jti+code replayed → second submission does not create a second session /// (idempotent-consumer dedupe at route level, keyed by mfa-verify:{jti}:{code}). /// The encrypted mfa_state blob carries only an OTP jti reference — /// never the plaintext OTP code (B3 contract; regression guard for state-leak scenarios). /// /// [Collection("ProductionHttp")] public sealed class MfaStateCookieG5Tests { private readonly ProductionHttpFixture _fx; public MfaStateCookieG5Tests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task MfaVerify_WithoutStateCookie_DoesNotIssueSession() { var (login, password, secretBase32) = await SeedMfaUserAsync(); // Step 1 — login with one cookie jar to obtain a valid mfa-state cookie (sanity). var jar1 = new CookieContainer(); using (var c1 = CreateClient(jar1)) { var loginResp = await c1.PostAsync("/login", Form(new() { ["username"] = login, ["password"] = password })); loginResp.StatusCode.Should().Be(HttpStatusCode.Redirect); HasMfaStateCookie(jar1).Should().BeTrue("sanity — login must set the mfa-state cookie"); } // Step 2 — attacker-style request: POST /mfa from an EMPTY cookie jar with a // forged-looking TOTP code but NO __Host-redb.identity.mfa cookie at all. var jar2 = new CookieContainer(); using var c2 = CreateClient(jar2); var code = GenerateValidTotp(secretBase32); var verifyResp = await c2.PostAsync("/mfa", Form(new() { ["code"] = code })); HasSessionCookie(jar2).Should().BeFalse( "no session cookie may be issued for a verify request that carries no mfa-state cookie"); } [Fact] public async Task MfaVerify_SameJtiReplayed_SecondCallDoesNotIssueAnotherSession() { var (login, password, secretBase32) = await SeedMfaUserAsync(); var jar = new CookieContainer(); using var client = CreateClient(jar); await client.PostAsync("/login", Form(new() { ["username"] = login, ["password"] = password })); HasMfaStateCookie(jar).Should().BeTrue(); // Capture the mfa-state cookie value BEFORE we submit it — a successful verify // clears the cookie (Max-Age=0), so we need to replay it by hand on a fresh client. var mfaStateCookieValue = MfaStateCookieValue(jar)!; // Make both client jars so that the first verify's session-cookie-set does not // contaminate the replay client (we want to observe cookies independently). var code = GenerateValidTotp(secretBase32); var jar1 = new CookieContainer(); using (var c1 = CreateClient(jar1)) { // Inject the captured mfa-state cookie manually. jar1.Add(new Uri(_fx.BaseUrl), new System.Net.Cookie( MfaStateCookieName(), mfaStateCookieValue) { HttpOnly = true }); var resp1 = await c1.PostAsync("/mfa", Form(new() { ["code"] = code })); HasSessionCookie(jar1).Should().BeTrue("first verify must succeed"); } // Now replay the SAME jti (same cookie value) + SAME code on a fresh jar. // IdempotentConsumer keyed by mfa-verify:{jti}:{code} with skipDuplicate=true — // the processor must NOT issue a brand-new session for the replay. var jar2 = new CookieContainer(); using (var c2 = CreateClient(jar2)) { jar2.Add(new Uri(_fx.BaseUrl), new System.Net.Cookie( MfaStateCookieName(), mfaStateCookieValue) { HttpOnly = true }); var resp2 = await c2.PostAsync("/mfa", Form(new() { ["code"] = code })); // The route-level IdempotentConsumer is registered with skipDuplicate=true, so // the second call skips MfaVerifyProcessor entirely and no Set-Cookie for the // session cookie is emitted. Anything else would let an attacker who captured // the mfa-state cookie mint additional sessions at will. HasSessionCookie(jar2).Should().BeFalse( "replayed jti+code must not mint a second session"); } } [Fact] public void MfaStateBlob_DoesNotCarryPlaintextOtpCode() { // B3 / G5 §7 regression guard: the encrypted mfa_state blob is the only artefact that // travels in the cookie, and it MUST only reference the OTP by jti — never include the // plaintext code. This is what keeps `OTP not in URL/logs` true even if a correlation // logger inadvertently logs the state cookie. var state = new MfaState { UserId = 42, Username = "alice", OtpJti = Guid.NewGuid(), OtpMethod = "sms", OtpExpiresAt = DateTimeOffset.UtcNow.AddMinutes(5), ReturnUrl = "/", IssuedAt = DateTimeOffset.UtcNow, Jti = Guid.NewGuid() }; var json = System.Text.Json.JsonSerializer.Serialize(state); json.Should().NotContain("OtpCode", "MfaState must not carry OTP plaintext (B3)"); json.Should().NotContain("otpCode"); // Also pin the reflection-level contract so future refactors that add a plaintext // OTP property back onto MfaState trip this test. var propNames = typeof(MfaState) .GetProperties() .Select(p => p.Name) .ToArray(); propNames.Should().NotContain("OtpCode"); propNames.Should().NotContain("Code"); propNames.Should().Contain("OtpJti"); } // ── helpers ── private HttpClient CreateClient(CookieContainer jar) => new(new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = jar, UseCookies = true }) { BaseAddress = new Uri(_fx.BaseUrl) }; private static FormUrlEncodedContent Form(Dictionary kv) => new(kv); private bool HasSessionCookie(CookieContainer jar) { foreach (System.Net.Cookie c in jar.GetCookies(new Uri(_fx.BaseUrl))) { if (c.Name.EndsWith("redb.identity.session", StringComparison.Ordinal) && !string.IsNullOrEmpty(c.Value)) return true; } return false; } private bool HasMfaStateCookie(CookieContainer jar) { foreach (System.Net.Cookie c in jar.GetCookies(new Uri(_fx.BaseUrl))) { if (c.Name.EndsWith("redb.identity.mfa", StringComparison.Ordinal) && !string.IsNullOrEmpty(c.Value)) return true; } return false; } private string MfaStateCookieName() => "redb.identity.mfa"; private string? MfaStateCookieValue(CookieContainer jar) { foreach (System.Net.Cookie c in jar.GetCookies(new Uri(_fx.BaseUrl))) { if (c.Name.EndsWith("redb.identity.mfa", StringComparison.Ordinal)) return c.Value; } return null; } private static string GenerateValidTotp(string base32Secret) { var key = Base32Encoding.ToBytes(base32Secret); var totp = new Totp(key, step: 30, totpSize: 6); return totp.ComputeTotp(); } private async Task<(string Login, string Password, string SecretBase32)> SeedMfaUserAsync() { var login = $"mfa-g5-{Guid.NewGuid():N}".Substring(0, 24); var password = "Mfa@G5#Test123!"; var secretBase32 = Base32Encoding.ToString(KeyGeneration.GenerateRandomKey(20)); var coreUser = await _fx.Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = login, Password = password, Name = login, Email = $"{login}@example.com", Phone = "+1999000111", Enabled = true }); var protector = _fx.ServiceProvider.GetRequiredService(); var mfaObj = new RedbObject(new MfaProps { Enabled = true, DefaultMethod = "totp", TotpSecret = protector.Protect(secretBase32), TotpConfirmed = true }); mfaObj.name = login; mfaObj.key = coreUser.Id; await _fx.Redb.SaveAsync(mfaObj); return (login, password, secretBase32); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/NativeConsentE2ETests.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/NativeConsentE2ETests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Sessions B-2 + B-3 (N-2 Native Consent) — end-to-end coverage of: /// • the X-Identity-Delegate-Consent header content-negotiation on /// /connect/authorize (B-2); /// • the full authorize → consent_required → POST /consent → resume /// authorize → POST /connect/token happy-path (B-3), exercising the /// same host-side /consent form endpoint that /// BackchannelOidcClient.RecordConsentGrantAsync calls in production. /// /// All tests run against the real OpenIddict pipeline + redb-backed stores + /// real PostgreSQL via . /// [Collection("ProductionHttp")] public sealed class NativeConsentE2ETests : IAsyncLifetime { private const string ConsentClientId = ProductionHttpFixture.TestConsentClientId; private readonly ProductionHttpFixture _fx; public NativeConsentE2ETests(ProductionHttpFixture fx) { _fx = fx; } /// /// Tests share a fixture, and the happy-path test creates an OpenIddict /// Authorization row that — if it survives between tests — silences the /// consent gate that the header-negotiation tests rely on. We delete any /// pre-existing authorization for the test client at the start of every /// test so order does not matter. /// public async Task InitializeAsync() { var appManager = _fx.ServiceProvider.GetRequiredService(); var authManager = _fx.ServiceProvider.GetRequiredService(); var app = await appManager.FindByClientIdAsync(ConsentClientId); if (app is null) return; var appId = await appManager.GetIdAsync(app); if (appId is null) return; // Delete every authorization tied to this client, regardless of subject. // Subject linkage on AuthorizationProps now lives in value_guid (the public sub // GUID); enumerating by application id alone sidesteps any lookup-by-subject // edge case and keeps the cleanup robust for header-negotiation tests. await foreach (var auth in authManager.FindByApplicationIdAsync(appId)) { await authManager.TryRevokeAsync(auth); await authManager.DeleteAsync(auth); } } public Task DisposeAsync() => Task.CompletedTask; [Fact] public async Task AuthorizeWithDelegateHeader_ReturnsConsentRequiredJson() { var (cookieJar, client) = await NewLoggedInClient(); var resp = await PostAuthorize(client, delegateHeader: "1"); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest, "delegate header must short-circuit the legacy 302 to /consent and return a machine-readable error instead. Body: {0}", await resp.Content.ReadAsStringAsync()); resp.Content.Headers.ContentType?.MediaType.Should().Be("application/json"); var json = await ParseJsonAsync(resp); json.GetProperty("error").GetString().Should().Be("consent_required"); json.GetProperty("clientId").GetString().Should().Be(ConsentClientId); json.GetProperty("appName").GetString().Should().NotBeNullOrEmpty(); json.GetProperty("scopes").GetArrayLength().Should().BeGreaterThan(0); json.GetProperty("userId").GetString().Should().NotBeNullOrEmpty(); json.GetProperty("returnUrl").GetString().Should().NotBeNullOrEmpty(); } [Fact] public async Task AuthorizeWithDelegateHeaderTrueLiteral_AlsoReturnsJson() { var (_, client) = await NewLoggedInClient(); var resp = await PostAuthorize(client, delegateHeader: "True"); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest, "the header value matcher must accept both \"1\" and \"true\" — case-insensitive. Body: {0}", await resp.Content.ReadAsStringAsync()); resp.Content.Headers.ContentType?.MediaType.Should().Be("application/json"); } [Fact] public async Task AuthorizeWithoutDelegateHeader_StillReturnsLegacyConsentRedirect() { var (_, client) = await NewLoggedInClient(); var resp = await PostAuthorize(client, delegateHeader: null); // Legacy behaviour: 302 to the host's /consent HTML page. We do not pin // the exact target (host may render inline or redirect) — only that we // did NOT get the new JSON shape. Status must be either a redirect or // a 200 (host rendered the consent page inline); anything else means // the delegate-header branch leaked into the no-header path. ((int)resp.StatusCode).Should().BeOneOf(new[] { 200, 302, 303 }, "without the delegate header, native JSON branch must NOT activate. Got {0}: {1}", resp.StatusCode, await resp.Content.ReadAsStringAsync()); if (resp.StatusCode is HttpStatusCode.OK) { // Inline-rendered host consent page is HTML, not JSON. resp.Content.Headers.ContentType?.MediaType.Should().NotBe("application/json"); } } [Fact] public async Task HappyPath_AuthorizeThenGrantConsentThenResumeThenToken_YieldsAccessAndIdToken() { // ─── Step 1: log in (session cookie) ─── var (_, client) = await NewLoggedInClient(); // ─── Step 2: GET /connect/authorize with delegate header → 400 JSON consent_required ─── // Use GET (not POST) because the host reconstructs returnUrl from the request // line, and our resume step needs that returnUrl to carry the original PKCE + // OIDC params. This is exactly what BackchannelOidcClient does in production. var (verifier, challenge) = GeneratePkce(); var state = "b3-happy-state"; var nonce = "b3-happy-nonce"; var authorizeQuery = $"response_type=code" + $"&client_id={Uri.EscapeDataString(ConsentClientId)}" + $"&redirect_uri={Uri.EscapeDataString(ProductionHttpFixture.TestRedirectUri)}" + $"&scope={Uri.EscapeDataString("openid profile")}" + $"&state={state}" + $"&nonce={nonce}" + $"&code_challenge={challenge}" + $"&code_challenge_method=S256"; using (var consentReq = new HttpRequestMessage(HttpMethod.Get, "/connect/authorize?" + authorizeQuery)) { consentReq.Headers.Add("X-Identity-Delegate-Consent", "1"); var consentResp = await client.SendAsync(consentReq); consentResp.StatusCode.Should().Be(HttpStatusCode.BadRequest, "expected consent_required JSON, got body: {0}", await consentResp.Content.ReadAsStringAsync()); var json = await ParseJsonAsync(consentResp); json.GetProperty("error").GetString().Should().Be("consent_required"); var returnUrl = json.GetProperty("returnUrl").GetString(); returnUrl.Should().NotBeNullOrEmpty(); returnUrl!.Should().StartWith("/connect/authorize?"); var scopes = string.Join(' ', json.GetProperty("scopes").EnumerateArray().Select(s => s.GetString())); // ─── Step 3: POST /consent (decision=allow) — mirrors RecordConsentGrantAsync ─── // Host records the authorization (creates Authorization row) and responds // with a 302 to returnUrl on success. var consentForm = new FormUrlEncodedContent(new Dictionary { ["client_id"] = ConsentClientId, ["scopes"] = scopes, ["decision"] = "allow", ["returnUrl"] = returnUrl, }); var grantResp = await client.PostAsync("/consent", consentForm); grantResp.StatusCode.Should().BeOneOf( new[] { HttpStatusCode.Found, HttpStatusCode.SeeOther }, "host /consent allow must respond with a redirect to returnUrl. Body: {0}", await grantResp.Content.ReadAsStringAsync()); grantResp.Headers.Location?.ToString().Should().NotBeNull(); } // ─── Step 4: GET /connect/authorize again (no header) → 302 to redirect_uri?code=… ─── // Authorization row now exists, so OpenIddict skips the consent gate and issues a code. string? code; string? echoedState; using (var resumeReq = new HttpRequestMessage(HttpMethod.Get, "/connect/authorize?" + authorizeQuery)) { var resumeResp = await client.SendAsync(resumeReq); resumeResp.StatusCode.Should().BeOneOf( new[] { HttpStatusCode.Found, HttpStatusCode.SeeOther }, "after consent grant, replay of authorize must redirect to redirect_uri with ?code=… . Body: {0}", await resumeResp.Content.ReadAsStringAsync()); var location = resumeResp.Headers.Location?.ToString(); location.Should().NotBeNull(); location!.Should().StartWith(ProductionHttpFixture.TestRedirectUri); code = ExtractQueryParam(location, "code"); echoedState = ExtractQueryParam(location, "state"); code.Should().NotBeNullOrEmpty("authorize replay must produce a code"); echoedState.Should().Be(state, "state must round-trip unchanged through consent + resume"); } // ─── Step 5: POST /connect/token (code + verifier) → access + id token ─── var tokenForm = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code!, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ConsentClientId, ["code_verifier"] = verifier, }); var tokenResp = await _fx.Http.PostAsync("/connect/token", tokenForm); tokenResp.StatusCode.Should().Be(HttpStatusCode.OK, "token exchange after consent grant must succeed: {0}", await tokenResp.Content.ReadAsStringAsync()); var tokenJson = await ParseJsonAsync(tokenResp); tokenJson.GetProperty("access_token").GetString().Should().NotBeNullOrEmpty(); tokenJson.GetProperty("id_token").GetString().Should().NotBeNullOrEmpty(); tokenJson.GetProperty("token_type").GetString().Should().Be("Bearer"); } // ────────────────── helpers ────────────────── private async Task<(CookieContainer cookies, HttpClient client)> NewLoggedInClient() { var cookies = new CookieContainer(); var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true, }; var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; var loginResp = await client.PostAsync("/login", new FormUrlEncodedContent( new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); // The /login response must set a session cookie regardless of whether // it returns 200 (rendered "logged in" page) or 302 (redirect to next). cookies.Count.Should().BeGreaterThan(0, "login must set the session cookie; got {0}", loginResp.StatusCode); return (cookies, client); } private static async Task PostAuthorize( HttpClient client, string? delegateHeader) { var (_, challenge) = GeneratePkce(); var form = new Dictionary { ["response_type"] = "code", ["client_id"] = ConsentClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid profile", ["code_challenge"] = challenge, ["code_challenge_method"] = "S256", }; using var req = new HttpRequestMessage(HttpMethod.Post, "/connect/authorize") { Content = new FormUrlEncodedContent(form) }; if (delegateHeader is not null) req.Headers.Add("X-Identity-Delegate-Consent", delegateHeader); return await client.SendAsync(req); } private static async Task ParseJsonAsync(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } private static (string verifier, string challenge) GeneratePkce() { var bytes = new byte[32]; System.Security.Cryptography.RandomNumberGenerator.Fill(bytes); var verifier = Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash).TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } private static string? ExtractQueryParam(string url, string key) { var qIdx = url.IndexOf('?'); if (qIdx < 0) return null; foreach (var pair in url[(qIdx + 1)..].Split('&', StringSplitOptions.RemoveEmptyEntries)) { var eq = pair.IndexOf('='); if (eq <= 0) continue; if (Uri.UnescapeDataString(pair[..eq]) == key) return Uri.UnescapeDataString(pair[(eq + 1)..]); } return null; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/OAuthMetadataComplianceTests.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/OAuthMetadataComplianceTests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Z3: RFC 8414 (OAuth 2.0 Authorization Server Metadata) §2 compliance. /// Asserts that /.well-known/oauth-authorization-server — and the equivalent /// /.well-known/openid-configuration document — expose every mandatory field /// with the correct shape. Also verifies that registration_endpoint is advertised /// when DCR is enabled. /// [Collection("ProductionHttp")] public class OAuthMetadataComplianceTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public OAuthMetadataComplianceTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } [Theory] [InlineData("/.well-known/oauth-authorization-server")] [InlineData("/.well-known/openid-configuration")] public async Task Metadata_Document_Declares_All_Mandatory_Fields(string path) { var resp = await _http.GetAsync(path); resp.StatusCode.Should().Be(HttpStatusCode.OK); resp.Content.Headers.ContentType!.MediaType.Should().Be("application/json"); var json = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; // RFC 8414 §2: issuer MUST be a URL using "https" scheme and no query/fragment. json.TryGetProperty("issuer", out var issuer).Should().BeTrue("RFC 8414 §2: issuer REQUIRED"); issuer.ValueKind.Should().Be(JsonValueKind.String); // RFC 8414 §2: authorization_endpoint MUST be present (except for grant_types that do not use it). json.TryGetProperty("authorization_endpoint", out var authEndpoint) .Should().BeTrue("RFC 8414 §2: authorization_endpoint REQUIRED when supported grant types need it"); authEndpoint.ValueKind.Should().Be(JsonValueKind.String); IsAbsoluteHttp(authEndpoint.GetString()!).Should().BeTrue(); // RFC 8414 §2: token_endpoint MUST be present (except for implicit-only servers — we support token grants). json.TryGetProperty("token_endpoint", out var tokenEndpoint) .Should().BeTrue("RFC 8414 §2: token_endpoint REQUIRED when supported grant types use it"); IsAbsoluteHttp(tokenEndpoint.GetString()!).Should().BeTrue(); // RFC 8414 §2: jwks_uri is RECOMMENDED when JWTs are issued (we do). json.TryGetProperty("jwks_uri", out var jwks).Should().BeTrue( "JWTs are issued — jwks_uri RECOMMENDED per RFC 8414 §2"); IsAbsoluteHttp(jwks.GetString()!).Should().BeTrue(); // RFC 8414 §2: response_types_supported — REQUIRED; JSON array of strings. json.TryGetProperty("response_types_supported", out var rts).Should().BeTrue( "RFC 8414 §2: response_types_supported REQUIRED"); rts.ValueKind.Should().Be(JsonValueKind.Array); rts.GetArrayLength().Should().BeGreaterThan(0); // grant_types_supported — OPTIONAL but strongly recommended; if present must include at least one string. if (json.TryGetProperty("grant_types_supported", out var gts)) { gts.ValueKind.Should().Be(JsonValueKind.Array); gts.GetArrayLength().Should().BeGreaterThan(0); } // token_endpoint_auth_methods_supported — RFC 8414 §2 OPTIONAL; when present, array of strings. if (json.TryGetProperty("token_endpoint_auth_methods_supported", out var teams)) { teams.ValueKind.Should().Be(JsonValueKind.Array); } // scopes_supported — RFC 8414 §2 RECOMMENDED; array of strings. if (json.TryGetProperty("scopes_supported", out var scopes)) { scopes.ValueKind.Should().Be(JsonValueKind.Array); scopes.GetArrayLength().Should().BeGreaterThan(0); } } [Fact] public async Task Metadata_Advertises_RegistrationEndpoint_When_Dcr_Enabled() { // ProductionHttpFixture enables dynamic registration → RFC 7591 §3 requires advertising the endpoint. var resp = await _http.GetAsync("/.well-known/oauth-authorization-server"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; json.TryGetProperty("registration_endpoint", out var reg).Should().BeTrue( "RFC 7591 §3: registration_endpoint MUST be advertised when DCR is supported"); IsAbsoluteHttp(reg.GetString()!).Should().BeTrue(); reg.GetString().Should().EndWith("/connect/register"); } [Fact] public async Task Rfc8414_And_Oidc_Metadata_Share_Issuer_And_CoreEndpoints() { var oauth = await GetJson("/.well-known/oauth-authorization-server"); var oidc = await GetJson("/.well-known/openid-configuration"); oauth.GetProperty("issuer").GetString().Should().Be(oidc.GetProperty("issuer").GetString()); oauth.GetProperty("token_endpoint").GetString().Should().Be(oidc.GetProperty("token_endpoint").GetString()); oauth.GetProperty("authorization_endpoint").GetString().Should().Be(oidc.GetProperty("authorization_endpoint").GetString()); oauth.GetProperty("jwks_uri").GetString().Should().Be(oidc.GetProperty("jwks_uri").GetString()); } private static bool IsAbsoluteHttp(string s) => Uri.TryCreate(s, UriKind.Absolute, out var u) && (u.Scheme == "http" || u.Scheme == "https"); private async Task GetJson(string path) { var resp = await _http.GetAsync(path); resp.EnsureSuccessStatusCode(); return JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/PasswordPolicyEnforcementTests.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/PasswordPolicyEnforcementTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Identity.Contracts.Scim; using redb.Identity.Core.Models; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// H10 Phase 4 — full-stack E2E tests for password policy enforcement (history reuse, /// expiration on login, SCIM PATCH gap). Each test creates a fresh user via the admin /// API to avoid coupling with the shared e2e-user fixture (which other tests /// rely on for ROPC happy-path). /// [Collection("ProductionHttp")] public class PasswordPolicyEnforcementTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public PasswordPolicyEnforcementTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } // ════════════════════════════════════════════════════════════════ // History reuse (Phase 2) // ════════════════════════════════════════════════════════════════ [Fact] public async Task ChangePassword_ReusingPreviousPassword_Rejected() { var (login, id, originalPwd) = await CreateUserAsync(); var pwd2 = $"Str0ng!Two{Guid.NewGuid():N}".Substring(0, 16); // Rotate: original → pwd2 → original (must fail because original is in history). await ChangePasswordAsync(id, originalPwd, pwd2) .Expect(HttpStatusCode.OK, "first rotation must succeed"); var resp = await ChangePasswordAsync(id, pwd2, originalPwd); resp.IsSuccessStatusCode.Should().BeFalse( "rotating back to the original password must be blocked by the history check; body={0}", await resp.Content.ReadAsStringAsync()); var body = await resp.Content.ReadAsStringAsync(); body.Should().Contain("last", "policy error must mention the history-window"); } [Fact] public async Task AdminResetAndAdminChange_CheckAndRecordTheHistory_OnTheRoutesConnection() { // Both run on the transacted manage-users route. Their history lookup and record used to open a // connection of their own inside the route's transaction: in a deployment that promoted it to a // distributed transaction, stock PostgreSQL refused it, and the caller got 400 "Id is required". var (_, id, originalPwd) = await CreateUserAsync(); var reset = $"Str0ng!R{Guid.NewGuid():N}".Substring(0, 16); var changed = $"Str0ng!C{Guid.NewGuid():N}".Substring(0, 16); var before = InRouteTransactionHistoryStoreGuard.Violations.Count; await AdminResetPasswordAsync(id, reset).Expect(HttpStatusCode.OK, "the admin reset must succeed"); await ChangePasswordAsync(id, reset, changed).Expect(HttpStatusCode.OK, "the admin change must succeed"); InRouteTransactionHistoryStoreGuard.Violations.Count.Should().Be(before, "no history call may open its own connection inside the route transaction: {0}", string.Join("; ", InRouteTransactionHistoryStoreGuard.Violations)); // The history was read and written on the route's connection: both earlier passwords are refused now. var back = await AdminResetPasswordAsync(id, reset); back.IsSuccessStatusCode.Should().BeFalse("the reset password is in the history; body={0}", await back.Content.ReadAsStringAsync()); (await back.Content.ReadAsStringAsync()).Should().Contain("last", "the refusal names the history window"); var original = await AdminResetPasswordAsync(id, originalPwd); original.IsSuccessStatusCode.Should().BeFalse("the original password is in the history too"); } [Fact] public async Task ChangePassword_BeyondHistoryWindow_Allowed() { // Default HistoryCount = 5 → after 6 distinct rotations, the original drops off // and may be reused again. var (login, id, originalPwd) = await CreateUserAsync(); var passwords = new List { originalPwd }; for (int i = 0; i < 6; i++) { var next = $"Str0ng!{i}xX{Guid.NewGuid():N}".Substring(0, 16); await ChangePasswordAsync(id, passwords[^1], next) .Expect(HttpStatusCode.OK, $"rotation #{i + 1} must succeed"); passwords.Add(next); } // Original password should now be reusable — verify a final rotation back to it. var resp = await ChangePasswordAsync(id, passwords[^1], originalPwd); resp.IsSuccessStatusCode.Should().BeTrue( "after rotating past the history window the original password must be reusable; body={0}", await resp.Content.ReadAsStringAsync()); } // ════════════════════════════════════════════════════════════════ // Expiration on login (Phase 3) — ROPC reject // ════════════════════════════════════════════════════════════════ [Fact] public async Task PasswordGrant_WithExpiredPassword_RejectsWithInvalidGrant() { var (login, id, password) = await CreateUserAsync(); // Backdate PasswordChangedAt so it falls outside MaxAge (default = 90 days). await ForcePasswordExpiredAsync(id); var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = login, ["password"] = password, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid" }); var resp = await _http.PostAsync("/connect/token", content); resp.IsSuccessStatusCode.Should().BeFalse("expired password must not yield a token"); var body = await resp.Content.ReadAsStringAsync(); var json = JsonDocument.Parse(body).RootElement; json.GetProperty("error").GetString().Should().Be("invalid_grant", "ROPC password-expired must surface as invalid_grant; body={0}", body); json.TryGetProperty("error_description", out var desc).Should().BeTrue(); desc.GetString().Should().Contain("expired", "error_description must mention expiration"); } [Fact] public async Task ChangePassword_ResetsExpiration_NextLoginSucceeds() { var (login, id, originalPwd) = await CreateUserAsync(); var newPwd = $"Str0ng!New{Guid.NewGuid():N}".Substring(0, 16); // Mark expired, then change the password — RecordPasswordHistoryAsync also // stamps PasswordChangedAt to now, so the next login should succeed. await ForcePasswordExpiredAsync(id); await ChangePasswordAsync(id, originalPwd, newPwd) .Expect(HttpStatusCode.OK, "rotation under expired password must still succeed via admin API"); var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["username"] = login, ["password"] = newPwd, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, ["scope"] = "openid" }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.OK, "after rotation, login with the new password must succeed; body={0}", await resp.Content.ReadAsStringAsync()); } // ════════════════════════════════════════════════════════════════ // SCIM PATCH password policy gap closure // ════════════════════════════════════════════════════════════════ [Fact] public async Task ScimPatchPassword_WithWeakPassword_Returns400() { var (id, _) = await CreateScimUserAsync(); var patch = new { schemas = new[] { "urn:ietf:params:scim:api:messages:2.0:PatchOp" }, Operations = new object[] { new { op = "replace", path = "password", value = "short" } // 5 chars, no digit/upper/special } }; using var req = ScimRequest(HttpMethod.Patch, $"/scim/v2/Users/{id}"); req.Content = new StringContent(JsonSerializer.Serialize(patch), Encoding.UTF8, "application/scim+json"); var resp = await _http.SendAsync(req); var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest, "SCIM PATCH password must enforce the H10 policy (gap closure); body={0}", body); } [Fact] public async Task ScimPatchPassword_WithStrongPassword_Succeeds() { var (id, _) = await CreateScimUserAsync(); var patch = new { schemas = new[] { "urn:ietf:params:scim:api:messages:2.0:PatchOp" }, Operations = new object[] { new { op = "replace", path = "password", value = "Str0ng!Passw0rdScim" } } }; using var req = ScimRequest(HttpMethod.Patch, $"/scim/v2/Users/{id}"); req.Content = new StringContent(JsonSerializer.Serialize(patch), Encoding.UTF8, "application/scim+json"); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, "policy-compliant SCIM PATCH password must succeed; body={0}", await resp.Content.ReadAsStringAsync()); } // ════════════════════════════════════════════════════════════════ // Helpers // ════════════════════════════════════════════════════════════════ /// /// Creates a fresh admin user via management API. Returns (login, id, password). /// Password is policy-compliant (15 chars, mixed case, digit, special). /// private async Task<(string login, long id, string password)> CreateUserAsync() { var login = $"e2e-pwpol-{Guid.NewGuid():N}".Substring(0, 24); var password = $"Str0ng!P{Guid.NewGuid():N}".Substring(0, 16); var req = new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/users") { Content = JsonContent.Create(new { login, password }) }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, "user create must succeed; body={0}", await resp.Content.ReadAsStringAsync()); var json = await resp.Content.ReadFromJsonAsync(); long id = ExtractId(json); id.Should().BeGreaterThan(0, "create response must include an id"); return (login, id, password); } private static long ExtractId(JsonElement json) { // Response envelopes vary across processors — check common shapes. if (json.ValueKind == JsonValueKind.Object) { if (json.TryGetProperty("id", out var idEl) && idEl.ValueKind == JsonValueKind.Number) return idEl.GetInt64(); if (json.TryGetProperty("Id", out var idEl2) && idEl2.ValueKind == JsonValueKind.Number) return idEl2.GetInt64(); if (json.TryGetProperty("data", out var data)) return ExtractId(data); if (json.TryGetProperty("user", out var user)) return ExtractId(user); } return 0; } private async Task AdminResetPasswordAsync(long userId, string newPwd) { var req = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/identity/users/{userId}/admin-reset-password") { Content = JsonContent.Create(new { id = userId, newPassword = newPwd }) }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return await _http.SendAsync(req); } private async Task ChangePasswordAsync(long userId, string oldPwd, string newPwd) { var req = new HttpRequestMessage(HttpMethod.Post, $"/api/v1/identity/users/{userId}/change-password") { Content = JsonContent.Create(new { id = userId, oldPassword = oldPwd, newPassword = newPwd }) }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return await _http.SendAsync(req); } /// /// Backdates by 200 days so it falls /// outside the default 90-day MaxAge window. Writes the OIDC props row directly via /// PROPS — bypasses the policy hooks, which is exactly what we need to simulate an /// aged account. /// private async Task ForcePasswordExpiredAsync(long userId) { await _fx.UseRedbAsync(async (IRedbService redb) => { var existing = await redb.Query() .WhereRedb(o => o.Key == userId) .FirstOrDefaultAsync(); var aged = DateTimeOffset.UtcNow.AddDays(-200); if (existing is not null) { existing.Props.PasswordChangedAt = aged; await redb.SaveAsync(existing); } else { var fresh = new redb.Core.Models.Entities.RedbObject( new UserProps { PasswordChangedAt = aged }) { key = userId }; await redb.SaveAsync(fresh); } }); } private async Task<(string id, string login)> CreateScimUserAsync() { var tag = Guid.NewGuid().ToString("N").Substring(0, 12); var user = new ScimUser { UserName = $"scim-pwpol-{tag}", DisplayName = $"SCIM PwPol {tag}" }; using var req = ScimRequest(HttpMethod.Post, "/scim/v2/Users"); req.Content = new StringContent(JsonSerializer.Serialize(user), Encoding.UTF8, ScimConstants.MediaType); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.Created, "SCIM POST must succeed; body={0}", await resp.Content.ReadAsStringAsync()); var json = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; return (json.GetProperty("id").GetString()!, user.UserName); } private HttpRequestMessage ScimRequest(HttpMethod method, string path) { var req = new HttpRequestMessage(method, path); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ScimToken); req.Headers.Accept.ParseAdd("application/scim+json"); return req; } } internal static class HttpResponseAssertExtensions { public static async Task Expect( this Task respTask, HttpStatusCode expected, string because) { var resp = await respTask; if (resp.StatusCode != expected) { var body = await resp.Content.ReadAsStringAsync(); throw new Xunit.Sdk.XunitException( $"Expected {(int)expected} {expected} but got {(int)resp.StatusCode} {resp.StatusCode}: {because}\nBody: {body}"); } } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/PkceEnforcementTests.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/PkceEnforcementTests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// C4 — PKCE enforcement (OAuth 2.1 / RFC 7636 §4.2): /// 1. authorize without code_challenge from a public client → invalid_request /// 2. authorize with code_challenge_method=plain → invalid_request /// 3. authorize with code_challenge_method=S256 → success (control case) /// Public clients (no client_secret) are required to use PKCE; only S256 is accepted. /// [Collection("ProductionHttp")] public sealed class PkceEnforcementTests { private readonly ProductionHttpFixture _fx; public PkceEnforcementTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task PublicClient_AuthorizeWithoutCodeChallenge_ReturnsInvalidRequest() { var resp = await PostAuthorizeAsync(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid", // intentionally no code_challenge / code_challenge_method }); await AssertInvalidRequestAsync(resp, "public client authorize without PKCE must be rejected"); } [Fact] public async Task AuthorizeWithPlainCodeChallengeMethod_IsRejected() { var (_, challenge) = GeneratePkce(); var resp = await PostAuthorizeAsync(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid", ["code_challenge"] = challenge, ["code_challenge_method"] = "plain", }); await AssertInvalidRequestAsync(resp, "code_challenge_method=plain must be rejected (OAuth 2.1)"); } [Fact] public async Task AuthorizeWithSha256CodeChallenge_Succeeds() { var (_, challenge) = GeneratePkce(); var resp = await PostAuthorizeAsync(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid", ["code_challenge"] = challenge, ["code_challenge_method"] = "S256", }); // Either a 302 redirect with `?code=...` or 200 JSON containing `code` is acceptable. if (resp.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found) { var location = resp.Headers.Location?.ToString(); location.Should().NotBeNullOrEmpty(); location!.Should().Contain("code=", "authorize with S256 must produce an authorization code"); return; } var body = await resp.Content.ReadAsStringAsync(); resp.IsSuccessStatusCode.Should().BeTrue( "authorize with code_challenge_method=S256 must succeed; got {0}: {1}", resp.StatusCode, body); var json = JsonDocument.Parse(body).RootElement; json.TryGetProperty("code", out var code).Should().BeTrue("response must contain a code"); code.GetString().Should().NotBeNullOrEmpty(); } // ─────────────── helpers ─────────────── private async Task PostAuthorizeAsync(IDictionary form) { // Authenticate first to get a session cookie, otherwise OpenIddict will // bounce us to /login (which would mask the actual PKCE rejection). var cookieJar = new System.Net.CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookieJar, UseCookies = true, }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); return await client.PostAsync("/connect/authorize", new FormUrlEncodedContent(form)); } private static async Task AssertInvalidRequestAsync(HttpResponseMessage resp, string because) { // OpenIddict can either return a 302 with error=invalid_request in the redirect // (when redirect_uri is registered) or a JSON 400. Accept both. if (resp.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found) { var location = resp.Headers.Location?.ToString() ?? ""; location.Should().Contain("error=invalid_request", because); return; } resp.IsSuccessStatusCode.Should().BeFalse(because + $". Got {resp.StatusCode}"); var body = await resp.Content.ReadAsStringAsync(); if (body.Length > 0 && body.TrimStart().StartsWith('{')) { var json = JsonDocument.Parse(body).RootElement; if (json.TryGetProperty("error", out var err)) { err.GetString().Should().Be("invalid_request", because + $". Body: {body}"); } } } private static (string verifier, string challenge) GeneratePkce() { var bytes = new byte[32]; System.Security.Cryptography.RandomNumberGenerator.Fill(bytes); var verifier = Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash).TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } } 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"); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/PushedAuthorizationFullCycleTests.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/PushedAuthorizationFullCycleTests.cs ---- using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Full-cycle E2E test for Pushed Authorization Requests (RFC 9126 / Z6). /// Pipeline: POST /connect/par → GET /connect/authorize?request_uri=… → /// (login + implicit consent) → callback → POST /connect/token → access_token. /// Validates that PAR-issued request_uri is single-use and short-lived per RFC. /// [Collection("ProductionHttp")] public class PushedAuthorizationFullCycleTests { private readonly ProductionHttpFixture _fx; public PushedAuthorizationFullCycleTests(ProductionHttpFixture fx) { _fx = fx; } [Fact] public async Task ParEndpoint_AdvertisedInDiscovery() { var resp = await _fx.Http.GetAsync("/.well-known/openid-configuration"); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.TryGetProperty("pushed_authorization_request_endpoint", out var parEndpoint) .Should().BeTrue("PAR endpoint must be advertised when EnablePushedAuthorization=true"); parEndpoint.GetString().Should().EndWith("/connect/par"); } [Fact] public async Task Par_RejectsRequestWithoutPkce_ForPublicClient() { var parForm = new FormUrlEncodedContent(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid" // intentionally no code_challenge }); var resp = await _fx.Http.PostAsync("/connect/par", parForm); ((int)resp.StatusCode).Should().BeGreaterThanOrEqualTo(400, "PAR for a PKCE-required public client without code_challenge must fail"); var json = await ParseJson(resp); json.TryGetProperty("error", out _).Should().BeTrue(); } [Fact] public async Task Par_FullCycle_ReturnsRequestUri_And_Authorize_With_RequestUri_Yields_Code_And_Token() { var (verifier, challenge) = GeneratePkce(); // ─── Step 1: POST /connect/par — push the authorization parameters ─── var parForm = new FormUrlEncodedContent(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid", ["code_challenge"] = challenge, ["code_challenge_method"] = "S256", ["state"] = "par-e2e-state", ["nonce"] = "par-e2e-nonce" }); var parResp = await _fx.Http.PostAsync("/connect/par", parForm); parResp.StatusCode.Should().Be(HttpStatusCode.Created, "RFC 9126 §2.2 requires 201 Created for a successful PAR response: {0}", await parResp.Content.ReadAsStringAsync()); var parJson = await ParseJson(parResp); parJson.TryGetProperty("request_uri", out var requestUriProp).Should().BeTrue(); var requestUri = requestUriProp.GetString(); requestUri.Should().NotBeNullOrEmpty(); requestUri!.Should().StartWith("urn:ietf:params:oauth:request_uri:", "RFC 9126 §2.2: request_uri MUST use the urn:ietf:params:oauth:request_uri prefix"); parJson.TryGetProperty("expires_in", out var expProp).Should().BeTrue(); expProp.GetInt32().Should().BePositive(); // ─── Step 2: Login (cookie-based session) ─── var cookies = new CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true }; using var browser = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; var loginForm = new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword }); await browser.PostAsync("/login", loginForm); cookies.Count.Should().BeGreaterThan(0, "login must set a session cookie"); // ─── Step 3: GET /connect/authorize?client_id=…&request_uri=… ─── // Per RFC 9126 §4: only client_id + request_uri are required at /authorize; // all other params come from the pushed payload. var authorizeUrl = $"/connect/authorize?client_id={Uri.EscapeDataString(ProductionHttpFixture.TestPublicClientId)}" + $"&request_uri={Uri.EscapeDataString(requestUri)}"; var authResp = await browser.GetAsync(authorizeUrl); string? code; if (authResp.StatusCode == HttpStatusCode.Redirect || authResp.StatusCode == HttpStatusCode.Found) { var location = authResp.Headers.Location?.ToString(); location.Should().NotBeNullOrEmpty("authorize must redirect to redirect_uri"); location!.Should().StartWith(ProductionHttpFixture.TestRedirectUri); code = ExtractQueryParam(location, "code"); ExtractQueryParam(location, "state").Should().Be("par-e2e-state", "state from PAR payload must be echoed back to the client"); } else { authResp.StatusCode.Should().Be(HttpStatusCode.OK, "authorize response: {0}", await authResp.Content.ReadAsStringAsync()); var json = await ParseJson(authResp); json.TryGetProperty("code", out var c).Should().BeTrue(); code = c.GetString(); } code.Should().NotBeNullOrEmpty("authorize must produce an authorization code"); // ─── Step 4: POST /connect/token — exchange code with code_verifier ─── var tokenForm = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code!, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["code_verifier"] = verifier }); var tokenResp = await _fx.Http.PostAsync("/connect/token", tokenForm); tokenResp.StatusCode.Should().Be(HttpStatusCode.OK, "token exchange after PAR must succeed: {0}", await tokenResp.Content.ReadAsStringAsync()); var tokenJson = await ParseJson(tokenResp); tokenJson.TryGetProperty("access_token", out var at).Should().BeTrue(); at.GetString().Should().NotBeNullOrEmpty(); } [Fact] public async Task Par_RequestUri_IsSingleUse() { var (_, challenge) = GeneratePkce(); var parForm = new FormUrlEncodedContent(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid", ["code_challenge"] = challenge, ["code_challenge_method"] = "S256", ["state"] = "single-use-state" }); var parResp = await _fx.Http.PostAsync("/connect/par", parForm); parResp.StatusCode.Should().Be(HttpStatusCode.Created); var requestUri = (await ParseJson(parResp)).GetProperty("request_uri").GetString()!; // Login + first authorize consumes the request_uri var cookies = new CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true }; using var browser = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; await browser.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword })); var url = $"/connect/authorize?client_id={Uri.EscapeDataString(ProductionHttpFixture.TestPublicClientId)}" + $"&request_uri={Uri.EscapeDataString(requestUri)}"; var first = await browser.GetAsync(url); ((int)first.StatusCode).Should().BeLessThan(500, "first /authorize call should not 500: {0}", await first.Content.ReadAsStringAsync()); // Second use of the same request_uri MUST fail (RFC 9126 §6 — single-use) var second = await browser.GetAsync(url); if (second.StatusCode == HttpStatusCode.Redirect || second.StatusCode == HttpStatusCode.Found) { var loc = second.Headers.Location?.ToString() ?? ""; // Either redirected to /login (session-related) or back to redirect_uri with error (loc.Contains("error=") || loc.StartsWith("/login")) .Should().BeTrue("replayed request_uri must not produce a fresh code, got: {0}", loc); } else { ((int)second.StatusCode).Should().BeGreaterThanOrEqualTo(400, "replayed request_uri must be rejected, got status {0}: {1}", second.StatusCode, await second.Content.ReadAsStringAsync()); } } // ─── Helpers ─── private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } private static string? ExtractQueryParam(string url, string param) { var idx = url.IndexOf('?'); if (idx < 0) return null; var query = url[(idx + 1)..]; // Strip fragment if present (response_mode=fragment) var hashIdx = query.IndexOf('#'); if (hashIdx >= 0) query = query[..hashIdx]; foreach (var pair in query.Split('&')) { var kv = pair.Split('=', 2); if (kv.Length == 2 && kv[0] == param) return Uri.UnescapeDataString(kv[1]); } // Try fragment var fragIdx = url.IndexOf('#'); if (fragIdx >= 0) { foreach (var pair in url[(fragIdx + 1)..].Split('&')) { var kv = pair.Split('=', 2); if (kv.Length == 2 && kv[0] == param) return Uri.UnescapeDataString(kv[1]); } } return null; } private static (string verifier, string challenge) GeneratePkce() { var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); var verifier = Convert.ToBase64String(bytes) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = SHA256.HashData(Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash) .TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/RedirectUriValidationTests.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/RedirectUriValidationTests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// C5 — redirect_uri exact-match validation (RFC 6749 §3.1.2 / OAuth 2.1 §4.1). /// Verifies that OpenIddict performs exact (no-substring, no-wildcard) matching /// of the redirect_uri presented at /connect/authorize against the registered set. /// [Collection("ProductionHttp")] public sealed class RedirectUriValidationTests { private readonly ProductionHttpFixture _fx; public RedirectUriValidationTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task AuthorizeWithUnregisteredRedirectUri_IsRejected() { var (_, challenge) = GeneratePkce(); var resp = await PostAuthorizeAsync(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, // Registered URI is "http://localhost/callback"; this is an attacker URI. ["redirect_uri"] = "https://evil.example.com/callback", ["scope"] = "openid", ["code_challenge"] = challenge, ["code_challenge_method"] = "S256", }); await AssertRejectedAsync(resp, "redirect_uri", "unregistered redirect_uri must be rejected (no open redirect)"); } [Fact] public async Task AuthorizeWithRedirectUriExtraQueryParam_IsRejected() { // Exact match: registered URI has no query string. Adding `?evil=1` must // make matching fail, otherwise an attacker could smuggle parameters. var (_, challenge) = GeneratePkce(); var resp = await PostAuthorizeAsync(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri + "?evil=1", ["scope"] = "openid", ["code_challenge"] = challenge, ["code_challenge_method"] = "S256", }); await AssertRejectedAsync(resp, "redirect_uri", "redirect_uri with extra query parameter must not match registered URI"); } // ─────────────── helpers ─────────────── private async Task PostAuthorizeAsync(IDictionary form) { var cookieJar = new CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookieJar, UseCookies = true, }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); return await client.PostAsync("/connect/authorize", new FormUrlEncodedContent(form)); } private static async Task AssertRejectedAsync(HttpResponseMessage resp, string parameterName, string because) { // Critical: the server MUST NOT redirect the browser to the unregistered URI. // It either returns a 4xx with `error=invalid_request` (or similar) JSON, // or shows an error page — but never `Location: `. if (resp.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found or HttpStatusCode.SeeOther) { var location = resp.Headers.Location?.ToString() ?? ""; location.Should().NotContain("evil.example.com", "browser must NOT be redirected to an unregistered URI ({0})", because); location.Should().NotContain("evil=1", "browser must NOT be redirected with attacker-controlled extras ({0})", because); return; } resp.IsSuccessStatusCode.Should().BeFalse( because + $". Got {resp.StatusCode}"); var body = await resp.Content.ReadAsStringAsync(); if (body.Length > 0 && body.TrimStart().StartsWith('{')) { var json = JsonDocument.Parse(body).RootElement; if (json.TryGetProperty("error", out var err)) { var errStr = err.GetString(); errStr.Should().BeOneOf(new[] { "invalid_request", "invalid_client", "unauthorized_client" }, because + $". Body: {body}"); } } } private static (string verifier, string challenge) GeneratePkce() { var bytes = new byte[32]; System.Security.Cryptography.RandomNumberGenerator.Fill(bytes); var verifier = Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash).TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/RefreshTokenReuseDetectionTests.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/RefreshTokenReuseDetectionTests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// C3 — Refresh-token rotation reuse detection: tests the production OpenIddict pipeline /// against the redb-backed token store. Verifies that once a refresh token has been /// rotated (A → B), presenting the original token (A) again is rejected, AND the entire /// token family (including the still-fresh B) is revoked so that a stolen rolling /// refresh token cannot be exchanged even once after the legitimate client has rotated. /// [Collection("ProductionHttp")] public sealed class RefreshTokenReuseDetectionTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; public RefreshTokenReuseDetectionTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } [Fact] public async Task ReusedRefreshToken_RejectsAndRevokesFamily() { // 1. Issue initial refresh token A via auth code flow + offline_access. var (refreshA, _) = await IssueInitialTokensAsync(); // 2. Rotate A → B (legitimate rotation). var rotated1 = await RefreshAsync(refreshA); rotated1.StatusCode.Should().Be(HttpStatusCode.OK, "first rotation must succeed: {0}", await rotated1.Content.ReadAsStringAsync()); var refreshB = (await ParseJsonAsync(rotated1)).GetProperty("refresh_token").GetString()!; refreshB.Should().NotBe(refreshA, "rotation must produce a fresh refresh_token"); // 3. Reuse the now-redeemed A. Per OAuth 2.1 §6.1 the server MUST refuse and // SHOULD revoke the entire token family. OpenIddict surfaces this as either // 400 invalid_grant or 401 (depending on whether it treats redeemed tokens as // a grant failure or an authentication failure) — both are rejections. var reuse = await RefreshAsync(refreshA); reuse.IsSuccessStatusCode.Should().BeFalse( "reusing a redeemed refresh token must be rejected. Got {0}: {1}", reuse.StatusCode, await reuse.Content.ReadAsStringAsync()); // 4. The freshly rotated B must ALSO be invalid now — that is the family revocation // half of the contract. Without this, an attacker who stole A can still use B // (or vice versa) once the legitimate user has already rotated. var attemptUseFamily = await RefreshAsync(refreshB); attemptUseFamily.IsSuccessStatusCode.Should().BeFalse( "after reuse of a redeemed token, every sibling in the family must be revoked. " + "Got {0}: {1}", attemptUseFamily.StatusCode, await attemptUseFamily.Content.ReadAsStringAsync()); } [Fact] public async Task ReusedAncestorAfterMultipleRotations_RevokesEntireChain() { // A → B → C. Reuse B (the middle one). Expect C also revoked. var (refreshA, _) = await IssueInitialTokensAsync(); var resp1 = await RefreshAsync(refreshA); resp1.StatusCode.Should().Be(HttpStatusCode.OK); var refreshB = (await ParseJsonAsync(resp1)).GetProperty("refresh_token").GetString()!; var resp2 = await RefreshAsync(refreshB); resp2.StatusCode.Should().Be(HttpStatusCode.OK); var refreshC = (await ParseJsonAsync(resp2)).GetProperty("refresh_token").GetString()!; // Reuse B (already redeemed when we exchanged it for C). var reuse = await RefreshAsync(refreshB); reuse.IsSuccessStatusCode.Should().BeFalse( "reusing a redeemed refresh token must be rejected. Got {0}: {1}", reuse.StatusCode, await reuse.Content.ReadAsStringAsync()); // The current head of the chain (C) must also be invalidated. var attemptUseC = await RefreshAsync(refreshC); attemptUseC.IsSuccessStatusCode.Should().BeFalse( "ancestor reuse must invalidate the entire chain, including the latest token (C). " + "Got {0}: {1}", attemptUseC.StatusCode, await attemptUseC.Content.ReadAsStringAsync()); } /// /// G7 — RFC 7009 token revocation: posting a refresh_token to /connect/revocation /// must invalidate it so a subsequent refresh_token grant on the same value fails. /// This is the explicit «log out / sign out everywhere» path the spec mandates. /// [Fact] public async Task RevokedRefreshToken_CannotBeUsed_ConfidentialClient() { // Issue refresh token via password grant on the confidential client (RFC 7009 §2.1 // requires client authentication for revocation; public clients cannot revoke). var initial = await _http.PostAsync("/connect/token", new FormUrlEncodedContent( new Dictionary { ["grant_type"] = "password", ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, ["scope"] = "openid offline_access", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, })); if (!initial.IsSuccessStatusCode) return; // password grant not available in this env — skip silently. var refreshToken = (await ParseJsonAsync(initial)).GetProperty("refresh_token").GetString()!; var revoke = await _http.PostAsync("/connect/revocation", new FormUrlEncodedContent( new Dictionary { ["token"] = refreshToken, ["token_type_hint"] = "refresh_token", ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, })); revoke.StatusCode.Should().Be(HttpStatusCode.OK, "RFC 7009 §2.2: revocation must respond 200 — got {0}: {1}", revoke.StatusCode, await revoke.Content.ReadAsStringAsync()); var refresh = await _http.PostAsync("/connect/token", new FormUrlEncodedContent( new Dictionary { ["grant_type"] = "refresh_token", ["refresh_token"] = refreshToken, ["client_id"] = ProductionHttpFixture.TestClientId, ["client_secret"] = ProductionHttpFixture.TestClientSecret, })); refresh.IsSuccessStatusCode.Should().BeFalse( "a revoked refresh_token must no longer be exchangeable. Got {0}: {1}", refresh.StatusCode, await refresh.Content.ReadAsStringAsync()); } // ────────────────── helpers ────────────────── private async Task<(string refreshToken, string accessToken)> IssueInitialTokensAsync() { var (verifier, challenge) = GeneratePkce(); var code = await AuthorizeAsync( ProductionHttpFixture.TestPublicClientId, challenge, "openid offline_access"); var resp = await _http.PostAsync("/connect/token", new FormUrlEncodedContent( new Dictionary { ["grant_type"] = "authorization_code", ["code"] = code!, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["code_verifier"] = verifier, })); resp.StatusCode.Should().Be(HttpStatusCode.OK, "initial token exchange failed: {0}", await resp.Content.ReadAsStringAsync()); var json = await ParseJsonAsync(resp); return (json.GetProperty("refresh_token").GetString()!, json.GetProperty("access_token").GetString()!); } private Task RefreshAsync(string refreshToken) => _http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "refresh_token", ["refresh_token"] = refreshToken, ["client_id"] = ProductionHttpFixture.TestPublicClientId, })); private async Task AuthorizeAsync(string clientId, string challenge, string scope) { // Reproduces FullStackProtocolTests.AuthorizeViaHttp: login first to obtain a // session cookie, then POST /connect/authorize with that cookie. var cookieJar = new System.Net.CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookieJar, UseCookies = true, }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; var loginResp = await client.PostAsync("/login", new FormUrlEncodedContent( new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); cookieJar.Count.Should().BeGreaterThan(0, "login response must set a session cookie"); var form = new Dictionary { ["response_type"] = "code", ["client_id"] = clientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = scope, ["code_challenge"] = challenge, ["code_challenge_method"] = "S256", }; var resp = await client.PostAsync("/connect/authorize", new FormUrlEncodedContent(form)); if (resp.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found) { var location = resp.Headers.Location?.ToString(); location.Should().NotBeNull(); return ExtractQueryParam(location!, "code"); } var json = await ParseJsonAsync(resp); if (json.TryGetProperty("code", out var c)) return c.GetString(); if (json.TryGetProperty("error", out var err)) throw new InvalidOperationException( $"Authorize error: {err.GetString()} — " + (json.TryGetProperty("error_description", out var d) ? d.GetString() : "(no description)")); throw new InvalidOperationException($"Unexpected authorize response: {json.GetRawText()}"); } private static async Task ParseJsonAsync(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } private static (string verifier, string challenge) GeneratePkce() { var bytes = new byte[32]; System.Security.Cryptography.RandomNumberGenerator.Fill(bytes); var verifier = Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash).TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } private static string? ExtractQueryParam(string url, string param) { var idx = url.IndexOf('?'); if (idx < 0) return null; foreach (var pair in url[(idx + 1)..].Split('&')) { var kv = pair.Split('=', 2); if (kv[0] == param) return Uri.UnescapeDataString(kv[1]); } return null; } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/RoleScopeAugmentationTests.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/RoleScopeAugmentationTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// Scopes attached to a role reach a token only when the client asked for them. /// /// Before, AttachRoleRegistryClaims added every scope of the user's roles to every token of that /// user, for any client, after the request had been checked against the client's permissions. A client /// that could not even request identity:manage received an administrator's token carrying it, with /// Identity's own audience, and the management API accepted that token: signing in to any application /// handed it the administration of Identity. Now a role is an entitlement only: the client asks, OpenIddict /// checks the client's permission, and the user's role decides whether a gated scope stays. /// /// [Collection("ProductionHttp")] public sealed class RoleScopeAugmentationTests : IAsyncLifetime { private const string ThirdPartyClientId = "rolescope-third-party"; private const string ThirdPartySecret = "rolescope-third-party-secret-value"; private const string ConsoleClientId = "rolescope-console"; private const string ConsoleSecret = "rolescope-console-secret-value"; private const string ManagementScope = "identity:manage"; private const string RoleName = "rolescope-test-admin"; private const string Password = "RoleScope@Test123!"; private readonly ProductionHttpFixture _fx; private string _admin = null!; private string _plain = null!; public RoleScopeAugmentationTests(ProductionHttpFixture fx) => _fx = fx; public async Task InitializeAsync() { var suffix = Guid.NewGuid().ToString("N")[..8]; _admin = "rolescope-admin-" + suffix; _plain = "rolescope-plain-" + suffix; var manager = _fx.ServiceProvider.GetRequiredService(); // A third-party client: it may sign users in and introspect its own tokens, nothing more. No // scp:identity:manage, so it may not even request the management scope. await EnsureClientAsync(manager, ThirdPartyClientId, ThirdPartySecret, withManagementScope: false); // A console-shaped client: permitted to ask for the management scope, like Identity Web. await EnsureClientAsync(manager, ConsoleClientId, ConsoleSecret, withManagementScope: true); // An administrator through a role that carries the management scope, as the seeded admin role // does, and a user without any role. await _fx.UseRedbAsync(async redb => { var admin = await CreateUserAsync(redb, _admin); await CreateUserAsync(redb, _plain); var svc = new RoleService(redb); var role = await redb.Query() .Where(p => p.Name == RoleName) .Where(p => p.Audience == "organization") .FirstOrDefaultAsync() ?? await svc.CreateRoleAsync(RoleName, "organization", applicationId: null, displayName: "Role scope test admin", description: "Carries identity:manage."); var scope = await redb.Query() .Where(p => p.ScopeName == ManagementScope) .FirstOrDefaultAsync(); if (scope is null) { scope = new RedbObject(new ScopeProps { ScopeName = ManagementScope }) { Name = ManagementScope }; await redb.SaveAsync(scope); } if (!(await svc.ListScopeIdsForRoleAsync(role.Id)).Contains(scope.Id)) await svc.AttachScopeAsync(role.Id, scope.Id, actingUserId: null); await svc.AssignUserAsync(role.Id, admin, actingUserId: null); return 0; }); } public Task DisposeAsync() => Task.CompletedTask; [Fact] public async Task A_client_without_the_permission_gets_no_role_scope_and_its_token_does_not_administer() { var token = await TokenAsync(ThirdPartyClientId, ThirdPartySecret, _admin, "openid"); (await ScopesAsync(token, ThirdPartyClientId, ThirdPartySecret)).Should().NotContain(ManagementScope, "the role's scope is not added: the client neither asked for it nor may request it"); using var response = await ManagementCallAsync(token); response.StatusCode.Should().BeOneOf([HttpStatusCode.Unauthorized, HttpStatusCode.Forbidden], "the token of a third-party client must not administer Identity"); } [Fact] public async Task A_client_without_the_permission_cannot_request_the_scope_either() { using var response = await _fx.Http.PostAsync("/connect/token", Form(ThirdPartyClientId, ThirdPartySecret, _admin, $"openid {ManagementScope}")); var body = JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync()); response.IsSuccessStatusCode.Should().BeFalse("the client's permissions are checked on the request"); // OpenIddict refuses a scope the client may not use as invalid_request (ID2051). body.GetProperty("error").GetString().Should().BeOneOf("invalid_request", "invalid_scope"); } [Fact] public async Task Without_a_request_the_role_scope_is_absent_even_for_a_permitted_client() { var token = await TokenAsync(ConsoleClientId, ConsoleSecret, _admin, "openid"); (await ScopesAsync(token, ConsoleClientId, ConsoleSecret)).Should().NotContain(ManagementScope, "a role entitles a requested scope, it does not add one"); } [Fact] public async Task Requested_and_carried_by_a_role_the_scope_is_issued_and_administers() { var token = await TokenAsync(ConsoleClientId, ConsoleSecret, _admin, $"openid {ManagementScope}"); (await ScopesAsync(token, ConsoleClientId, ConsoleSecret)).Should().Contain(ManagementScope); using var response = await ManagementCallAsync(token); response.StatusCode.Should().Be(HttpStatusCode.OK, "the administrator asked through the console: {0}", await response.Content.ReadAsStringAsync()); } [Fact] public async Task Requested_without_a_role_the_scope_is_dropped() { var token = await TokenAsync(ConsoleClientId, ConsoleSecret, _plain, $"openid {ManagementScope}"); (await ScopesAsync(token, ConsoleClientId, ConsoleSecret)).Should().NotContain(ManagementScope, "nothing about this user entitles the management scope"); } private static async Task EnsureClientAsync(IOpenIddictApplicationManager manager, string clientId, string secret, bool withManagementScope) { if (await manager.FindByClientIdAsync(clientId) is not null) return; var descriptor = new OpenIddictApplicationDescriptor { ClientId = clientId, ClientSecret = secret, DisplayName = "Role scope test: " + clientId, Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Introspection, OpenIddictConstants.Permissions.GrantTypes.Password, OpenIddictConstants.Permissions.Prefixes.Scope + "openid", }, }; if (withManagementScope) descriptor.Permissions.Add(OpenIddictConstants.Permissions.Prefixes.Scope + ManagementScope); await manager.CreateAsync(descriptor); } private static async Task CreateUserAsync(IRedbService redb, string login) => (await redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = login, Password = Password, Name = login, Email = $"{login}@rolescope.test", })).Id; private static FormUrlEncodedContent Form(string clientId, string secret, string user, string scope) => new(new Dictionary { ["grant_type"] = "password", ["username"] = user, ["password"] = Password, ["client_id"] = clientId, ["client_secret"] = secret, ["scope"] = scope, }); private async Task TokenAsync(string clientId, string secret, string user, string scope) { using var response = await _fx.Http.PostAsync("/connect/token", Form(clientId, secret, user, scope)); var body = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(HttpStatusCode.OK, "token: {0}", body); return JsonSerializer.Deserialize(body).GetProperty("access_token").GetString()!; } // What the token carries, asked of Identity itself; the token answer may omit "scope" (RFC 6749 §5.1). private async Task ScopesAsync(string token, string clientId, string secret) { using var response = await _fx.Http.PostAsync("/connect/introspect", new FormUrlEncodedContent(new Dictionary { ["token"] = token, ["client_id"] = clientId, ["client_secret"] = secret, })); var body = JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync()); body.GetProperty("active").GetBoolean().Should().BeTrue(); return body.TryGetProperty("scope", out var scope) ? scope.GetString()!.Split(' ', StringSplitOptions.RemoveEmptyEntries) : []; } private async Task ManagementCallAsync(string token) { var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/users"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); return await _fx.Http.SendAsync(request); } } Path: redb-identity/tests/redb.Identity.Tests/FullStack/UserProfileManagementTests.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/UserProfileManagementTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.FullStack; /// /// E2E tests for user profile management via Management REST API. /// Validates Address, CustomClaims, verification flags, and External fields /// through the full HTTP pipeline: Kestrel → bearer auth → controller → direct-vm → processor → PostgreSQL. /// [Collection("ProductionHttp")] public class UserProfileManagementTests { private readonly ProductionHttpFixture _fx; private readonly HttpClient _http; private static readonly JsonSerializerOptions CamelCase = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true }; public UserProfileManagementTests(ProductionHttpFixture fx) { _fx = fx; _http = fx.Http; } private HttpRequestMessage Auth(HttpRequestMessage req) { req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); return req; } private static async Task ParseResponse(HttpResponseMessage resp, string context) { var body = await resp.Content.ReadAsStringAsync(); resp.StatusCode.Should().Be(HttpStatusCode.OK, $"{context}: {body}"); return JsonDocument.Parse(body).RootElement; } private static long GetId(JsonElement el) { if (el.TryGetProperty("id", out var v)) return v.GetInt64(); if (el.TryGetProperty("Id", out v)) return v.GetInt64(); throw new InvalidOperationException($"No 'id' in response: {el}"); } private async Task<(long Id, string Login)> CreateUser(string? prefix = null) { var login = $"{prefix ?? "profile"}-{Guid.NewGuid():N}"; var req = Auth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/users") { Content = JsonContent.Create(new { login, password = "P@ssw0rd123!", email = $"{login}@test.com", phoneNumber = "+79001234567" }, options: CamelCase) }); var resp = await _http.SendAsync(req); var json = await ParseResponse(resp, "create"); return (GetId(json), login); } private async Task ReadUser(long id) { var req = Auth(new HttpRequestMessage(HttpMethod.Get, $"/api/v1/identity/users/{id}")); var resp = await _http.SendAsync(req); return await ParseResponse(resp, "read"); } private async Task UpdateUser(long id, object body) { var req = Auth(new HttpRequestMessage(HttpMethod.Put, $"/api/v1/identity/users/{id}") { Content = JsonContent.Create(body, options: CamelCase) }); var resp = await _http.SendAsync(req); return await ParseResponse(resp, "update"); } // ══════════════════════════════════════════════ // Newly-created user has null profile extensions // ══════════════════════════════════════════════ [Fact] public async Task NewUser_ProfileFieldsDefaultToNull() { var (id, _) = await CreateUser("defaults"); var user = await ReadUser(id); GetBool(user, "emailVerified").Should().BeFalse(); GetBool(user, "phoneNumberVerified").Should().BeFalse(); GetNullableString(user, "externalProvider").Should().BeNull(); GetNullableString(user, "externalId").Should().BeNull(); AssertPropertyNullOrMissing(user, "address"); AssertPropertyNullOrMissing(user, "customClaims"); } // ══════════════════════════════════════════════ // Update Address via PUT // ══════════════════════════════════════════════ [Fact] public async Task UpdateAddress_RoundTrips() { var (id, _) = await CreateUser("addr"); // Update with full OIDC address await UpdateUser(id, new { id, address = new { streetAddress = "123 Main St, Apt 4B", locality = "Springfield", region = "IL", postalCode = "62701", country = "US", formatted = "123 Main St, Apt 4B\nSpringfield, IL 62701\nUS" } }); // Read back and verify var user = await ReadUser(id); var addr = Prop(user, "address")!.Value; GetNullableString(addr, "streetAddress").Should().Be("123 Main St, Apt 4B"); GetNullableString(addr, "locality").Should().Be("Springfield"); GetNullableString(addr, "region").Should().Be("IL"); GetNullableString(addr, "postalCode").Should().Be("62701"); GetNullableString(addr, "country").Should().Be("US"); GetNullableString(addr, "formatted").Should().Contain("Springfield"); } // ══════════════════════════════════════════════ // Update verification flags (Lk scenario) // ══════════════════════════════════════════════ [Fact] public async Task UpdateVerificationFlags_ViaManagementApi() { var (id, _) = await CreateUser("verify"); // Lk scenario: service confirms user's email → sets email_verified via Management API await UpdateUser(id, new { id, emailVerified = true, phoneNumberVerified = true }); var user = await ReadUser(id); GetBool(user, "emailVerified").Should().BeTrue(); GetBool(user, "phoneNumberVerified").Should().BeTrue(); } // ══════════════════════════════════════════════ // Update CustomClaims — set and merge // ══════════════════════════════════════════════ [Fact] public async Task UpdateCustomClaims_SetAndReadBack() { var (id, _) = await CreateUser("claims"); await UpdateUser(id, new { id, customClaims = new Dictionary { ["department"] = "Engineering", ["employee_id"] = "EMP-42" } }); var user = await ReadUser(id); var claims = Prop(user, "customClaims")!.Value; GetNullableString(claims, "department").Should().Be("Engineering"); GetNullableString(claims, "employee_id").Should().Be("EMP-42"); } [Fact] public async Task UpdateCustomClaims_MergeSemanticsPreservesExisting() { var (id, _) = await CreateUser("merge"); // First update: set A + B await UpdateUser(id, new { id, customClaims = new Dictionary { ["role"] = "admin", ["tier"] = "gold" } }); // Second update: change B + add C — should preserve A await UpdateUser(id, new { id, customClaims = new Dictionary { ["tier"] = "platinum", ["region"] = "EU" } }); var user = await ReadUser(id); var claims = Prop(user, "customClaims")!.Value; GetNullableString(claims, "role").Should().Be("admin", "A should be preserved"); GetNullableString(claims, "tier").Should().Be("platinum", "B should be overwritten"); GetNullableString(claims, "region").Should().Be("EU", "C should be added"); } // ══════════════════════════════════════════════ // Full profile update in one PUT // ══════════════════════════════════════════════ [Fact] public async Task FullProfileUpdate_AddressClaimsAndFlags() { var (id, _) = await CreateUser("full"); var updated = await UpdateUser(id, new { id, givenName = "John", familyName = "Smith", emailVerified = true, phoneNumberVerified = true, address = new { streetAddress = "42 Main Street", locality = "London", country = "GB" }, customClaims = new Dictionary { ["org"] = "Acme Corp", ["level"] = "senior" } }); // Verify all fields in the response from the update itself GetNullableString(updated, "givenName").Should().Be("John"); GetNullableString(updated, "familyName").Should().Be("Smith"); GetBool(updated, "emailVerified").Should().BeTrue(); GetBool(updated, "phoneNumberVerified").Should().BeTrue(); var addr = Prop(updated, "address")!.Value; GetNullableString(addr, "streetAddress").Should().Be("42 Main Street"); GetNullableString(addr, "locality").Should().Be("London"); GetNullableString(addr, "country").Should().Be("GB"); var claims = Prop(updated, "customClaims")!.Value; GetNullableString(claims, "org").Should().Be("Acme Corp"); GetNullableString(claims, "level").Should().Be("senior"); // Also verify via separate GET to confirm persistence var readback = await ReadUser(id); GetBool(readback, "emailVerified").Should().BeTrue(); GetNullableString(Prop(readback, "address")!.Value, "country").Should().Be("GB"); GetNullableString(Prop(readback, "customClaims")!.Value, "org").Should().Be("Acme Corp"); } // ══════════════════════════════════════════════ // ExternalIdentities are null for local users // ══════════════════════════════════════════════ [Fact] public async Task LocalUser_ExternalFieldsAreNull() { var (id, _) = await CreateUser("local"); // Even after profile updates, external fields stay null for locally-created users await UpdateUser(id, new { id, emailVerified = true, customClaims = new Dictionary { ["test"] = "value" } }); var user = await ReadUser(id); var extId = Prop(user, "externalIdentities"); (extId is null || extId.Value.ValueKind == System.Text.Json.JsonValueKind.Null).Should().BeTrue( "local users should not have external identities"); } // ══════════════════════════════════════════════ // GivenName + FamilyName via Management API // ══════════════════════════════════════════════ [Fact] public async Task UpdateNameFields_ViaManagementApi() { var (id, _) = await CreateUser("names"); await UpdateUser(id, new { id, givenName = "Alice", familyName = "Smith", picture = "https://example.com/avatar.jpg" }); var user = await ReadUser(id); GetNullableString(user, "givenName").Should().Be("Alice"); GetNullableString(user, "familyName").Should().Be("Smith"); GetNullableString(user, "picture").Should().Be("https://example.com/avatar.jpg"); } // ══════════════════════════════════════════════ // Helpers // ══════════════════════════════════════════════ private static JsonElement? Prop(JsonElement el, string name) { // Try camelCase first, then PascalCase if (el.TryGetProperty(name, out var v)) return v; var pascal = char.ToUpper(name[0]) + name[1..]; if (el.TryGetProperty(pascal, out v)) return v; return null; } private static string? GetNullableString(JsonElement el, string prop) { var v = Prop(el, prop); if (v is null || v.Value.ValueKind == JsonValueKind.Null) return null; return v.Value.GetString(); } private static bool GetBool(JsonElement el, string prop) { var v = Prop(el, prop); return v?.GetBoolean() ?? false; } private static void AssertPropertyNullOrMissing(JsonElement el, string prop) { var v = Prop(el, prop); if (v is not null) v.Value.ValueKind.Should().Be(JsonValueKind.Null, $"'{prop}' should be null if present"); } } Path: redb-identity/tests/redb.Identity.Tests/Groups/GroupClaimsTests.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/Groups/GroupClaimsTests.cs ---- using System.Security.Claims; using AwesomeAssertions; using OpenIddict.Abstractions; using redb.Core; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; using static OpenIddict.Abstractions.OpenIddictConstants; namespace redb.Identity.Tests.Groups; /// /// Tests for — enriching ClaimsPrincipal /// with group/role claims based on scopes. /// [Collection("Postgres")] public class GroupClaimsTests { private readonly PostgresFixture _fx; private readonly ITestOutputHelper _output; public GroupClaimsTests(PostgresFixture fx, ITestOutputHelper output) { _fx = fx; _output = output; } private IGroupService CreateGroupService() => new GroupService(_fx.Redb); private GroupClaimsResolver CreateResolver() => new GroupClaimsResolver(_fx.Redb); private static ClaimsPrincipal BuildTestPrincipal(long userId, params string[] scopes) { var identity = new ClaimsIdentity("test"); identity.AddClaim(new Claim(Claims.Subject, userId.ToString())); identity.AddClaim(new Claim(Claims.Name, $"user_{userId}")); identity.SetScopes(scopes); return new ClaimsPrincipal(identity); } [Fact] public async Task EnrichPrincipal_WithGroupsScope_AddsGroupClaims() { var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var group1 = await svc.CreateGroupAsync("ClaimGroup1", "team"); var group2 = await svc.CreateGroupAsync("ClaimGroup2", "department"); await svc.AddMemberAsync(group1.id, userId, "member"); await svc.AddMemberAsync(group2.id, userId, "admin"); var principal = BuildTestPrincipal(userId, "openid", "groups"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "groups" }); var groupClaims = principal.FindAll(GroupClaimsResolver.GroupsClaim).Select(c => c.Value).ToList(); groupClaims.Should().Contain("ClaimGroup1"); groupClaims.Should().Contain("ClaimGroup2"); _output.WriteLine($"Group claims: {string.Join(", ", groupClaims)}"); } [Fact] public async Task EnrichPrincipal_WithRolesScope_AddsRoleClaims() { var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var group1 = await svc.CreateGroupAsync("RoleClaimG1", "team"); var group2 = await svc.CreateGroupAsync("RoleClaimG2", "department"); await svc.AddMemberAsync(group1.id, userId, "editor"); await svc.AddMemberAsync(group2.id, userId, "viewer"); var principal = BuildTestPrincipal(userId, "openid", "roles"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "roles" }); var roleClaims = principal.FindAll(GroupClaimsResolver.RolesClaim).Select(c => c.Value).ToList(); roleClaims.Should().Contain("editor"); roleClaims.Should().Contain("viewer"); _output.WriteLine($"Role claims: {string.Join(", ", roleClaims)}"); } [Fact] public async Task EnrichPrincipal_WithBothScopes_AddsBothClaims() { var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var group = await svc.CreateGroupAsync("BothScopeGroup", "team"); await svc.AddMemberAsync(group.id, userId, "admin"); var principal = BuildTestPrincipal(userId, "openid", "groups", "roles"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "groups", "roles" }); principal.FindAll(GroupClaimsResolver.GroupsClaim).Should().NotBeEmpty(); principal.FindAll(GroupClaimsResolver.RolesClaim).Should().NotBeEmpty(); } [Fact] public async Task EnrichPrincipal_WithoutGroupsOrRolesScope_NoClaimsAdded() { var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var group = await svc.CreateGroupAsync("NoScopeGroup", "team"); await svc.AddMemberAsync(group.id, userId, "member"); var principal = BuildTestPrincipal(userId, "openid", "profile"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "profile" }); principal.FindAll(GroupClaimsResolver.GroupsClaim).Should().BeEmpty(); principal.FindAll(GroupClaimsResolver.RolesClaim).Should().BeEmpty(); } [Fact] public async Task EnrichPrincipal_DuplicateRoles_Deduplicated() { var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var group1 = await svc.CreateGroupAsync("DedupG1", "team"); var group2 = await svc.CreateGroupAsync("DedupG2", "team"); await svc.AddMemberAsync(group1.id, userId, "member"); await svc.AddMemberAsync(group2.id, userId, "member"); // same role var principal = BuildTestPrincipal(userId, "openid", "roles"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "roles" }); var roleClaims = principal.FindAll(GroupClaimsResolver.RolesClaim).Select(c => c.Value).ToList(); // "member" should appear only once roleClaims.Count(r => r == "member").Should().Be(1, "duplicate roles should be deduplicated"); } [Fact] public async Task EnrichPrincipal_ExpiredMembership_NotIncluded() { var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var active = await svc.CreateGroupAsync("ClaimActiveG", "team"); var expired = await svc.CreateGroupAsync("ClaimExpiredG", "team"); await svc.AddMemberAsync(active.id, userId, "member"); await svc.AddMemberAsync(expired.id, userId, "member", expiresAt: DateTimeOffset.UtcNow.AddHours(-1)); var principal = BuildTestPrincipal(userId, "openid", "groups"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "groups" }); var groupClaims = principal.FindAll(GroupClaimsResolver.GroupsClaim).Select(c => c.Value).ToList(); groupClaims.Should().Contain("ClaimActiveG"); groupClaims.Should().NotContain("ClaimExpiredG"); } [Fact] public async Task EnrichPrincipal_WithGroupsScope_AddsOrgClaim() { var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var org = await svc.CreateGroupAsync("OrgClaimCorp", "organization"); var team = await svc.CreateGroupAsync("OrgClaimTeam", "team"); await svc.AddMemberAsync(org.id, userId, "member"); await svc.AddMemberAsync(team.id, userId, "admin"); var principal = BuildTestPrincipal(userId, "openid", "groups"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "groups" }); var orgClaims = principal.FindAll(GroupClaimsResolver.OrgClaim).Select(c => c.Value).ToList(); orgClaims.Should().ContainSingle().Which.Should().Be("OrgClaimCorp"); _output.WriteLine($"Org claim: {string.Join(", ", orgClaims)}"); } [Fact] public async Task EnrichPrincipal_WithoutOrgTypeGroup_NoOrgClaim() { var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var team = await svc.CreateGroupAsync("NoOrgTeam", "team"); await svc.AddMemberAsync(team.id, userId, "member"); var principal = BuildTestPrincipal(userId, "openid", "groups"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "groups" }); principal.FindAll(GroupClaimsResolver.OrgClaim).Should().BeEmpty( "no organization-type group means no org claim"); } // ── Composite group inheritance via tree-hierarchy (DoD §5 H2 closure) ── [Fact] public async Task EnrichPrincipal_GroupsScope_IncludesAncestorGroupNames() { // Tree: company → engineering → developers // User is direct member of "developers" — should also receive // "engineering" and "company" via tree-ancestor traversal. var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var suffix = userId.ToString(); var company = await svc.CreateGroupAsync($"InheritCompany_{suffix}", "organization"); var engineering = await svc.CreateChildGroupAsync(company.id, $"InheritEngineering_{suffix}", "department"); var developers = await svc.CreateChildGroupAsync(engineering.id, $"InheritDevelopers_{suffix}", "team"); await svc.AddMemberAsync(developers.id, userId, "member"); var principal = BuildTestPrincipal(userId, "openid", "groups"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "groups" }); var groupClaims = principal.FindAll(GroupClaimsResolver.GroupsClaim).Select(c => c.Value).ToList(); groupClaims.Should().Contain($"InheritDevelopers_{suffix}", "direct membership"); groupClaims.Should().Contain($"InheritEngineering_{suffix}", "ancestor (parent)"); groupClaims.Should().Contain($"InheritCompany_{suffix}", "ancestor (grandparent / root)"); _output.WriteLine($"Inherited group claims: {string.Join(", ", groupClaims)}"); } [Fact] public async Task EnrichPrincipal_GroupsScope_DeduplicatesAncestorsWhenSharedAcrossMemberships() { // Tree: rootShared → branchA, branchB // User is member of both branchA and branchB — should receive // "rootShared" exactly once (no duplicate ancestor claim). var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var suffix = userId.ToString(); var root = await svc.CreateGroupAsync($"SharedRoot_{suffix}", "organization"); var branchA = await svc.CreateChildGroupAsync(root.id, $"BranchA_{suffix}", "team"); var branchB = await svc.CreateChildGroupAsync(root.id, $"BranchB_{suffix}", "team"); await svc.AddMemberAsync(branchA.id, userId, "member"); await svc.AddMemberAsync(branchB.id, userId, "member"); var principal = BuildTestPrincipal(userId, "openid", "groups"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "groups" }); var groupClaims = principal.FindAll(GroupClaimsResolver.GroupsClaim).Select(c => c.Value).ToList(); groupClaims.Count(c => c == $"SharedRoot_{suffix}").Should().Be(1, "ancestor shared by two direct memberships should appear once"); } [Fact] public async Task EnrichPrincipal_GroupsScope_OrgClaimFallsBackToAncestor() { // Tree: orgRoot (organization) → team (no org-type) // User is direct member only of "team" — org claim should fall back // to ancestor organization-type group "orgRoot". var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var suffix = userId.ToString(); var orgRoot = await svc.CreateGroupAsync($"OrgRootInherited_{suffix}", "organization"); var team = await svc.CreateChildGroupAsync(orgRoot.id, $"TeamInherited_{suffix}", "team"); await svc.AddMemberAsync(team.id, userId, "member"); var principal = BuildTestPrincipal(userId, "openid", "groups"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "groups" }); var orgClaims = principal.FindAll(GroupClaimsResolver.OrgClaim).Select(c => c.Value).ToList(); orgClaims.Should().ContainSingle().Which.Should().Be($"OrgRootInherited_{suffix}", "org claim should fall back to closest organization-type ancestor when no direct organization membership exists"); } [Fact] public async Task EnrichPrincipal_RolesScope_PerMembershipRolesAreNotInherited() { // Tree: parent (with no user membership) → child (user is member with role="editor") // The "editor" role applies only to the child membership; the parent group // does NOT auto-grant a role to the user (per-membership Role label is not transitive). var svc = CreateGroupService(); var resolver = CreateResolver(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var suffix = userId.ToString(); var parent = await svc.CreateGroupAsync($"NoInheritParent_{suffix}", "team"); var child = await svc.CreateChildGroupAsync(parent.id, $"NoInheritChild_{suffix}", "team"); await svc.AddMemberAsync(child.id, userId, "editor"); var principal = BuildTestPrincipal(userId, "openid", "roles"); await resolver.EnrichPrincipalAsync(principal, userId, new[] { "openid", "roles" }); var roleClaims = principal.FindAll(GroupClaimsResolver.RolesClaim).Select(c => c.Value).ToList(); roleClaims.Should().Contain("editor", "direct membership emits its role"); // No additional inherited role beyond "editor" — per-membership label, not transitive. roleClaims.Count(r => r == "editor").Should().Be(1); } } Path: redb-identity/tests/redb.Identity.Tests/Groups/GroupIntegrationTests.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/Groups/GroupIntegrationTests.cs ---- using AwesomeAssertions; using redb.Identity.Contracts.Groups; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using redb.Route.Core; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Groups; /// /// Integration tests for group management via direct-vm routes. /// Uses with full OpenIddict pipeline. /// [Collection("ProductionBootstrap")] public class GroupIntegrationTests { private readonly ProductionBootstrapFixture _fx; private readonly ITestOutputHelper _output; public GroupIntegrationTests(ProductionBootstrapFixture fx, ITestOutputHelper output) { _fx = fx; _output = output; } private Task Send(string operation, Dictionary body) { return _fx.RequestWithHeaders( IdentityEndpoints.ManageGroups, body, new Dictionary { ["operation"] = operation }); } // ── Group CRUD ────────────────────────────────────────────── [Fact] public async Task Create_And_Read_Group() { var createEx = await Send("create", new Dictionary { ["name"] = "IntGroup1", ["groupType"] = "team", ["description"] = "Integration test group" }); var created = createEx.Out?.Body; created.Should().NotBeNull(); var id = GetId(created!); id.Should().BeGreaterThan(0); var readEx = await Send("read", new Dictionary { ["groupId"] = id }); var read = readEx.Out?.Body; read.Should().NotBeNull(); _output.WriteLine($"Created and read group {id}"); } [Fact] public async Task List_ReturnsRootGroups() { await Send("create", new Dictionary { ["name"] = "IntListRoot", ["groupType"] = "organization" }); var listEx = await Send("list", new Dictionary()); var list = listEx.Out?.Body as IEnumerable; list.Should().NotBeNullOrEmpty(); _output.WriteLine($"Root groups count: {list!.Count()}"); } [Fact] public async Task Update_Group() { var createEx = await Send("create", new Dictionary { ["name"] = "IntUpdateBefore", ["groupType"] = "team" }); var id = GetId(createEx.Out!.Body!); var updateEx = await Send("update", new Dictionary { ["groupId"] = id, ["name"] = "IntUpdateAfter", ["description"] = "Updated" }); updateEx.Out?.Body.Should().NotBeNull(); var readEx = await Send("read", new Dictionary { ["groupId"] = id }); var body = readEx.Out?.Body; body.Should().BeOfType().Subject.Name.Should().Be("IntUpdateAfter"); _output.WriteLine($"Updated group {id}"); } [Fact] public async Task Delete_Group() { var createEx = await Send("create", new Dictionary { ["name"] = "IntDeleteTarget", ["groupType"] = "team" }); var id = GetId(createEx.Out!.Body!); await Send("delete", new Dictionary { ["groupId"] = id }); var readEx = await Send("read", new Dictionary { ["groupId"] = id }); // Should be not_found or null var body = readEx.Out?.Body; if (body is IDictionary dict) dict.ContainsKey("error").Should().BeTrue(); } // ── Tree ──────────────────────────────────────────────────── [Fact] public async Task CreateChild_And_GetTree() { var parentEx = await Send("create", new Dictionary { ["name"] = "IntTreeRoot", ["groupType"] = "organization" }); var parentId = GetId(parentEx.Out!.Body!); await Send("create-child", new Dictionary { ["parentGroupId"] = parentId, ["name"] = "IntTreeChild", ["groupType"] = "team" }); var treeEx = await Send("tree", new Dictionary { ["groupId"] = parentId }); treeEx.Out?.Body.Should().NotBeNull(); _output.WriteLine($"Tree loaded for group {parentId}"); } [Fact] public async Task Children_ReturnsDirectChildren() { var parentEx = await Send("create", new Dictionary { ["name"] = "IntChildrenRoot", ["groupType"] = "organization" }); var parentId = GetId(parentEx.Out!.Body!); await Send("create-child", new Dictionary { ["parentGroupId"] = parentId, ["name"] = "IntChild1", ["groupType"] = "team" }); var childrenEx = await Send("children", new Dictionary { ["groupId"] = parentId }); var children = childrenEx.Out?.Body as IEnumerable; children.Should().NotBeNullOrEmpty(); } [Fact] public async Task Path_ReturnsAncestors() { var rootEx = await Send("create", new Dictionary { ["name"] = "IntPathRoot", ["groupType"] = "organization" }); var rootId = GetId(rootEx.Out!.Body!); var childEx = await Send("create-child", new Dictionary { ["parentGroupId"] = rootId, ["name"] = "IntPathChild", ["groupType"] = "team" }); var childId = GetId(childEx.Out!.Body!); var pathEx = await Send("path", new Dictionary { ["groupId"] = childId }); var path = pathEx.Out?.Body as IEnumerable; path.Should().NotBeNullOrEmpty(); } [Fact] public async Task Move_Group() { // Unique-per-run names so re-runs against a shared DB don't collide with // residue from a previous run (the create endpoint returns an error // response rather than a group when a same-named group already exists, and // GetId() then fails on the type). var runTag = Guid.NewGuid().ToString("N")[..8]; var org1Ex = await Send("create", new Dictionary { ["name"] = $"IntMoveOrg1-{runTag}", ["groupType"] = "organization" }); var org1Id = GetId(org1Ex.Out!.Body!); var org2Ex = await Send("create", new Dictionary { ["name"] = $"IntMoveOrg2-{runTag}", ["groupType"] = "organization" }); var org2Id = GetId(org2Ex.Out!.Body!); var teamEx = await Send("create-child", new Dictionary { ["parentGroupId"] = org1Id, ["name"] = $"IntMoveTeam-{runTag}", ["groupType"] = "team" }); var teamId = GetId(teamEx.Out!.Body!); await Send("move", new Dictionary { ["groupId"] = teamId, ["newParentGroupId"] = org2Id }); var children2 = await Send("children", new Dictionary { ["groupId"] = org2Id }); var list = children2.Out?.Body as IEnumerable; list.Should().NotBeNullOrEmpty("team should have moved to org2"); } // ── Membership ────────────────────────────────────────────── [Fact] public async Task AddMember_And_ListMembers() { var groupEx = await Send("create", new Dictionary { ["name"] = "IntMemberGroup", ["groupType"] = "team" }); var groupId = GetId(groupEx.Out!.Body!); await Send("add-member", new Dictionary { ["groupId"] = groupId, ["userId"] = _fx.TestUserId, ["role"] = "admin" }); var membersEx = await Send("list-members", new Dictionary { ["groupId"] = groupId }); var members = membersEx.Out?.Body as IEnumerable; members.Should().NotBeNullOrEmpty(); _output.WriteLine($"Group {groupId} has {members!.Count()} member(s)"); } [Fact] public async Task UpdateMember_ChangesRole() { var groupEx = await Send("create", new Dictionary { ["name"] = "IntUpdateMemberGroup", ["groupType"] = "team" }); var groupId = GetId(groupEx.Out!.Body!); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await Send("add-member", new Dictionary { ["groupId"] = groupId, ["userId"] = userId, ["role"] = "member" }); await Send("update-member", new Dictionary { ["groupId"] = groupId, ["userId"] = userId, ["role"] = "admin" }); var membersEx = await Send("list-members", new Dictionary { ["groupId"] = groupId }); var members = membersEx.Out?.Body as IEnumerable; members.Should().NotBeNullOrEmpty(); } [Fact] public async Task RemoveMember_DeletesMembership() { var groupEx = await Send("create", new Dictionary { ["name"] = "IntRemoveMemberGroup", ["groupType"] = "team" }); var groupId = GetId(groupEx.Out!.Body!); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await Send("add-member", new Dictionary { ["groupId"] = groupId, ["userId"] = userId, ["role"] = "member" }); await Send("remove-member", new Dictionary { ["groupId"] = groupId, ["userId"] = userId }); var membersEx = await Send("list-members", new Dictionary { ["groupId"] = groupId }); var members = membersEx.Out?.Body as IEnumerable; // After removing the only member, list should be empty or not contain the user var memberList = members?.ToList() ?? []; var hasUser = memberList.OfType>() .Any(d => d.TryGetValue("UserId", out var uid) && uid?.ToString() == userId.ToString()); hasUser.Should().BeFalse("removed member should not appear in list"); } [Fact] public async Task UserGroups_ReturnsUserMemberships() { var groupEx = await Send("create", new Dictionary { ["name"] = "IntUserGroupsGroup", ["groupType"] = "team" }); var groupId = GetId(groupEx.Out!.Body!); var userId = _fx.TestUserId; await Send("add-member", new Dictionary { ["groupId"] = groupId, ["userId"] = userId, ["role"] = "member" }); var userGroupsEx = await Send("user-groups", new Dictionary { ["userId"] = userId }); var groups = userGroupsEx.Out?.Body as IEnumerable; groups.Should().NotBeNullOrEmpty(); } [Fact] public async Task IsMember_ReturnsCorrectResult() { var groupEx = await Send("create", new Dictionary { ["name"] = "IntIsMemberGroup", ["groupType"] = "team" }); var groupId = GetId(groupEx.Out!.Body!); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // Not a member yet var checkEx1 = await Send("is-member", new Dictionary { ["groupId"] = groupId, ["userId"] = userId }); var result1 = checkEx1.Out?.Body; result1.Should().BeOfType().Subject.IsMember.Should().BeFalse(); // Add member await Send("add-member", new Dictionary { ["groupId"] = groupId, ["userId"] = userId, ["role"] = "member" }); var checkEx2 = await Send("is-member", new Dictionary { ["groupId"] = groupId, ["userId"] = userId }); var result2 = checkEx2.Out?.Body; result2.Should().BeOfType().Subject.IsMember.Should().BeTrue(); } // ── Events ────────────────────────────────────────────────── [Fact] public async Task Create_SetsEventProperties() { var ex = await Send("create", new Dictionary { ["name"] = "IntEventGroup", ["groupType"] = "team" }); ex.Properties.Should().ContainKey("identity-event-type"); ex.Properties["identity-event-type"].Should().Be("GroupCreated"); ex.Properties.Should().ContainKey("identity-event-data"); } [Fact] public async Task AddMember_SetsEventProperties() { var groupEx = await Send("create", new Dictionary { ["name"] = "IntEventMemberGroup", ["groupType"] = "team" }); var groupId = GetId(groupEx.Out!.Body!); var addEx = await Send("add-member", new Dictionary { ["groupId"] = groupId, ["userId"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ["role"] = "member" }); addEx.Properties.Should().ContainKey("identity-event-type"); addEx.Properties["identity-event-type"].Should().Be("MemberAdded"); } // ── Helpers ───────────────────────────────────────────────── private static long GetId(object body) => body.Should().BeOfType().Subject.Id; } Path: redb-identity/tests/redb.Identity.Tests/Groups/GroupServiceTests.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/Groups/GroupServiceTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Models; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Groups; /// /// Store-level tests for . /// Uses (raw redb + PostgreSQL, no OpenIddict pipeline). /// [Collection("Postgres")] public class GroupServiceTests { private readonly PostgresFixture _fx; private readonly ITestOutputHelper _output; public GroupServiceTests(PostgresFixture fx, ITestOutputHelper output) { _fx = fx; _output = output; } private IGroupService CreateService() => new GroupService(_fx.Redb); // ── Group CRUD ────────────────────────────────────────────── [Fact] public async Task CreateGroup_ReturnsNewGroup() { var svc = CreateService(); var group = await svc.CreateGroupAsync("Engineering", "department", "The engineering org"); group.Should().NotBeNull(); group.id.Should().BeGreaterThan(0); group.name.Should().Be("Engineering"); group.Props.GroupType.Should().Be("department"); group.Props.Description.Should().Be("The engineering org"); _output.WriteLine($"Created group {group.id}: {group.name}"); } [Fact] public async Task GetGroup_ReturnsExistingGroup() { var svc = CreateService(); var created = await svc.CreateGroupAsync("GetTest", "team"); var loaded = await svc.GetGroupAsync(created.id); loaded.Should().NotBeNull(); loaded!.id.Should().Be(created.id); loaded.name.Should().Be("GetTest"); loaded.Props.GroupType.Should().Be("team"); } [Fact] public async Task GetGroup_NonExistent_ReturnsNull() { var svc = CreateService(); var result = await svc.GetGroupAsync(999999999); result.Should().BeNull(); } [Fact] public async Task UpdateGroup_ModifiesFields() { var svc = CreateService(); var group = await svc.CreateGroupAsync("BeforeUpdate", "team"); await svc.UpdateGroupAsync(group.id, name: "AfterUpdate", description: "Updated desc"); var loaded = await svc.GetGroupAsync(group.id); loaded!.name.Should().Be("AfterUpdate"); loaded.Props.Description.Should().Be("Updated desc"); loaded.Props.GroupType.Should().Be("team"); // unchanged } [Fact] public async Task DeleteGroup_RemovesGroup() { var svc = CreateService(); var group = await svc.CreateGroupAsync("ToDelete", "team"); await svc.DeleteGroupAsync(group.id); var loaded = await svc.GetGroupAsync(group.id); loaded.Should().BeNull(); } [Fact] public async Task DeleteGroup_AlsoRemovesMembers() { var svc = CreateService(); var group = await svc.CreateGroupAsync("DeleteWithMembers", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await svc.AddMemberAsync(group.id, userId); await svc.DeleteGroupAsync(group.id); // Member should also be gone — user-groups should not reference deleted group var userGroups = await svc.GetUserGroupsAsync(userId); userGroups.Should().NotContain(g => g.GroupId == group.id); } [Fact] public async Task GroupWithoutProperties_UserGroupsAndLoadsWork() { // A group created with nothing but a name stores no props rows. var svc = CreateService(); var group = await svc.CreateGroupAsync("NoProps-" + Guid.NewGuid().ToString("N")[..8]); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await svc.AddMemberAsync(group.id, userId); var userGroups = await svc.GetUserGroupsAsync(userId); userGroups.Should().ContainSingle(g => g.GroupId == group.id); userGroups.Single(g => g.GroupId == group.id).GroupType.Should().BeNull(); userGroups.Single(g => g.GroupId == group.id).GroupName.Should().Be(group.name); (await svc.ResolveUserRolesAsync(userId)).Should().ContainSingle(g => g.GroupId == group.id); // redb hands such a group back with Props null; callers must not dereference it blindly. var loaded = await svc.GetGroupAsync(group.id); loaded.Should().NotBeNull(); loaded!.Props?.GroupType.Should().BeNull(); await svc.UpdateGroupAsync(group.id, groupType: "team"); (await svc.GetGroupAsync(group.id))!.Props.GroupType.Should().Be("team"); } // ── Tree operations ───────────────────────────────────────── [Fact] public async Task CreateChildGroup_SetsParent() { var svc = CreateService(); var parent = await svc.CreateGroupAsync("ParentOrg", "organization"); var child = await svc.CreateChildGroupAsync(parent.id, "ChildTeam", "team"); child.Should().NotBeNull(); child.id.Should().BeGreaterThan(0); child.parent_id.Should().Be(parent.id); child.name.Should().Be("ChildTeam"); _output.WriteLine($"Created child {child.id} under parent {parent.id}"); } [Fact] public async Task GetChildGroups_ReturnsDirectChildren() { var svc = CreateService(); var parent = await svc.CreateGroupAsync("ChildrenTestParent", "organization"); await svc.CreateChildGroupAsync(parent.id, "Child1", "team"); await svc.CreateChildGroupAsync(parent.id, "Child2", "team"); var children = await svc.GetChildGroupsAsync(parent.id); children.Should().HaveCountGreaterThanOrEqualTo(2); children.Should().Contain(c => c.name == "Child1"); children.Should().Contain(c => c.name == "Child2"); } [Fact] public async Task ListRootGroups_ReturnsGroupsWithoutParent() { var svc = CreateService(); var ts = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var rootName = $"Root_{ts}"; await svc.CreateGroupAsync(rootName, "organization"); var roots = await svc.ListRootGroupsAsync(); roots.Should().Contain(g => g.name == rootName); roots.Should().OnlyContain(g => g.parent_id == null); } [Fact] public async Task LoadTree_ReturnsHierarchy() { var svc = CreateService(); var root = await svc.CreateGroupAsync("TreeRoot", "organization"); var dept = await svc.CreateChildGroupAsync(root.id, "TreeDept", "department"); await svc.CreateChildGroupAsync(dept.id, "TreeTeam", "team"); var tree = await svc.LoadTreeAsync(root.id); tree.Should().NotBeNull(); tree.id.Should().Be(root.id); tree.Children.Should().NotBeEmpty(); _output.WriteLine($"Tree root {tree.id}, children: {tree.Children.Count}"); } [Fact] public async Task GetPathToRoot_ReturnsAncestors() { var svc = CreateService(); var root = await svc.CreateGroupAsync("PathRoot", "organization"); var dept = await svc.CreateChildGroupAsync(root.id, "PathDept", "department"); var team = await svc.CreateChildGroupAsync(dept.id, "PathTeam", "team"); var path = await svc.GetPathToRootAsync(team.id); path.Should().HaveCountGreaterThanOrEqualTo(2); path.Select(p => p.id).Should().Contain(root.id); } [Fact] public async Task MoveGroup_ChangesParent() { var svc = CreateService(); var org1 = await svc.CreateGroupAsync("MoveOrg1", "organization"); var org2 = await svc.CreateGroupAsync("MoveOrg2", "organization"); var team = await svc.CreateChildGroupAsync(org1.id, "MoveTeam", "team"); await svc.MoveGroupAsync(team.id, org2.id); var children1 = await svc.GetChildGroupsAsync(org1.id); var children2 = await svc.GetChildGroupsAsync(org2.id); children1.Should().NotContain(c => c.id == team.id); children2.Should().Contain(c => c.id == team.id); } // ── Membership ────────────────────────────────────────────── [Fact] public async Task AddMember_CreatesMembership() { var svc = CreateService(); var group = await svc.CreateGroupAsync("MemberGroup", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var member = await svc.AddMemberAsync(group.id, userId, "admin"); member.Should().NotBeNull(); member.id.Should().BeGreaterThan(0); member.key.Should().Be(userId); member.parent_id.Should().Be(group.id); member.Props.Role.Should().Be("admin"); member.Props.JoinedAt.Should().NotBeNull(); _output.WriteLine($"Added user {userId} to group {group.id} as admin"); } [Fact] public async Task AddMember_Duplicate_Throws() { var svc = CreateService(); var group = await svc.CreateGroupAsync("DupeMemberGroup", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await svc.AddMemberAsync(group.id, userId); var act = () => svc.AddMemberAsync(group.id, userId); await act.Should().ThrowAsync() .WithMessage("*already a member*"); } [Fact] public async Task RemoveMember_DeletesMembership() { var svc = CreateService(); var group = await svc.CreateGroupAsync("RemoveMemberGroup", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await svc.AddMemberAsync(group.id, userId); await svc.RemoveMemberAsync(group.id, userId); var isMember = await svc.IsMemberAsync(group.id, userId); isMember.Should().BeFalse(); } [Fact] public async Task UpdateMemberRole_ChangesRole() { var svc = CreateService(); var group = await svc.CreateGroupAsync("RoleChangeGroup", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await svc.AddMemberAsync(group.id, userId, "member"); await svc.UpdateMemberRoleAsync(group.id, userId, "admin"); var members = await svc.GetMembersAsync(group.id); members.Should().Contain(m => m.UserId == userId && m.Role == "admin"); } [Fact] public async Task GetMembers_ReturnsGroupMembers() { var svc = CreateService(); var group = await svc.CreateGroupAsync("ListMembersGroup", "team"); var user1 = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var user2 = user1 + 1; await svc.AddMemberAsync(group.id, user1, "admin"); await svc.AddMemberAsync(group.id, user2, "member"); var members = await svc.GetMembersAsync(group.id); members.Should().HaveCount(2); members.Should().Contain(m => m.UserId == user1 && m.Role == "admin"); members.Should().Contain(m => m.UserId == user2 && m.Role == "member"); } [Fact] public async Task GetUserGroups_ReturnsUserMemberships() { var svc = CreateService(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var group1 = await svc.CreateGroupAsync("UserGroup1", "team"); var group2 = await svc.CreateGroupAsync("UserGroup2", "department"); await svc.AddMemberAsync(group1.id, userId, "member"); await svc.AddMemberAsync(group2.id, userId, "admin"); var groups = await svc.GetUserGroupsAsync(userId); groups.Should().HaveCountGreaterThanOrEqualTo(2); groups.Should().Contain(g => g.GroupId == group1.id && g.Role == "member"); groups.Should().Contain(g => g.GroupId == group2.id && g.Role == "admin"); } [Fact] public async Task IsMember_ReturnsTrueForActiveMember() { var svc = CreateService(); var group = await svc.CreateGroupAsync("IsMemberGroup", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await svc.AddMemberAsync(group.id, userId); var result = await svc.IsMemberAsync(group.id, userId); result.Should().BeTrue(); } [Fact] public async Task IsMember_ReturnsFalseForNonMember() { var svc = CreateService(); var group = await svc.CreateGroupAsync("IsMemberFalseGroup", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var result = await svc.IsMemberAsync(group.id, userId); result.Should().BeFalse(); } [Fact] public async Task IsMember_ReturnsFalseForExpiredMembership() { var svc = CreateService(); var group = await svc.CreateGroupAsync("ExpiredGroup", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // Add with expiration in the past await svc.AddMemberAsync(group.id, userId, "member", expiresAt: DateTimeOffset.UtcNow.AddHours(-1)); var result = await svc.IsMemberAsync(group.id, userId); result.Should().BeFalse(); } // ── Role resolution ───────────────────────────────────────── [Fact] public async Task ResolveUserRoles_ReturnsActiveNonExpiredMemberships() { var svc = CreateService(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var active = await svc.CreateGroupAsync("ResolveActive", "role"); var expired = await svc.CreateGroupAsync("ResolveExpired", "role"); await svc.AddMemberAsync(active.id, userId, "member"); await svc.AddMemberAsync(expired.id, userId, "member", expiresAt: DateTimeOffset.UtcNow.AddHours(-1)); var roles = await svc.ResolveUserRolesAsync(userId); roles.Should().Contain(r => r.GroupId == active.id); roles.Should().NotContain(r => r.GroupId == expired.id); } [Fact] public async Task ResolveUserRoles_IncludesGroupInfo() { var svc = CreateService(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var group = await svc.CreateGroupAsync("ResolveInfo", "role"); await svc.AddMemberAsync(group.id, userId, "admin"); var roles = await svc.ResolveUserRolesAsync(userId); var entry = roles.FirstOrDefault(r => r.GroupId == group.id); entry.Should().NotBeNull(); entry!.GroupName.Should().Be("ResolveInfo"); entry.GroupType.Should().Be("role"); entry.Role.Should().Be("admin"); } // ── Ancestor membership ───────────────────────────────────── [Fact] public async Task IsMember_ViaAncestorGroup_ReturnsTrue() { var svc = CreateService(); var org = await svc.CreateGroupAsync("AncOrg", "organization"); var dept = await svc.CreateChildGroupAsync(org.id, "AncDept", "department"); var team = await svc.CreateChildGroupAsync(dept.id, "AncTeam", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // User is member of org (top-level) await svc.AddMemberAsync(org.id, userId, "member"); // Should be considered member of dept and team via ancestor traversal var isDeptMember = await svc.IsMemberAsync(dept.id, userId); var isTeamMember = await svc.IsMemberAsync(team.id, userId); isDeptMember.Should().BeTrue("member of ancestor org → member of dept"); isTeamMember.Should().BeTrue("member of ancestor org → member of team"); _output.WriteLine($"User {userId} in org {org.id}: dept={isDeptMember}, team={isTeamMember}"); } [Fact] public async Task IsMember_ViaAncestorGroup_Expired_ReturnsFalse() { var svc = CreateService(); var org = await svc.CreateGroupAsync("AncExpOrg", "organization"); var team = await svc.CreateChildGroupAsync(org.id, "AncExpTeam", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // Expired membership in ancestor await svc.AddMemberAsync(org.id, userId, "member", expiresAt: DateTimeOffset.UtcNow.AddHours(-1)); var isTeamMember = await svc.IsMemberAsync(team.id, userId); isTeamMember.Should().BeFalse("expired ancestor membership should not count"); } // ── Cascade delete ────────────────────────────────────────── [Fact] public async Task DeleteGroup_CascadesChildMemberships() { var svc = CreateService(); var org = await svc.CreateGroupAsync("CascadeOrg", "organization"); var dept = await svc.CreateChildGroupAsync(org.id, "CascadeDept", "department"); var team = await svc.CreateChildGroupAsync(dept.id, "CascadeTeam", "team"); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); await svc.AddMemberAsync(dept.id, userId, "lead"); await svc.AddMemberAsync(team.id, userId, "member"); // Delete the org (parent of dept and team) await svc.DeleteGroupAsync(org.id); // All memberships should be gone var userGroups = await svc.GetUserGroupsAsync(userId); userGroups.Should().NotContain(g => g.GroupId == dept.id); userGroups.Should().NotContain(g => g.GroupId == team.id); _output.WriteLine($"After cascade delete: user has {userGroups.Count} groups (none from deleted subtree)"); } // ── Expired member filtering ──────────────────────────────── [Fact] public async Task GetMembers_ExcludesExpiredMembers() { var svc = CreateService(); var group = await svc.CreateGroupAsync("ExpFilterGroup", "team"); var activeUser = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var expiredUser = activeUser + 1; await svc.AddMemberAsync(group.id, activeUser, "member"); await svc.AddMemberAsync(group.id, expiredUser, "member", expiresAt: DateTimeOffset.UtcNow.AddHours(-1)); var members = await svc.GetMembersAsync(group.id); members.Should().Contain(m => m.UserId == activeUser); members.Should().NotContain(m => m.UserId == expiredUser, "expired members should be filtered out"); } [Fact] public async Task GetUserGroups_ExcludesExpiredMemberships() { var svc = CreateService(); var userId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var active = await svc.CreateGroupAsync("UGActive", "team"); var expired = await svc.CreateGroupAsync("UGExpired", "team"); await svc.AddMemberAsync(active.id, userId, "member"); await svc.AddMemberAsync(expired.id, userId, "member", expiresAt: DateTimeOffset.UtcNow.AddHours(-1)); var groups = await svc.GetUserGroupsAsync(userId); groups.Should().Contain(g => g.GroupId == active.id); groups.Should().NotContain(g => g.GroupId == expired.id, "expired memberships should be filtered out"); } // ── GetChildGroups ────────────────────────────────────────── [Fact] public async Task GetChildGroups_ReturnsOnlyDirectChildrenNotGrandchildren() { var svc = CreateService(); var root = await svc.CreateGroupAsync("OnlyDirectRoot", "organization"); var child = await svc.CreateChildGroupAsync(root.id, "OnlyDirectChild", "department"); var grandchild = await svc.CreateChildGroupAsync(child.id, "OnlyDirectGrandchild", "team"); var children = await svc.GetChildGroupsAsync(root.id); children.Should().Contain(c => c.id == child.id); children.Should().NotContain(c => c.id == grandchild.id, "grandchildren should not appear in direct children list"); } } Path: redb-identity/tests/redb.Identity.Tests/Grpc/GrpcFacadeModuleTests.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/Grpc/GrpcFacadeModuleTests.cs ---- using System.Buffers.Binary; using System.Net; using System.Net.Sockets; using AwesomeAssertions; using Grpc.Core; using Google.Protobuf; using Grpc.Net.Client; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// F0 — the gRPC facade module boots: its config binder reads the Tsak-merged section, its module host /// builds a child container, its route builder mounts a listener, and the port answers a real gRPC client. /// /// Everything except Tsak's own ALC loading is exercised here: InitRoute.main is called exactly the /// way the worker calls it. What this cannot cover is the packaging path — that is verified by loading the /// .tpkg in a worker. /// /// public class GrpcFacadeModuleTests : IAsyncLifetime { private ServiceProvider _sp = null!; private RouteContext _context = null!; private int _port; public Task InitializeAsync() { _port = GetFreePort(); var services = new ServiceCollection(); services.AddLogging(); _sp = services.BuildServiceProvider(); _context = new RouteContext(_sp, "identity.grpc-test"); // What Tsak hands a module: the merged 5-layer configuration as a nested dictionary. Using the // real property name means the binder is exercised, not bypassed. _context.SetProperty>("IdentityTransport", new Dictionary { ["Grpc"] = new Dictionary { ["Host"] = "127.0.0.1", ["PublicPort"] = _port, }, }); return Task.CompletedTask; } public async Task DisposeAsync() { await _context.DisposeAsync(); await _sp.DisposeAsync(); } [Fact] public async Task Module_boots_and_mounts_every_operation_as_its_own_route() { redb.Identity.Grpc.InitRoute.main(_context); await _context.Start(); // One method address = one route. That is the whole point of the design: each operation gets its // own id, policies, metrics and lifecycle instead of hiding inside one Choice(). _context.Routes.Select(r => r.RouteId).Should().Contain( [ "grpc-identity-token", "grpc-identity-introspect", "grpc-identity-revoke", "grpc-identity-userinfo", "grpc-identity-discovery", "grpc-identity-jwks", "grpc-identity-envelope", ]); } [Fact] public async Task Envelope_without_an_operation_says_what_it_expects() { redb.Identity.Grpc.InitRoute.main(_context); await _context.Start(); // The fallback path is keyed by an `operation` header. Answering with the list of known // operations beats a bare InvalidArgument the caller has to guess about. var act = async () => await CallAsync("/redb.route.grpc.RedbService/Process"); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.InvalidArgument); ex.Which.Status.Detail.Should().Contain("operation").And.Contain("token"); } [Fact] public async Task The_module_registers_the_management_surface_too() { // What every other test in this file could not see: they call the protocol addresses, and those // were registered. The management builder was not, so forty admin operations existed, were fully // covered by their own tests, and were unreachable in any real deployment — while InitRoute's log // line still announced a management port. A live worker showed `identity.grpc` starting with 7 // endpoints instead of 47. This asserts the wiring, not the behaviour behind it. redb.Identity.Grpc.InitRoute.main(_context); await _context.Start(); var routeIds = _context.Routes.Select(r => r.RouteId).ToList(); routeIds.Should().Contain("grpc-identity-token", "the protocol surface must stay registered"); routeIds.Should().Contain("grpc-identity-manage-users-list", "the management surface must be registered by the module, not only by the tests"); routeIds.Count(id => id.StartsWith("grpc-identity-manage-", StringComparison.Ordinal)) .Should().Be(40, "all five groups ship, or the count says which are missing"); } [Fact] public async Task Unknown_method_address_is_unimplemented() { redb.Identity.Grpc.InitRoute.main(_context); await _context.Start(); var act = async () => await CallAsync("/identity.v1.Identity/Nope"); (await act.Should().ThrowAsync()) .Which.StatusCode.Should().Be(StatusCode.Unimplemented); } [Fact] public async Task Envelope_with_an_unknown_operation_is_unimplemented() { redb.Identity.Grpc.InitRoute.main(_context); await _context.Start(); var envelope = new redb.Route.Grpc.Proto.RedbMessage(); envelope.Headers.Add("operation", "nope"); RpcException? failure = null; byte[]? reply = null; try { reply = await CallAsync("/redb.route.grpc.RedbService/Process", envelope.ToByteArray(), new Metadata { { "operation", "nope" } }); } catch (RpcException ex) { failure = ex; } failure.Should().NotBeNull("the server instead answered: {0}", reply is null ? "(nothing)" : Convert.ToHexString(reply)); failure!.StatusCode.Should().Be(StatusCode.Unimplemented); } [Fact] public async Task Health_probe_answers_serving() { redb.Identity.Grpc.InitRoute.main(_context); await _context.Start(); // grpc.health.v1.Health/Check — what Kubernetes, Consul and Envoy probe. var reply = await CallAsync("/grpc.health.v1.Health/Check"); // HealthCheckResponse { status = SERVING } → field 1, varint 1. reply.Should().Equal((byte)0x08, (byte)0x01); } [Fact] public async Task Config_binder_reads_the_tsak_section() { // The listener came up on the port the merged config declared, not on the 5001 default — which is // the only externally visible proof that the binder ran. redb.Identity.Grpc.InitRoute.main(_context); await _context.Start(); IsReachable("127.0.0.1", _port).Should().BeTrue(); } /// Calls a method address with an empty message and returns the reply bytes. private async Task CallAsync(string methodPath, byte[]? payload = null, Metadata? metadata = null) { using var channel = GrpcChannel.ForAddress($"http://127.0.0.1:{_port}"); var slash = methodPath.LastIndexOf('/'); var marshaller = Marshallers.Create(b => (byte[])b, b => b); var method = new Method( MethodType.Unary, methodPath[1..slash], methodPath[(slash + 1)..], marshaller, marshaller); return await channel.CreateCallInvoker() .AsyncUnaryCall(method, null, metadata is null ? new CallOptions() : new CallOptions(metadata), payload ?? Array.Empty()); } private static bool IsReachable(string host, int port) { using var client = new TcpClient(); try { return client.ConnectAsync(host, port).Wait(TimeSpan.FromSeconds(2)) && client.Connected; } catch { return false; } } private static int GetFreePort() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } } Path: redb-identity/tests/redb.Identity.Tests/Grpc/GrpcIdentityInteropTests.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/Grpc/GrpcIdentityInteropTests.cs ---- using System.Diagnostics; using System.Net.Sockets; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// F4 — the published contract, exercised by a stack that shares no code with ours: an /// @grpc/grpc-js client generated from identity.v1.proto the way any consumer would generate /// it, running in another process inside a container (see C:\Work\yaml\grpc). /// /// This is what the loopback tests cannot show. They use our own byte marshallers against our own /// listener, so a contract that disagreed with itself consistently would still pass. Here a foreign /// implementation parses the .proto we publish and has to accept the bytes we send — including the /// trailers, which is where a non-OK reply keeps the only machine-readable thing it has left. /// /// /// GATED: each test no-ops unless the container answers on 127.0.0.1:18100, so the normal suite stays /// green without Docker. Run docker compose up -d in C:\Work\yaml\grpc first. The gate is /// deliberately loud in one direction only — a missing container skips, a broken contract fails. /// /// [Trait("Category", "Interop")] [Collection("PostgresCollection")] public class GrpcIdentityInteropTests : IClassFixture { private const int ContainerPort = 18100; // the compose-mapped grpc-js host, our proof it is running private readonly GrpcInteropIdentityFixture _fixture; public GrpcIdentityInteropTests(GrpcInteropIdentityFixture fixture) => _fixture = fixture; [Fact] public void A_foreign_client_gets_a_token_from_the_published_contract() { if (!ContainerIsUp()) return; var result = Call("Token", new { grant_type = "client_credentials", client_id = GrpcIdentityFixture.ClientId, client_secret = GrpcIdentityFixture.ClientSecret, scope = GrpcIdentityFixture.GrantedScope, }); result.GetProperty("ok").GetBoolean().Should().BeTrue("{0}", result); var token = result.GetProperty("value"); token.GetProperty("access_token").GetString().Should().NotBeNullOrEmpty(); token.GetProperty("token_type").GetString().Should().Be("Bearer"); } [Fact] public void A_foreign_client_reads_the_refusal_as_a_status_and_a_trailer() { if (!ContainerIsUp()) return; var result = Call("Token", new { grant_type = "client_credentials", client_id = GrpcIdentityFixture.ClientId, client_secret = "not-the-secret", }); result.GetProperty("ok").GetBoolean().Should().BeFalse("a wrong secret must not yield a token"); result.GetProperty("status").GetString().Should().Be("UNAUTHENTICATED"); // The payload of a non-OK reply is discarded by the protocol itself, so this trailer is the only // place the caller can learn *which* refusal it was. result.GetProperty("trailers").GetProperty("error").GetString().Should().Be("invalid_client"); } [Fact] public void A_foreign_client_reads_the_discovery_document() { if (!ContainerIsUp()) return; // A Struct field decoded by a foreign runtime: proves the overflow shape is real protobuf and not // something only our own codec agrees with. var result = Call("Discovery", new { }); result.GetProperty("ok").GetBoolean().Should().BeTrue("{0}", result); var fields = result.GetProperty("value").GetProperty("document").GetProperty("fields"); fields.GetProperty("issuer").GetProperty("stringValue").GetString() .Should().Be($"http://localhost:{_fixture.Port}/"); // The document keeps advertising the server.s HTTP addresses. Rewriting them for gRPC callers // would hand them endpoints that do not exist. fields.GetProperty("token_endpoint").GetProperty("stringValue").GetString() .Should().EndWith("/connect/token"); // A list inside the Struct, decoded by a runtime that never saw our codec. fields.GetProperty("scopes_supported").GetProperty("listValue").GetProperty("values") .EnumerateArray().Should().NotBeEmpty(); } // ── helpers ─────────────────────────────────────────────── /// /// Runs the container's client against our facade and returns its JSON verdict. The request travels /// on stdin: `docker exec` hands argv straight to the process with no shell, and Windows argument /// splitting eats the quotes out of a JSON literal before the container ever sees it. /// private JsonElement Call(string method, object request) { var info = new ProcessStartInfo("docker") { RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, }; foreach (var argument in new[] { "exec", "-i", "grpc-echo", "node", "identity-client.js", $"host.docker.internal:{_fixture.Port}", method, }) { info.ArgumentList.Add(argument); } using var process = Process.Start(info)!; process.StandardInput.Write(JsonSerializer.Serialize(request)); process.StandardInput.Close(); var stdout = process.StandardOutput.ReadToEnd(); var stderr = process.StandardError.ReadToEnd(); process.WaitForExit(60_000); var line = stdout.Split('\n', StringSplitOptions.RemoveEmptyEntries) .LastOrDefault(l => l.TrimStart().StartsWith('{')); line.Should().NotBeNull($"client produced no verdict. stdout={stdout} stderr={stderr}"); return JsonDocument.Parse(line!).RootElement.Clone(); } private static bool ContainerIsUp() { try { using var probe = new TcpClient(); return probe.ConnectAsync("127.0.0.1", ContainerPort).Wait(TimeSpan.FromSeconds(1)); } catch { return false; } } } Path: redb-identity/tests/redb.Identity.Tests/Grpc/GrpcIdentityProcessorsTests.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/Grpc/GrpcIdentityProcessorsTests.cs ---- using System.Reflection; using System.Runtime.ExceptionServices; using AwesomeAssertions; using Grpc.Core; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Grpc; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// F3 — the steps that bridge what Core expects to what gRPC speaks. Tested directly on an exchange: /// these are decisions about headers and statuses, and a transport round-trip would only obscure them. /// public class GrpcIdentityProcessorsTests { // ── correlation id ─────────────────────────────────────── [Fact] public async Task A_caller_supplied_correlation_id_is_kept_and_echoed() { var exchange = NewExchange(); exchange.In.Headers["X-Correlation-Id"] = "caller-trace-1"; await Invoke("PropagateCorrelationId", exchange); exchange.Properties["identity:correlation-id"].Should().Be("caller-trace-1"); exchange.In.GetHeader(GrpcHeaders.TrailerPrefix + "x-correlation-id") .Should().Be("caller-trace-1", "the caller must be able to stitch its logs to ours"); } [Fact] public async Task Reserved_internal_headers_sent_as_metadata_are_stripped_on_ingress() { // The gRPC connector copies caller metadata and envelope headers into In.Headers verbatim; // Core trusts these names (audit attribution, credentials, idempotency operation). Before // the strip a caller could sign the audit log with another user's id and a fabricated // address by sending them as metadata on Token / Revoke / Introspect. var exchange = NewExchange(); foreach (var name in redb.Identity.Contracts.Routes.IdentityReservedInboundHeaders.Names) exchange.In.Headers[name] = "forged"; exchange.In.Headers["SESSION_USER_ID"] = "forged-upper"; exchange.In.Headers["Idempotency-Key"] = "legit-key"; exchange.In.Headers["authorization"] = "Bearer legit"; await Invoke("PropagateCorrelationId", exchange); foreach (var name in redb.Identity.Contracts.Routes.IdentityReservedInboundHeaders.Names) exchange.In.Headers.ContainsKey(name).Should().BeFalse($"'{name}' must only ever be set by a facade processor"); exchange.In.Headers.ContainsKey("SESSION_USER_ID").Should().BeFalse("header names are case-insensitive"); exchange.In.Headers["Idempotency-Key"].Should().Be("legit-key", "caller metadata that is not reserved stays"); exchange.In.Headers["authorization"].Should().Be("Bearer legit"); } [Fact] public async Task A_correlation_id_is_invented_when_the_caller_sent_none() { var exchange = NewExchange(); await Invoke("PropagateCorrelationId", exchange); exchange.Properties["identity:correlation-id"].Should().NotBeNull(); exchange.In.GetHeader(GrpcHeaders.TrailerPrefix + "x-correlation-id") .Should().NotBeNullOrEmpty(); } // ── idempotency ────────────────────────────────────────── [Fact] public async Task The_operation_is_named_so_idempotency_keys_do_not_collide() { // Core composes its idempotency record name from scope, operation, caller and the caller's key. // Without a name every gRPC call would share the bucket "default" and two different operations // carrying one Idempotency-Key would collide. var exchange = NewExchange(); await InvokeFactory("TagOperation", "token", exchange); exchange.In.GetHeader("operation").Should().Be("token"); } // ── upstream statuses ──────────────────────────────────── [Theory] [InlineData(429, StatusCode.ResourceExhausted)] // rate limiting [InlineData(403, StatusCode.PermissionDenied)] // scope guard [InlineData(503, StatusCode.Unavailable)] // database outage [InlineData(404, StatusCode.NotFound)] public async Task A_status_core_decided_reaches_the_caller_as_a_status(int responseCode, StatusCode expected) { // These arrive as redbHttp.ResponseCode because every processor in Core speaks that vocabulary. // Untranslated they would reach the caller as a successful call. var exchange = NewExchange(); exchange.Out = new Message(new Dictionary { ["success"] = false }); exchange.Out.Headers["redbHttp.ResponseCode"] = responseCode; await Invoke("MapErrorToGrpcStatus", exchange); exchange.Out.GetHeader(GrpcHeaders.StatusCode).Should().Be((int)expected); } [Fact] public async Task Retry_after_survives_into_a_trailer() { // Rate limiting says when to come back. A non-OK gRPC reply discards its payload, so that advice // has to travel as a trailer or it is lost. var exchange = NewExchange(); exchange.Out = new Message(new Dictionary()); exchange.Out.Headers["redbHttp.ResponseCode"] = 429; exchange.Out.Headers["Retry-After"] = "30"; await Invoke("MapErrorToGrpcStatus", exchange); exchange.Out.GetHeader(GrpcHeaders.TrailerPrefix + "retry-after").Should().Be("30"); } [Fact] public async Task A_successful_response_code_leaves_the_status_alone() { var exchange = NewExchange(); exchange.Out = new Message(new Dictionary { ["access_token"] = "at" }); exchange.Out.Headers["redbHttp.ResponseCode"] = 200; await Invoke("MapErrorToGrpcStatus", exchange); exchange.Out.Headers.Should().NotContainKey(GrpcHeaders.StatusCode); } [Fact] public async Task An_oauth_error_wins_over_the_response_code_and_lands_in_trailers() { var exchange = NewExchange(); exchange.Out = new Message(new Dictionary { ["error"] = "invalid_client", ["error_description"] = "Unknown client.", }); await Invoke("MapErrorToGrpcStatus", exchange); exchange.Out.GetHeader(GrpcHeaders.StatusCode).Should().Be((int)StatusCode.Unauthenticated); exchange.Out.GetHeader(GrpcHeaders.TrailerPrefix + "error").Should().Be("invalid_client"); exchange.Out.GetHeader(GrpcHeaders.StatusDetail).Should().Be("Unknown client."); } [Fact] public async Task A_rate_limited_answer_keeps_both_its_status_and_its_retry_after() { // The shape Core actually produces: RateLimitProcessor writes an error document AND a 429 AND a // Retry-After. An earlier version read the error first and stopped there, which demoted the answer // to InvalidArgument and dropped the backoff advice - and every test that fed only the response // code went on passing. So this one feeds all three. var exchange = NewExchange(); exchange.Out = new Message(new Dictionary { ["success"] = false, ["error"] = "rate_limited", ["error_description"] = "Too many requests. Please retry later.", }); exchange.Out.Headers["redbHttp.ResponseCode"] = 429; exchange.Out.Headers["Retry-After"] = "60"; await Invoke("MapErrorToGrpcStatus", exchange); exchange.Out.GetHeader(GrpcHeaders.StatusCode).Should().Be((int)StatusCode.ResourceExhausted, "`rate_limited` is in no RFC 6749 table, so only Core's own 429 can name this status"); exchange.Out.GetHeader(GrpcHeaders.TrailerPrefix + "retry-after").Should().Be("60"); exchange.Out.GetHeader(GrpcHeaders.TrailerPrefix + "error").Should().Be("rate_limited"); } // ── the boundary into Core ─────────────────────────────── [Fact] public void An_answer_is_lifted_out_of_the_isolated_exchange() { var facade = NewExchange(); var core = NewExchange(); core.Out = new Message(new Dictionary { ["access_token"] = "at" }); core.Out.Headers["redbHttp.ResponseCode"] = 200; core.Stop(); // the limiter and the granular guard both end this way var merged = AdoptCoreAnswer(facade, core); merged.Should().BeSameAs(facade); facade.IsStopped.Should().BeFalse("a stop Core decided for itself must not end our pipeline"); facade.In.Body.Should().BeSameAs(core.Out.Body); facade.In.Headers.Should().ContainKey("redbHttp.ResponseCode"); } [Fact] public void An_unhandled_core_fault_is_not_swallowed_at_the_boundary() { var facade = NewExchange(); var core = NewExchange(); core.Exception = new InvalidOperationException("the store is down"); var act = () => AdoptCoreAnswer(facade, core); act.Should().Throw("silently adopting a failed call would answer OK"); } [Fact] public void A_fault_core_already_handled_is_left_alone() { // The limiter marks its own short-circuit this way. Its error document is the reply, not a bug. var facade = NewExchange(); var core = NewExchange(); core.Out = new Message(new Dictionary { ["error"] = "rate_limited" }); core.Exception = new InvalidOperationException("marker"); core.ExceptionHandled = true; var act = () => AdoptCoreAnswer(facade, core); act.Should().NotThrow(); } // ── helpers ─────────────────────────────────────────────── /// Calls the merge strategy, unwrapping reflection so a thrown fault keeps its own type. private static IExchange AdoptCoreAnswer(IExchange facade, IExchange core) { try { return (IExchange)ProcessorsType.GetMethod("AdoptCoreAnswer")!.Invoke(null, [facade, core])!; } catch (TargetInvocationException ex) when (ex.InnerException is not null) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } private static Exchange NewExchange() => new(new Message(Array.Empty())); private static Task Invoke(string name, IExchange exchange) { var method = ProcessorsType.GetMethod(name)!; return (Task)method.Invoke(null, [exchange, CancellationToken.None])!; } private static Task InvokeFactory(string name, string argument, IExchange exchange) { var factory = ProcessorsType.GetMethod(name)!; var processor = (Func)factory.Invoke(null, [argument])!; return processor(exchange, CancellationToken.None); } private static readonly Type ProcessorsType = typeof(global::redb.Identity.Grpc.IdentityGrpcTransportOptions).Assembly .GetType("redb.Identity.Grpc.Processors.GrpcIdentityProcessors")!; } Path: redb-identity/tests/redb.Identity.Tests/Grpc/GrpcManagementFailClosedTests.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/Grpc/GrpcManagementFailClosedTests.cs ---- using AwesomeAssertions; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using redb.Identity.Grpc.Management.V1; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// What the management surface does when Core was wired without a management authentication processor — /// a configuration a deployment can reach, and the one where "fails closed" has to be true rather than /// assumed. /// /// Its own class with its own class fixture, deliberately. Booting this second stack inside a test method /// ran InitializeAsync(ensureCreated) and SyncSchemeAsync against the shared database while /// other collections were still running, and twelve unrelated HTTP tests failed for it. A fixture in /// PostgresCollection is serialized against them, which is why every other fixture here is one. /// /// [Collection("PostgresCollection")] public class GrpcManagementFailClosedTests : IClassFixture { private readonly GrpcManagementWithoutAuthFixture _fixture; public GrpcManagementFailClosedTests(GrpcManagementWithoutAuthFixture fixture) => _fixture = fixture; [Fact] public async Task With_no_authentication_route_registered_the_surface_refuses_everything() { // Core registers direct-vm://identity-auth-management only when it was given a management auth // processor. A deployment can wire Core without one and still deploy the gRPC management module — // the authentication hop then points at an address nobody serves. Two comments in this codebase // assert what happens next, and they disagree with each other; neither was ever executed. If the // hop is a no-op on a missing endpoint, every admin operation runs unauthenticated. // The decisive question is not which status comes back, it is whether the operation ran. // A create either left a row behind or it did not, and no amount of status-reading is as // honest as looking. var login = "failclosed-" + Guid.NewGuid().ToString("N")[..10]; var create = new ManagementRequest { Arguments = JsonParser.Default.Parse( $$"""{"login":"{{login}}","email":"{{login}}@example.test","password":"Str0ng!Passw0rd"}"""), }; try { await _fixture.CallManagementRawAsync( "/identity.management.v1.Users/Create", create.ToByteArray(), new Metadata { { "authorization", "Bearer irrelevant-there-is-no-validator" } }); } catch (RpcException) { /* the refusal is expected; the row check below is the proof */ } // Through the fixture's own redb, so the row is looked for in the database the server writes // to, whichever provider the run uses. var created = await _fixture.Redb.UserProvider.GetUserByLoginAsync(login); created.Should().BeNull( "an admin create must not persist anything when authentication could not run"); var request = new ManagementRequest { Arguments = JsonParser.Default.Parse("""{"offset":0,"count":1}"""), }; var act = async () => await _fixture.CallManagementRawAsync( "/identity.management.v1.Users/List", request.ToByteArray(), new Metadata { { "authorization", "Bearer irrelevant-there-is-no-validator" } }); // The operation must not execute. Which refusal it is matters less than that it is one. var ex = await act.Should().ThrowAsync( "an authentication hop that cannot run must stop the call, not wave it through"); ex.Which.StatusCode.Should().NotBe(StatusCode.OK); } } Path: redb-identity/tests/redb.Identity.Tests/Grpc/GrpcManagementResultWireTests.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/Grpc/GrpcManagementResultWireTests.cs ---- using AwesomeAssertions; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using redb.Identity.Grpc.Management.V1; using redb.Identity.Grpc.V1; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// The management answers over gRPC, one case per kind of result body. The controller's JSON reaches the /// caller as a protobuf , so the check is member for member against the JSON these routes /// answered before their bodies became declared types in redb.Identity.Contracts; an error document still /// becomes a status with its error code in the trailers. /// [Collection("PostgresCollection")] public class GrpcManagementResultWireTests : IClassFixture { private readonly GrpcIdentityFixture _fixture; public GrpcManagementResultWireTests(GrpcIdentityFixture fixture) => _fixture = fixture; [Fact] public async Task Not_found_is_a_status_with_the_error_code() { var act = async () => await CallAsync("Applications", "Get", """{"id":"987654321"}"""); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.NotFound); ex.Which.Trailers.GetValue("error").Should().Be("not_found"); } [Fact] public async Task Deleting_a_scope_answers_success_alone() { var name = "wire_" + Guid.NewGuid().ToString("N")[..10]; var created = await CallAsync("Scopes", "Create", $$"""{"name":"{{name}}"}"""); var id = created.Result.StructValue.Fields["id"]; var deleted = await CallAsync("Scopes", "Delete", $$"""{"id":"{{Text(id)}}"}"""); deleted.Result.Should().Be(Value.Parser.ParseJson("""{"success":true}""")); } [Fact] public async Task Deleting_a_user_answers_success_and_the_sessions_revoked() { var id = await CreateUserAsync(); var deleted = await CallAsync("Users", "Delete", $$"""{"id":"{{id}}"}"""); deleted.Result.Should().Be(Value.Parser.ParseJson("""{"success":true,"sessionsRevoked":0}""")); } [Fact] public async Task Revoking_a_subjects_tokens_answers_the_count() { var id = await CreateUserAsync(); var revoked = await CallAsync("Tokens", "RevokeBySubject", $$"""{"userId":{{id}}}"""); revoked.Result.Should().Be(Value.Parser.ParseJson("""{"revokedCount":0}""")); } [Fact] public async Task A_group_answers_its_fields_membership_and_deletion() { var name = "wire-" + Guid.NewGuid().ToString("N")[..8]; var created = await CallAsync("Groups", "Create", $$"""{"name":"{{name}}","groupType":"team","description":"d"}"""); var fields = created.Result.StructValue.Fields; fields.Keys.Should().Equal("id", "name", "parentId", "groupType", "description", "createdAt", "modifiedAt"); fields["name"].StringValue.Should().Be(name); fields["groupType"].StringValue.Should().Be("team"); var groupId = Text(fields["id"]); var userId = await CreateUserAsync(); var check = await CallAsync("Groups", "IsMember", $$"""{"id":"{{groupId}}","userId":"{{userId}}"}"""); check.Result.Should().Be(Value.Parser.ParseJson($$"""{"isMember":false,"groupId":{{groupId}},"userId":{{userId}}}""")); var deleted = await CallAsync("Groups", "Delete", $$"""{"id":"{{groupId}}"}"""); deleted.Result.Should().Be(Value.Parser.ParseJson($$"""{"success":true,"groupId":{{groupId}}}""")); } private async Task CreateUserAsync() { var login = "wire-" + Guid.NewGuid().ToString("N")[..10]; var created = await CallAsync("Users", "Create", $$"""{"login":"{{login}}","email":"{{login}}@example.test","password":"Str0ng!Passw0rd"}"""); // UserResponse declares no JSON names and the gRPC dispatcher has no naming policy: its id is "Id" here. return Text(created.Result.StructValue.Fields["Id"]); } private static string Text(Value value) => value.KindCase == Value.KindOneofCase.NumberValue ? ((long)value.NumberValue).ToString() : value.StringValue; private async Task CallAsync(string service, string method, string argumentsJson) { var request = new ManagementRequest { Arguments = JsonParser.Default.Parse(argumentsJson) }; var metadata = new Metadata { { "authorization", "Bearer " + await AdminTokenAsync() } }; var reply = await _fixture.CallManagementRawAsync( $"/identity.management.v1.{service}/{method}", request.ToByteArray(), metadata); return ManagementResponse.Parser.ParseFrom(reply); } private async Task AdminTokenAsync() { var issued = await _fixture.CallAsync("Token", new TokenRequest { GrantType = "client_credentials", ClientId = GrpcIdentityFixture.ClientId, ClientSecret = GrpcIdentityFixture.ClientSecret, Scope = GrpcIdentityFixture.GrantedScope, }, TokenResponse.Parser); return issued.AccessToken; } } Path: redb-identity/tests/redb.Identity.Tests/Grpc/GrpcManagementSurfaceTests.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/Grpc/GrpcManagementSurfaceTests.cs ---- using System.Reflection; using AwesomeAssertions; using redb.Identity.Management.Controllers; using redb.Route.Controllers.Attributes; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// F6 — the operation table against the controllers it claims to expose. /// /// The table is hand-written, and the two ways it can be wrong are both silent. A missing row means an /// operation simply is not on this transport, and nobody notices until a caller asks for it. A row whose /// Writes disagrees with the controller's own HTTP verb means the authorization gate checks the /// read scope for something that mutates — which is the bad direction. So the table is compared against /// the controllers themselves rather than reviewed by eye. /// /// public class GrpcManagementSurfaceTests { private static readonly Type[] ExposedControllers = [ typeof(UsersController), typeof(ApplicationsController), typeof(GroupsController), typeof(ScopesController), typeof(TokensController), ]; [Fact] public void Both_sides_were_actually_read() { // Every other test in this file compares two sets. If either read came back empty — a renamed // field, a reflection miss — all of them would pass on nothing at all. This is the one that says so. Operations().Should().NotBeEmpty("the operation table was not read; the comparisons below are vacuous"); ControllerActions().Should().NotBeEmpty("no controller actions were found; the comparisons are vacuous"); Operations().Should().HaveSameCount(ControllerActions(), "the transport exposes exactly the actions of the controllers it registers"); } [Fact] public void Every_action_of_an_exposed_controller_has_a_route() { var wired = Operations().Select(o => o.Dispatch).ToHashSet(StringComparer.Ordinal); var actual = ControllerActions().Select(a => a.Dispatch).ToHashSet(StringComparer.Ordinal); actual.Except(wired).Should().BeEmpty( "an exposed controller's action with no route is invisible on this transport, and nothing says so"); } [Fact] public void No_route_points_at_an_action_that_does_not_exist() { var wired = Operations().Select(o => o.Dispatch).ToHashSet(StringComparer.Ordinal); var actual = ControllerActions().Select(a => a.Dispatch).ToHashSet(StringComparer.Ordinal); wired.Except(actual).Should().BeEmpty( "a route to a method that was renamed or removed answers NotFound at dispatch time, not at build time"); } [Fact] public void Read_and_write_match_the_controller_verb() { var byName = ControllerActions().ToDictionary(a => a.Dispatch, a => a.Writes, StringComparer.Ordinal); var mismatched = Operations() .Where(o => byName.TryGetValue(o.Dispatch, out var writes) && writes != o.Writes) .Select(o => $"{o.Dispatch}: table says {(o.Writes ? "write" : "read")}, controller says {(byName[o.Dispatch] ? "write" : "read")}") .ToList(); mismatched.Should().BeEmpty( "a mutating operation marked read is checked against the read scope — the gate would admit it"); } [Fact] public void Dispatch_names_are_qualified() { // Five controllers share method names like List and Delete. GrpcControllerDispatcher resolves an // unqualified name to whichever matched first, so an unqualified row here would route by accident. Operations().Should().OnlyContain(o => o.Dispatch.Contains('.'), "an unqualified dispatch name is ambiguous across five registered controllers"); } // ── reading the two sides ───────────────────────────────── private static IEnumerable<(string Dispatch, bool Writes)> Operations() { var builderType = typeof(redb.Identity.Grpc.IdentityGrpcTransportOptions).Assembly .GetType("redb.Identity.Grpc.GrpcManagementRouteBuilder")!; var table = builderType .GetField("Operations", BindingFlags.NonPublic | BindingFlags.Static)! .GetValue(null)!; foreach (var entry in (System.Collections.IEnumerable)table) { var type = entry.GetType(); yield return ( (string)type.GetProperty("DispatchMethod")!.GetValue(entry)!, (bool)type.GetProperty("Writes")!.GetValue(entry)!); } } private static IEnumerable<(string Dispatch, bool Writes)> ControllerActions() { foreach (var controller in ExposedControllers) { var prefix = controller.Name.EndsWith("Controller", StringComparison.Ordinal) ? controller.Name[..^"Controller".Length] : controller.Name; foreach (var method in controller.GetMethods( BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { var verb = Verb(method); if (verb is null) continue; // helpers, not actions yield return ($"{prefix}.{method.Name}", verb != "GET"); } } } /// The controller's own HTTP verb — the single statement of whether an action mutates. private static string? Verb(MethodInfo method) { if (method.GetCustomAttribute() is not null) return "GET"; if (method.GetCustomAttribute() is not null) return "POST"; if (method.GetCustomAttribute() is not null) return "PUT"; if (method.GetCustomAttribute() is not null) return "PATCH"; if (method.GetCustomAttribute() is not null) return "DELETE"; return null; } } Path: redb-identity/tests/redb.Identity.Tests/Grpc/GrpcManagementTests.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/Grpc/GrpcManagementTests.cs ---- using Microsoft.Extensions.Configuration; using redb.Identity.Core.Models; using AwesomeAssertions; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using redb.Identity.Grpc.Management.V1; using redb.Identity.Grpc.V1; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// F6 — the management surface over gRPC. The tests that matter here are not the happy path: an admin API /// that works is easy, an admin API that refuses correctly is the whole job. So the shape of this file is /// three refusals and one verdict-parity check, with the happy path present only to prove the refusals /// are refusing something that would otherwise have worked. /// [Collection("PostgresCollection")] public class GrpcManagementTests : IClassFixture { private readonly GrpcIdentityFixture _fixture; public GrpcManagementTests(GrpcIdentityFixture fixture) => _fixture = fixture; private const string Service = "/identity.management.v1.Users"; // ── the gate ───────────────────────────────────────────── [Fact] public async Task Without_a_token_an_admin_operation_is_refused_not_executed() { var act = async () => await CallAsync("List", new { offset = 0, count = 5 }, token: null); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.Unauthenticated, "an unauthenticated admin call must be stopped at the gate, not answered"); } [Fact] public async Task A_garbage_token_is_refused() { var act = async () => await CallAsync("List", new { offset = 0, count = 5 }, "not-a-token"); (await act.Should().ThrowAsync()) .Which.StatusCode.Should().Be(StatusCode.Unauthenticated); } [Fact] public async Task A_token_that_may_read_is_refused_a_write() { // The narrow client holds identity:users:read and nothing else. Read passes, write must not — // otherwise the granular table is decorative on this transport. var narrow = await NarrowTokenAsync(); var read = async () => await CallAsync("List", new { offset = 0, count = 1 }, narrow); await read.Should().NotThrowAsync("identity:users:read authorises reading users"); var write = async () => await CallAsync("Delete", new { id = "999999" }, narrow); var ex = await write.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.PermissionDenied, "read does not imply write; the refusal must be PermissionDenied, not a 200 with an error body"); ex.Which.Trailers.GetValue("error").Should().Be("insufficient_scope"); } // ── the surface works at all ───────────────────────────── [Fact] public async Task An_admin_token_lists_users() { var response = await CallAsync("List", new { offset = 0, count = 5 }, await AdminTokenAsync()); // Whatever the store holds, the answer is a decoded protobuf carrying a real JSON value — which is // what proves the Struct round-trip rather than the count of users. response.Result.Should().NotBeNull(); response.Result.KindCase.Should().BeOneOf(Value.KindOneofCase.StructValue, Value.KindOneofCase.ListValue); } [Fact] public async Task A_controller_error_arrives_as_a_status_not_as_a_successful_body() { // Users.Get on an id that does not exist: the controller answers `error = "not_found"` with no // status of its own. Untranslated it would reach the caller as a successful call. var act = async () => await CallAsync("Get", new { id = "999999999" }, await AdminTokenAsync()); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.NotFound); } [Fact] public async Task A_forged_dispatch_header_cannot_redirect_the_call() { // The controller dispatcher routes on a `dispatch-method` header, and that name is not reserved by // the connector — a caller can put it in gRPC metadata and it reaches the exchange. If it survived, // the escalation is direct: authorize as Users/List (a read the narrow token holds) and execute // Users.Delete (a write it does not). The facade overwrites the header before dispatch; this test // is what keeps that true, because the defence is an ordering and orderings get edited. var narrow = await NarrowTokenAsync(); var metadata = new Metadata { { "dispatch-method", "Users.Delete" } }; metadata.Add("authorization", "Bearer " + narrow); var request = new ManagementRequest { Arguments = JsonParser.Default.Parse("""{"offset":0,"count":1}"""), }; var reply = await _fixture.CallManagementRawAsync($"{Service}/List", request.ToByteArray(), metadata); var response = ManagementResponse.Parser.ParseFrom(reply); // The address decides, not the header: this ran List, which the narrow token may do. response.Result.Should().NotBeNull("the call must run the operation its address names"); response.Result.KindCase.Should().BeOneOf(Value.KindOneofCase.StructValue, Value.KindOneofCase.ListValue); } [Fact] public async Task An_idempotency_key_makes_a_repeated_create_one_create() { // Claimed in the package README and never tested. It has to work through two translations: the // caller sends `idempotency-key` as gRPC metadata (HTTP/2 lowercases it), the connector puts that // into the exchange headers, and Core reads `Idempotency-Key` — a different spelling. If the // header dictionary were case-sensitive anywhere along that path, replays would silently create a // second user instead of returning the first. var admin = await AdminTokenAsync(); var login = "idem-" + Guid.NewGuid().ToString("N")[..10]; var key = Guid.NewGuid().ToString("N"); var first = await CreateUser(admin, login, key); var second = await CreateUser(admin, login, key); var firstId = first.Result.StructValue.Fields["Id"].NumberValue; var secondId = second.Result.StructValue.Fields["Id"].NumberValue; secondId.Should().Be(firstId, "the replay must return the original record, not create a second one"); // And the contrast, so the assertion above cannot pass for the wrong reason: a DIFFERENT key is a // different request, so the same login is now a genuine duplicate and must be refused. If the key // were being ignored entirely, this call would replay too and quietly return the same record. var act = async () => await CreateUser(admin, login, Guid.NewGuid().ToString("N")); (await act.Should().ThrowAsync()) .Which.StatusCode.Should().Be(StatusCode.AlreadyExists, "a fresh key means a fresh request, and this login already exists"); } private async Task CreateUser(string token, string login, string idempotencyKey) { var metadata = new Metadata { { "authorization", "Bearer " + token }, { "idempotency-key", idempotencyKey }, }; var request = new ManagementRequest { Arguments = JsonParser.Default.Parse( $$"""{"login":"{{login}}","email":"{{login}}@example.test","password":"Str0ng!Passw0rd"}"""), }; var reply = await _fixture.CallManagementRawAsync( $"{Service}/Create", request.ToByteArray(), metadata); return ManagementResponse.Parser.ParseFrom(reply); } // ── verdict parity, the acceptance criterion ───────────── [Fact] public async Task The_scope_gate_decides_by_scope_and_nothing_else() { // Both transports consult one table in Core (F5), so the property to assert here is that this // transport actually consults it: the same operation is refused for a narrow token and waved // through for an admin one, and the refusal comes from the gate rather than from the controller. var narrow = await NarrowTokenAsync(); var admin = await AdminTokenAsync(); var refused = async () => await CallAsync("Delete", new { id = "999999" }, narrow); (await refused.Should().ThrowAsync()) .Which.StatusCode.Should().Be(StatusCode.PermissionDenied); // The admin token clears the gate. What happens afterwards is the controller's business — deleting // a user that is not there is idempotent here, so this call simply succeeds. The assertion is only // that no gate refused it. RpcException? failure = null; try { await CallAsync("Delete", new { id = "999999" }, admin); } catch (RpcException ex) { failure = ex; } failure?.StatusCode.Should().NotBe(StatusCode.PermissionDenied, "identity:manage authorises this operation; a refusal here would mean the gate ignores scope"); failure?.StatusCode.Should().NotBe(StatusCode.Unauthenticated, "the token is valid; a refusal here would mean the gate ignores the token"); } // ── helpers ─────────────────────────────────────────────── private async Task CallAsync(string method, object arguments, string? token) { var request = new ManagementRequest { Arguments = JsonParser.Default.Parse(System.Text.Json.JsonSerializer.Serialize(arguments)), }; var metadata = new Metadata(); if (token is not null) metadata.Add("authorization", "Bearer " + token); var reply = await _fixture.CallManagementRawAsync($"{Service}/{method}", request.ToByteArray(), metadata); return ManagementResponse.Parser.ParseFrom(reply); } private Task AdminTokenAsync() => TokenAsync(GrpcIdentityFixture.ClientId, GrpcIdentityFixture.ClientSecret, GrpcIdentityFixture.GrantedScope); private Task NarrowTokenAsync() => TokenAsync(GrpcIdentityFixture.NarrowClientId, GrpcIdentityFixture.NarrowClientSecret, GrpcIdentityFixture.NarrowScope); private async Task TokenAsync(string clientId, string secret, string scope) { var issued = await _fixture.CallAsync("Token", new TokenRequest { GrantType = "client_credentials", ClientId = clientId, ClientSecret = secret, Scope = scope, }, TokenResponse.Parser); return issued.AccessToken; } } Path: redb-identity/tests/redb.Identity.Tests/Grpc/GrpcProtocolFlowTests.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/Grpc/GrpcProtocolFlowTests.cs ---- using System.Text; using Google.Protobuf; using System.Text.Json; using AwesomeAssertions; using Grpc.Core; using redb.Identity.Grpc.V1; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// Ф2/Ф3 end to end: the service-to-service protocol over gRPC against the real Core — a token is issued, /// introspected, revoked, and seen dead afterwards. Both spellings of the contract are covered: the typed /// identity.v1 addresses and the generic envelope fallback. /// [Collection("PostgresCollection")] public class GrpcProtocolFlowTests : IClassFixture { private readonly GrpcIdentityFixture _fixture; public GrpcProtocolFlowTests(GrpcIdentityFixture fixture) => _fixture = fixture; [Fact] public async Task Client_credentials_issues_a_token() { var response = await Token(GrpcIdentityFixture.ClientId, "identity:manage"); response.AccessToken.Should().NotBeNullOrEmpty(); response.TokenType.Should().Be("Bearer"); response.ExpiresIn.Should().BeGreaterThan(0); } [Fact] public async Task Issued_token_introspects_as_active_then_dies_on_revocation() { var issued = await Token(GrpcIdentityFixture.ClientId, "identity:manage"); var before = await _fixture.CallAsync("Introspect", new IntrospectRequest { Token = issued.AccessToken, ClientId = GrpcIdentityFixture.ClientId, ClientSecret = GrpcIdentityFixture.ClientSecret, }, IntrospectResponse.Parser); before.Active.Should().BeTrue(); before.ClientId.Should().Be(GrpcIdentityFixture.ClientId); await _fixture.CallAsync("Revoke", new RevokeRequest { Token = issued.AccessToken, ClientId = GrpcIdentityFixture.ClientId, ClientSecret = GrpcIdentityFixture.ClientSecret, }, RevokeResponse.Parser); // Revocation took effect. OpenIddict reports a revoked token as an error rather than as RFC 7662's // `active: false` — the repo records the same behaviour in IntrospectionRevocationTests — so the // proof is the refusal, and our facade carries it as a status rather than as a 200 with a body. var act = async () => await _fixture.CallAsync("Introspect", new IntrospectRequest { Token = issued.AccessToken, ClientId = GrpcIdentityFixture.ClientId, ClientSecret = GrpcIdentityFixture.ClientSecret, }, IntrospectResponse.Parser); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.Unauthenticated); ex.Which.Status.Detail.Should().Contain("no longer valid"); } [Fact] public async Task Discovery_is_passed_through_with_its_http_addresses() { var response = await _fixture.CallAsync("Discovery", new DiscoveryRequest(), DiscoveryResponse.Parser); response.Document.Should().NotBeNull(); response.Document!.Fields.Should().ContainKey("issuer"); // The document advertises the server's HTTP endpoints. Those are the real ones — rewriting them // here would hand callers addresses that do not exist. response.Document.Fields["token_endpoint"].StringValue.Should().Contain("/connect/token"); } [Fact] public async Task Jwks_returns_the_signing_keys() { var response = await _fixture.CallAsync("Jwks", new JwksRequest(), JwksResponse.Parser); response.Document!.Fields["keys"].ListValue.Values.Should().NotBeEmpty(); } [Fact] public async Task An_oauth_error_arrives_as_a_grpc_status_not_as_a_successful_body() { // Without the error mapping this would be a successful call carrying an error document — which no // generated client inspects. var act = async () => await _fixture.CallAsync("Token", new TokenRequest { GrantType = "no_such_grant", ClientId = "x" }, TokenResponse.Parser); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.InvalidArgument); // The machine-readable code survives in a trailer: a non-OK reply has its payload discarded. ex.Which.Trailers.GetValue("error").Should().NotBeNullOrEmpty(); } [Fact] public async Task Unknown_claims_are_not_dropped_they_overflow_into_the_struct() { var issued = await Token(GrpcIdentityFixture.ClientId, "identity:manage"); var introspected = await _fixture.CallAsync("Introspect", new IntrospectRequest { Token = issued.AccessToken, ClientId = GrpcIdentityFixture.ClientId, ClientSecret = GrpcIdentityFixture.ClientSecret, }, IntrospectResponse.Parser); introspected.Active.Should().BeTrue(); // The named RFC 7662 members land in their own slots … introspected.ClientId.Should().Be(GrpcIdentityFixture.ClientId); introspected.Exp.Should().BeGreaterThan(0); // … and nothing the codec has a slot for may be duplicated into the overflow instead. A named // field appearing in `extra` would mean the caller has to look in two places for one claim. var named = IntrospectResponse.Descriptor.Fields.InDeclarationOrder() .Where(f => f.Name != "extra").Select(f => f.Name); (introspected.Extra?.Fields.Keys ?? Enumerable.Empty()) .Should().NotIntersectWith(named); } // ── negative matrix ────────────────────────────────────── [Fact] public async Task A_wrong_client_secret_is_refused_as_unauthenticated() { // Real client registry, BCrypt-hashed secret — this assertion means something only because the // fixture is not in degraded mode. var act = async () => await _fixture.CallAsync("Token", new TokenRequest { GrantType = "client_credentials", ClientId = GrpcIdentityFixture.ClientId, ClientSecret = "not-the-secret", Scope = GrpcIdentityFixture.GrantedScope, }, TokenResponse.Parser); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.Unauthenticated); ex.Which.Trailers.GetValue("error").Should().Be("invalid_client"); } [Fact] public async Task An_unknown_client_is_refused() { var act = async () => await _fixture.CallAsync("Token", new TokenRequest { GrantType = "client_credentials", ClientId = "no-such-client", ClientSecret = "whatever", }, TokenResponse.Parser); (await act.Should().ThrowAsync()) .Which.StatusCode.Should().Be(StatusCode.Unauthenticated); } [Fact] public async Task A_scope_the_client_may_not_have_is_refused() { // The seeded client is permitted exactly one scope. Asking for another must fail rather than // quietly issue a token with fewer scopes than requested. var act = async () => await _fixture.CallAsync("Token", new TokenRequest { GrantType = "client_credentials", ClientId = GrpcIdentityFixture.ClientId, ClientSecret = GrpcIdentityFixture.ClientSecret, Scope = "some:other:scope", }, TokenResponse.Parser); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.InvalidArgument); ex.Which.Trailers.GetValue("error").Should().Be("invalid_scope"); } [Fact] public async Task Introspecting_a_garbage_token_is_refused() { // RFC 7662 §2.2 would allow `active: false`, but OpenIddict answers an unparseable token with an // error, and the repo records that behaviour in IntrospectionRevocationTests. The facade's job is // to carry that verdict faithfully as a status, not to invent an RFC-shaped answer Core never gave. var act = async () => await _fixture.CallAsync("Introspect", new IntrospectRequest { Token = "not-a-real-token", ClientId = GrpcIdentityFixture.ClientId, ClientSecret = GrpcIdentityFixture.ClientSecret, }, IntrospectResponse.Parser); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.Unauthenticated); ex.Which.Trailers.GetValue("error").Should().Be("invalid_token"); } // ── envelope fallback ──────────────────────────────────── [Fact] public async Task The_envelope_path_issues_a_token_too() { // Same surface, second spelling: JSON body plus an `operation` header, for callers that do not // want to carry identity.v1.proto. var body = JsonSerializer.SerializeToUtf8Bytes(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = GrpcIdentityFixture.ClientId, ["client_secret"] = GrpcIdentityFixture.ClientSecret, ["scope"] = "identity:manage", }); var reply = await CallEnvelope("token", body); var json = JsonSerializer.Deserialize(reply); json.GetProperty("access_token").GetString().Should().NotBeNullOrEmpty(); } [Fact] public async Task An_unknown_envelope_operation_is_unimplemented() { RpcException? failure = null; byte[]? reply = null; try { reply = await CallEnvelope("nope", "{}"u8.ToArray()); } catch (RpcException ex) { failure = ex; } failure.Should().NotBeNull( "an unknown operation must be rejected; the server instead answered: {0}", reply is null ? "(nothing)" : Encoding.UTF8.GetString(reply)); failure!.StatusCode.Should().Be(StatusCode.Unimplemented); failure.Status.Detail.Should().Contain("token", "the answer should list what is available"); } // ── helpers ─────────────────────────────────────────────── private Task Token(string clientId, string scope) => _fixture.CallAsync("Token", new TokenRequest { GrantType = "client_credentials", ClientId = clientId, ClientSecret = GrpcIdentityFixture.ClientSecret, Scope = scope, }, TokenResponse.Parser); /// /// Calls the envelope path and unwraps the reply. The generic address runs in envelope mode on both /// legs, so the answer comes back inside a RedbMessage — the JSON body is its payload. /// private async Task CallEnvelope(string operation, byte[] body) { var reply = await _fixture.CallRawAsync("/redb.route.grpc.RedbService/Process", Envelope(operation, body), new Metadata { { "operation", operation } }); return redb.Route.Grpc.Proto.RedbMessage.Parser.ParseFrom(reply).Payload.ToByteArray(); } /// Wraps a JSON body in the connector's generic RedbMessage envelope. private static byte[] Envelope(string operation, byte[] body) { var message = new redb.Route.Grpc.Proto.RedbMessage { Payload = Google.Protobuf.ByteString.CopyFrom(body), }; message.Headers.Add("operation", operation); return message.ToByteArray(); } } Path: redb-identity/tests/redb.Identity.Tests/Grpc/GrpcRateLimitTests.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/Grpc/GrpcRateLimitTests.cs ---- using AwesomeAssertions; using Grpc.Core; using redb.Identity.Grpc.V1; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// F4 — the per-IP limiter, over gRPC, for real. Core keys it on redbHttp.RemoteAddress, a header /// no gRPC call has of its own: the listener synthesizes it from the connection peer because the facade /// asks for EmitHttpCompatHeaders. If that bridge ever breaks, the limiter does not fail loudly — /// it silently stops protecting the gRPC port, and every other test in this suite still passes. This is /// the one that would not. /// [Collection("PostgresCollection")] public class GrpcRateLimitTests : IClassFixture { private readonly GrpcThrottledIdentityFixture _fixture; public GrpcRateLimitTests(GrpcThrottledIdentityFixture fixture) => _fixture = fixture; [Fact] public async Task A_caller_over_the_per_ip_limit_is_told_to_back_off() { RpcException? rejection = null; // A couple more than the limit: enough to cross it, few enough that the failure message names a // number rather than "somewhere in a hundred calls". for (var attempt = 1; attempt <= GrpcThrottledIdentityFixture.PerIpPerMinute + 2; attempt++) { try { await _fixture.CallAsync("Token", new TokenRequest { GrantType = "client_credentials", ClientId = GrpcIdentityFixture.ClientId, ClientSecret = GrpcIdentityFixture.ClientSecret, Scope = GrpcIdentityFixture.GrantedScope, }, TokenResponse.Parser); } catch (RpcException ex) when (ex.StatusCode == StatusCode.ResourceExhausted) { rejection = ex; break; } } rejection.Should().NotBeNull( "the per-IP limit is {0}/minute, so a run of {1} calls from one address must be cut short", GrpcThrottledIdentityFixture.PerIpPerMinute, GrpcThrottledIdentityFixture.PerIpPerMinute + 2); // 429 in the HTTP facade, ResourceExhausted here — the same verdict, spelled in the caller's // protocol rather than translated back through a status code they would have to know about. rejection!.Trailers.GetValue("error").Should().Be("rate_limited"); // A non-OK reply discards its payload, so "come back in N seconds" only survives as a trailer. rejection.Trailers.GetValue("retry-after").Should().NotBeNullOrEmpty( "a limiter that will not say when to retry leaves the caller guessing"); } } Path: redb-identity/tests/redb.Identity.Tests/Grpc/GrpcSplitPortTests.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/Grpc/GrpcSplitPortTests.cs ---- using AwesomeAssertions; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using redb.Identity.Grpc.Management.V1; using redb.Identity.Grpc.V1; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// The production port layout: the admin surface on a port of its own, firewalled separately from the /// protocol surface every relying party calls. /// /// Until this fixture existed, EffectiveManagementPort only ever took its null → same port /// branch. A split that has never run is not a supported configuration, it is a config key that looks /// like one — and the way it would fail is the worst kind: admin operations quietly still answering on /// the public port, so the firewall rule protects nothing. /// /// [Collection("PostgresCollection")] public class GrpcSplitPortTests : IClassFixture { private readonly GrpcSplitPortIdentityFixture _fixture; public GrpcSplitPortTests(GrpcSplitPortIdentityFixture fixture) => _fixture = fixture; private const string Users = "/identity.management.v1.Users"; [Fact] public void The_two_surfaces_really_are_on_different_ports() { _fixture.EffectiveManagementPort.Should().NotBe(_fixture.Port, "the rest of this class asserts nothing if the fixture quietly shared one port"); } [Fact] public async Task The_admin_surface_answers_on_the_management_port() { var response = await CallManagement("List", await AdminTokenAsync()); response.Result.Should().NotBeNull(); } [Fact] public async Task The_admin_surface_is_not_reachable_on_the_public_port() { // The point of splitting the ports. If the admin address answered here too, a firewall rule on the // management port would be decoration. var act = async () => await _fixture.CallRawAsync( $"{Users}/List", Request().ToByteArray(), Bearer(await AdminTokenAsync())); var ex = await act.Should().ThrowAsync(); ex.Which.StatusCode.Should().Be(StatusCode.Unimplemented, "the public port serves the protocol surface and must not know the admin addresses"); } [Fact] public async Task The_protocol_surface_still_answers_on_the_public_port() { // The other half of the split: moving the admin surface must not move anything else. var issued = await _fixture.CallAsync("Token", new TokenRequest { GrantType = "client_credentials", ClientId = GrpcIdentityFixture.ClientId, ClientSecret = GrpcIdentityFixture.ClientSecret, Scope = GrpcIdentityFixture.GrantedScope, }, TokenResponse.Parser); issued.AccessToken.Should().NotBeNullOrEmpty(); } [Fact] public async Task The_gate_is_still_a_gate_on_the_management_port() { // Splitting ports must not move the authentication step off the path it protects. var act = async () => await CallManagement("List", token: null); (await act.Should().ThrowAsync()) .Which.StatusCode.Should().Be(StatusCode.Unauthenticated); } // ── helpers ─────────────────────────────────────────────── private static ManagementRequest Request() => new() { Arguments = JsonParser.Default.Parse("""{"offset":0,"count":1}"""), }; private static Metadata? Bearer(string? token) => token is null ? null : new Metadata { { "authorization", "Bearer " + token } }; private async Task CallManagement(string method, string? token) { var reply = await _fixture.CallManagementRawAsync( $"{Users}/{method}", Request().ToByteArray(), Bearer(token)); return ManagementResponse.Parser.ParseFrom(reply); } private async Task AdminTokenAsync() { var issued = await _fixture.CallAsync("Token", new TokenRequest { GrantType = "client_credentials", ClientId = GrpcIdentityFixture.ClientId, ClientSecret = GrpcIdentityFixture.ClientSecret, Scope = GrpcIdentityFixture.GrantedScope, }, TokenResponse.Parser); return issued.AccessToken; } } Path: redb-identity/tests/redb.Identity.Tests/Grpc/IdentityGrpcCodecTests.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/Grpc/IdentityGrpcCodecTests.cs ---- using AwesomeAssertions; using redb.Identity.Grpc; using redb.Identity.Grpc.V1; using Xunit; namespace redb.Identity.Tests.Grpc; /// /// F1 — the codec between the published identity.v1 contract and the parameter/answer shapes the /// direct-vm://identity-* boundary speaks. Mapping is descriptor-driven, so these tests are really /// about the rules: what is omitted, what overflows into the Struct, what survives a type it cannot hold. /// public class IdentityGrpcCodecTests { // ── request → parameters ───────────────────────────────── [Fact] public void Named_fields_become_parameters_under_their_proto_names() { var request = new TokenRequest { GrantType = "client_credentials", ClientId = "svc", ClientSecret = "s3cret", Scope = "identity:manage", }; var parameters = IdentityGrpcCodec.ToParameters(request); parameters.Should().Contain("grant_type", "client_credentials"); parameters.Should().Contain("client_id", "svc"); parameters.Should().Contain("client_secret", "s3cret"); parameters.Should().Contain("scope", "identity:manage"); } [Fact] public void Empty_fields_are_omitted_not_sent_blank() { // OAuth distinguishes «absent» from «present and empty»: sending code="" on a // client_credentials request would make the server reject a request it should accept. var parameters = IdentityGrpcCodec.ToParameters(new TokenRequest { GrantType = "client_credentials" }); parameters.Should().ContainKey("grant_type"); parameters.Should().NotContainKey("code"); parameters.Should().NotContainKey("refresh_token"); parameters.Should().NotContainKey("username"); } [Fact] public void Additional_map_is_merged_flat() { // An extension parameter is a parameter — the boundary must not see a nested bag. var request = new TokenRequest { GrantType = "urn:example:custom" }; request.Additional.Add("resource", "https://api.example.com"); request.Additional.Add("audience", "orders"); var parameters = IdentityGrpcCodec.ToParameters(request); parameters.Should().Contain("resource", "https://api.example.com"); parameters.Should().Contain("audience", "orders"); parameters.Should().NotContainKey("additional"); } // ── answer → response ──────────────────────────────────── [Fact] public void Named_response_fields_are_filled_by_proto_name() { var answer = new Dictionary { ["access_token"] = "at", ["token_type"] = "Bearer", ["expires_in"] = 3600L, ["scope"] = "openid", }; var response = new TokenResponse(); IdentityGrpcCodec.Populate(response, answer, "extra"); response.AccessToken.Should().Be("at"); response.TokenType.Should().Be("Bearer"); response.ExpiresIn.Should().Be(3600); response.Scope.Should().Be("openid"); response.Extra.Should().BeNull("nothing was left over"); } [Fact] public void Unknown_keys_overflow_into_the_struct_instead_of_being_dropped() { // Introspection extensions (RFC 7662 §2.2) and vendor claims are open sets. Dropping them would // lose data the caller explicitly asked for. var answer = new Dictionary { ["access_token"] = "at", ["x_tenant"] = "acme", ["x_quota"] = 42L, }; var response = new TokenResponse(); IdentityGrpcCodec.Populate(response, answer, "extra"); response.AccessToken.Should().Be("at"); response.Extra.Should().NotBeNull(); response.Extra!.Fields["x_tenant"].StringValue.Should().Be("acme"); response.Extra.Fields["x_quota"].NumberValue.Should().Be(42); } [Fact] public void Repeated_fields_accept_a_list_and_a_single_value() { var many = new IntrospectResponse(); IdentityGrpcCodec.Populate(many, new Dictionary { ["active"] = true, ["aud"] = new object?[] { "api-a", "api-b" }, }, "extra"); many.Active.Should().BeTrue(); many.Aud.Should().Equal("api-a", "api-b"); // OpenIddict flattens a single-element audience to a bare string; the contract still says repeated. var one = new IntrospectResponse(); IdentityGrpcCodec.Populate(one, new Dictionary { ["aud"] = "api-a" }, "extra"); one.Aud.Should().Equal("api-a"); } [Fact] public void Numbers_and_booleans_survive_their_wire_representations() { var response = new IntrospectResponse(); IdentityGrpcCodec.Populate(response, new Dictionary { ["active"] = "true", // a processor may hand back the string form ["exp"] = 1_700_000_000L, ["iat"] = 1_699_999_000d, // JSON numbers arrive as double when not integral }, "extra"); response.Active.Should().BeTrue(); response.Exp.Should().Be(1_700_000_000); response.Iat.Should().Be(1_699_999_000); } [Fact] public void A_value_the_field_cannot_hold_falls_through_to_the_struct() { // Better than failing the call: the caller still sees the value, just not in the typed slot. var response = new IntrospectResponse(); IdentityGrpcCodec.Populate(response, new Dictionary { ["exp"] = "not-a-number", ["active"] = true, }, "extra"); response.Active.Should().BeTrue(); response.Exp.Should().Be(0); response.Extra!.Fields["exp"].StringValue.Should().Be("not-a-number"); } [Fact] public void Nested_objects_and_arrays_become_struct_values() { var response = new UserInfoResponse(); IdentityGrpcCodec.Populate(response, new Dictionary { ["sub"] = "user-1", ["roles"] = new object?[] { "admin", "ops" }, ["address"] = new Dictionary { ["country"] = "RU" }, }, "claims"); response.Sub.Should().Be("user-1"); response.Claims!.Fields["roles"].ListValue.Values.Select(v => v.StringValue) .Should().Equal("admin", "ops"); response.Claims.Fields["address"].StructValue.Fields["country"].StringValue.Should().Be("RU"); } [Fact] public void Document_responses_pass_the_answer_through_verbatim() { // Discovery advertises the server's HTTP addresses — those are the real ones, and this facade // does not rewrite them. var answer = new Dictionary { ["issuer"] = "https://id.example.com", ["token_endpoint"] = "https://id.example.com/connect/token", }; var response = new DiscoveryResponse(); IdentityGrpcCodec.PopulateDocument(response, answer, "document"); response.Document!.Fields["issuer"].StringValue.Should().Be("https://id.example.com"); response.Document.Fields["token_endpoint"].StringValue .Should().Be("https://id.example.com/connect/token"); } [Fact] public void Empty_answer_leaves_the_response_empty() { var response = new RevokeResponse(); // RFC 7009 §2.2: a successful revocation carries no content. Nothing to map, nothing to fail on. IdentityGrpcCodec.Populate(response, new Dictionary(), "extra"); response.CalculateSize().Should().Be(0); } } Path: redb-identity/tests/redb.Identity.Tests/Health/IdentityHealthContributorTests.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/Health/IdentityHealthContributorTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection.KeyManagement; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using NSubstitute; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Health; using redb.Tsak.Contracts; using Xunit; namespace redb.Identity.Tests.Health; /// /// Unit tests for covering the three probes /// (database, signing-keys, data-protection) and the worst-status aggregation rule. /// public class IdentityHealthContributorTests { [Fact] public async Task AllProbesGreen_ReturnsHealthy() { var sp = BuildProvider(dbVersion: "PostgreSQL 16.2", signingKeys: 1, dpKeys: 1); var contributor = new IdentityHealthContributor(sp, NullLogger.Instance); var status = await contributor.CheckHealthAsync(CancellationToken.None); status.Should().Be(HealthStatus.Healthy); contributor.ModuleName.Should().Be("identity"); } [Fact] public async Task DatabaseUnreachable_ReturnsUnhealthy() { var redb = Substitute.For(); redb.GetDbVersionAsync(Arg.Any()) .Returns>(_ => throw new InvalidOperationException("DB down")); var sp = BuildProvider(redb: redb, signingKeys: 1, dpKeys: 1); var contributor = new IdentityHealthContributor(sp, NullLogger.Instance); var status = await contributor.CheckHealthAsync(CancellationToken.None); status.Should().Be(HealthStatus.Unhealthy); } [Fact] public async Task DatabaseEmptyVersion_ReturnsUnhealthy() { var sp = BuildProvider(dbVersion: "", signingKeys: 1, dpKeys: 1); var contributor = new IdentityHealthContributor(sp, NullLogger.Instance); var status = await contributor.CheckHealthAsync(CancellationToken.None); status.Should().Be(HealthStatus.Unhealthy); } [Fact] public async Task NoSigningKeys_ReturnsUnhealthy() { var sp = BuildProvider(dbVersion: "PostgreSQL 16.2", signingKeys: 0, dpKeys: 1); var contributor = new IdentityHealthContributor(sp, NullLogger.Instance); var status = await contributor.CheckHealthAsync(CancellationToken.None); status.Should().Be(HealthStatus.Unhealthy); } [Fact] public async Task NoDataProtectionKeys_ReturnsDegraded() { var sp = BuildProvider(dbVersion: "PostgreSQL 16.2", signingKeys: 1, dpKeys: 0); var contributor = new IdentityHealthContributor(sp, NullLogger.Instance); var status = await contributor.CheckHealthAsync(CancellationToken.None); status.Should().Be(HealthStatus.Degraded); } [Fact] public async Task DatabaseAndSigningBoth_Unhealthy_ReturnsUnhealthy() { // Worst-status wins: even though data-protection is fine, db+signing failure dominates. var sp = BuildProvider(dbVersion: "", signingKeys: 0, dpKeys: 1); var contributor = new IdentityHealthContributor(sp, NullLogger.Instance); var status = await contributor.CheckHealthAsync(CancellationToken.None); status.Should().Be(HealthStatus.Unhealthy); } [Fact] public async Task SigningOptionsMissing_ReturnsUnhealthy() { // No IOptionsMonitor registered at all. var redb = Substitute.For(); redb.GetDbVersionAsync(Arg.Any()).Returns("v1"); var keyManager = Substitute.For(); keyManager.GetAllKeys().Returns(new List { Substitute.For() }); var services = new ServiceCollection(); services.AddScoped(_ => redb); services.AddSingleton(keyManager); var sp = services.BuildServiceProvider(); var contributor = new IdentityHealthContributor(sp, NullLogger.Instance); var status = await contributor.CheckHealthAsync(CancellationToken.None); status.Should().Be(HealthStatus.Unhealthy); } [Fact] public async Task Cancellation_PropagatesFromDbProbe() { var redb = Substitute.For(); redb.GetDbVersionAsync(Arg.Any()) .Returns>(_ => throw new OperationCanceledException()); var sp = BuildProvider(redb: redb, signingKeys: 1, dpKeys: 1); var contributor = new IdentityHealthContributor(sp, NullLogger.Instance); // OperationCanceledException is not caught — bubbles up so the probe respects cancellation. await Assert.ThrowsAsync( () => contributor.CheckHealthAsync(CancellationToken.None)); } // ----------------------------------------------------------------------- private static IServiceProvider BuildProvider( string? dbVersion = null, IRedbService? redb = null, int signingKeys = 0, int dpKeys = 0) { var services = new ServiceCollection(); if (redb is null) { redb = Substitute.For(); redb.GetDbVersionAsync(Arg.Any()).Returns(dbVersion); } services.AddScoped(_ => redb); var serverOptions = new OpenIddictServerOptions(); for (int i = 0; i < signingKeys; i++) { var bytes = new byte[64]; Random.Shared.NextBytes(bytes); serverOptions.SigningCredentials.Add(new SigningCredentials( new SymmetricSecurityKey(bytes), SecurityAlgorithms.HmacSha256)); } services.AddSingleton>( new StaticOptionsMonitor(serverOptions)); var keyManager = Substitute.For(); var keys = new List(); for (int i = 0; i < dpKeys; i++) keys.Add(Substitute.For()); keyManager.GetAllKeys().Returns(keys); services.AddSingleton(keyManager); return services.BuildServiceProvider(); } private sealed class StaticOptionsMonitor : IOptionsMonitor { public StaticOptionsMonitor(T value) => CurrentValue = value; public T CurrentValue { get; } public T Get(string? name) => CurrentValue; public IDisposable? OnChange(Action listener) => null; } } Path: redb-identity/tests/redb.Identity.Tests/Http/BearerTransportTests.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/Http/BearerTransportTests.cs ---- using System.Net; using System.Net.Http.Headers; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http; /// /// G9 / D6 — bearer-token transport rules. /// /// Protected endpoints (userinfo, management API, SCIM) accept the access token /// ONLY in the Authorization: Bearer header per RFC 6750 §2. Identity /// deliberately does NOT honour RFC 6750 §2.3 (URI query parameter) because: /// /// Query-string tokens leak into access logs, proxy logs, Referer /// headers, and browser history; /// The RFC's own §2.3 is advisory and marked "SHOULD NOT use"; /// Major IdPs (Auth0, Okta, Google) disabled query-param bearer years ago. /// /// These tests pin the contract so a future "helpful" refactor that enables query /// bearer cannot ship without noise. /// /// [Collection("ProductionHttp")] public sealed class BearerTransportTests { private readonly ProductionHttpFixture _fx; public BearerTransportTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task ManagementApi_WithBearerInQueryString_IsRejected() { // Use a valid management token but present it in the query string rather than // the Authorization header. The server must ignore the query param entirely // and reject the call as anonymous. var path = $"/api/v1/identity/users?access_token={Uri.EscapeDataString(_fx.ManagementToken)}"; using var req = new HttpRequestMessage(HttpMethod.Get, path); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().Be(401, "access_token in the query string MUST NOT authenticate the caller (D6). " + "Otherwise a bearer token accidentally logged by an upstream proxy / " + "browser history / server access log would remain a usable credential " + "until expiry. Response: {0}", resp.StatusCode); } [Fact] public async Task Userinfo_WithBearerInQueryString_IsRejected() { // Userinfo is the canonical browser-facing protected endpoint — extra // important that it never honours query-string bearer (it WOULD end up // in Referer headers to third-party analytics scripts). var path = $"/connect/userinfo?access_token={Uri.EscapeDataString(_fx.ManagementToken)}"; using var req = new HttpRequestMessage(HttpMethod.Get, path); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().BeOneOf(new[] { 400, 401 }, "/connect/userinfo with access_token in the URL must reject — Referer leakage " + "to third-party scripts loaded by the redirecting client would otherwise " + "export the token to the entire ad/analytics graph. OpenIddict may answer " + "401 (missing bearer) or 400 (invalid_request) depending on pipeline order; " + "either is an acceptable rejection, but 2xx is a privacy regression."); } [Theory] [InlineData("bearer")] // RFC 6750 §2.1: case-insensitive scheme [InlineData("BEARER")] [InlineData("BeArEr")] public async Task ManagementApi_AcceptsBearerSchemeCaseInsensitively(string schemeCasing) { // RFC 6750 §2.1 / D6: the scheme token is case-insensitive. Clients in the wild // (including some enterprise proxies) uppercase it; rejecting them would be // non-interop. The parser under test is the one in HttpIdentityProcessors. using var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/users"); req.Headers.TryAddWithoutValidation("Authorization", $"{schemeCasing} {_fx.ManagementToken}"); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().BeInRange(200, 299, "bearer scheme is case-insensitive per RFC 6750 §2.1 — '{0}' must be " + "accepted. A regression that exact-matched 'Bearer' would break " + "interop with legitimate clients. Status: {1}", schemeCasing, resp.StatusCode); } [Fact] public async Task ManagementApi_WithoutAuthorizationHeader_Returns401() { // Pure negative: no Authorization header at all → 401. The Retry-After-ish // sibling is already in AdminEndpointAuthMatrixTests; this is the D6 shape. using var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/users"); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().Be(401); } [Fact] public async Task ManagementApi_WithMalformedBearerHeader_Returns401() { // Authorization header without a token value, or with Basic scheme, or just // "Bearer" → 401 (parser rejects rather than silently accepting). using var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/users"); req.Headers.TryAddWithoutValidation("Authorization", "Bearer"); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().Be(401, "an Authorization header with scheme 'Bearer' but no token MUST 401 — " + "silently treating it as 'no token' is fine, but it must never be " + "interpreted as a blank token that passes validation."); } } Path: redb-identity/tests/redb.Identity.Tests/Http/Controllers/ApplicationsControllerTests.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/Http/Controllers/ApplicationsControllerTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Identity.Contracts.Applications; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Routes; using redb.Identity.Management.Controllers;using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Http.Controllers; public class ApplicationsControllerTests { private readonly IRouteContext _ctx = Substitute.For(); private readonly IEndpoint _endpoint = Substitute.For(); private readonly IProducer _producer = Substitute.For(); private readonly ApplicationsController _sut; private IExchange? _captured; public ApplicationsControllerTests() { _ctx.GetEndpoint(IdentityEndpoints.ManageApps).Returns(_endpoint); _endpoint.CreateProducer().Returns(_producer); _producer.Process(Arg.Do(e => _captured = e), Arg.Any()) .Returns(Task.CompletedTask); _sut = new ApplicationsController(); _sut.Context = _ctx; } [Fact] public async Task Get_NumericId_ForwardsWithNumericId() { await _sut.Get("42"); _captured!.In.Headers["operation"].Should().Be("read"); var body = _captured.In.Body as Dictionary; body.Should().NotBeNull(); body!["id"].Should().Be(42L); } [Fact] public async Task Get_StringId_ForwardsWithClientId() { await _sut.Get("my-app"); _captured!.In.Headers["operation"].Should().Be("read"); var body = _captured.In.Body as Dictionary; body.Should().NotBeNull(); body!["clientId"].Should().Be("my-app"); } [Fact] public async Task Update_SetsIdOnRequest() { var req = new UpdateApplicationRequest { DisplayName = "Updated" }; await _sut.Update("app-1", req); _captured!.In.Headers["operation"].Should().Be("update"); req.Id.Should().Be("app-1"); _captured.In.Body.Should().BeSameAs(req); } [Fact] public async Task Delete_NumericId_ForwardsWithNumericId() { await _sut.Delete("99"); _captured!.In.Headers["operation"].Should().Be("delete"); var body = _captured.In.Body as Dictionary; body!["id"].Should().Be(99L); } [Fact] public async Task Delete_StringId_ForwardsWithClientId() { await _sut.Delete("my-app"); _captured!.In.Headers["operation"].Should().Be("delete"); var body = _captured.In.Body as Dictionary; body!["clientId"].Should().Be("my-app"); } [Fact] public async Task Forward_SetsInOutPattern() { await _sut.List(); _captured!.Pattern.Should().Be(ExchangePattern.InOut); } [Fact] public async Task Forward_ReturnsOutBody_WhenAvailable() { _producer.Process(Arg.Any(), Arg.Any()) .Returns(ci => { var ex = ci.Arg(); // Simulate pipeline setting Out ex.Out = Substitute.For(); ex.Out.Body.Returns("result-data"); return Task.CompletedTask; }); var result = await _sut.List(); result.Should().Be("result-data"); } } Path: redb-identity/tests/redb.Identity.Tests/Http/Controllers/ConsentsControllerTests.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/Http/Controllers/ConsentsControllerTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Identity.Contracts.Routes; using redb.Identity.Management.Controllers;using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Http.Controllers; public class ConsentsControllerTests { private readonly IRouteContext _ctx = Substitute.For(); private readonly IEndpoint _endpoint = Substitute.For(); private readonly IProducer _producer = Substitute.For(); private readonly ConsentsController _sut; private IExchange? _captured; public ConsentsControllerTests() { _ctx.GetEndpoint(IdentityEndpoints.ManageConsents).Returns(_endpoint); _endpoint.CreateProducer().Returns(_producer); _producer.Process(Arg.Do(e => _captured = e), Arg.Any()) .Returns(Task.CompletedTask); _sut = new ConsentsController(); _sut.Context = _ctx; } // ── ListByUser ── [Fact] public async Task ListByUser_NumericId_ForwardsAsLong() { await _sut.ListByUser("42"); _captured!.In.Headers["operation"].Should().Be("list"); var body = _captured.In.Body as Dictionary; body.Should().NotBeNull(); body!["userId"].Should().Be(42L); } [Fact] public async Task ListByUser_NonNumericId_DefaultsToZero() { await _sut.ListByUser("abc"); var body = _captured!.In.Body as Dictionary; body!["userId"].Should().Be(0L); } // ── Revoke ── [Fact] public async Task Revoke_NumericIds_ForwardsUserAndAppId() { await _sut.Revoke("42", "99"); _captured!.In.Headers["operation"].Should().Be("revoke"); var body = _captured.In.Body as Dictionary; body.Should().NotBeNull(); body!["userId"].Should().Be(42L); body["applicationId"].Should().Be(99L); } [Fact] public async Task Revoke_NonNumericUserId_DefaultsToZero() { await _sut.Revoke("abc", "99"); var body = _captured!.In.Body as Dictionary; body!["userId"].Should().Be(0L); body["applicationId"].Should().Be(99L); } [Fact] public async Task Revoke_NonNumericAppId_DefaultsToZero() { await _sut.Revoke("42", "not-a-number"); var body = _captured!.In.Body as Dictionary; body!["userId"].Should().Be(42L); body["applicationId"].Should().Be(0L); } // ── RevokeAll ── [Fact] public async Task RevokeAll_NumericId_ForwardsUserId() { await _sut.RevokeAll("7"); _captured!.In.Headers["operation"].Should().Be("revoke-all"); var body = _captured.In.Body as Dictionary; body!["userId"].Should().Be(7L); } [Fact] public async Task RevokeAll_NonNumericId_DefaultsToZero() { await _sut.RevokeAll("xyz"); var body = _captured!.In.Body as Dictionary; body!["userId"].Should().Be(0L); } // ── Exchange pattern ── [Fact] public async Task Forward_SetsInOutPattern() { await _sut.ListByUser("1"); _captured!.Pattern.Should().Be(ExchangePattern.InOut); } } Path: redb-identity/tests/redb.Identity.Tests/Http/Controllers/DisabledFeatureEndpointTests.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/Http/Controllers/DisabledFeatureEndpointTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Routes; using redb.Identity.Contracts.Users; using redb.Identity.Management; using redb.Identity.Management.Controllers; using redb.Route.Abstractions; using redb.Route.Components; using Xunit; namespace redb.Identity.Tests.Http.Controllers; /// /// A feature that is switched off answers "no such endpoint", not a failure. /// /// Self-service registration, e-mail verification, e-mail change and WebAuthn bind their /// direct-vm:// routes only when enabled, while the facades mount their controllers /// regardless. A caller reaching a disabled feature therefore arrived at a producer with nothing /// behind it, and the InvalidOperationException that followed reached the client as a /// generic failure with an unhandled-exception stack trace in the log — observed on a running /// worker as POST /account/register answering 400 with /// No consumer registered for direct-vm endpoint 'identity-account-register'. /// /// /// The contract these tests pin is the one the client SDK already reads: 404, which /// IdentityClient.RegisterAccountAsync translates into registration_disabled. /// /// public class DisabledFeatureEndpointTests { private readonly IRouteContext _ctx = Substitute.For(); private readonly IEndpoint _endpoint = Substitute.For(); private readonly IProducer _producer = Substitute.For(); private readonly SharedVmRegistry _registry = new(); private readonly AccountRegistrationController _sut; public DisabledFeatureEndpointTests() { _ctx.GetEndpoint(IdentityEndpoints.AccountRegister).Returns(_endpoint); _endpoint.CreateProducer().Returns(_producer); // What the real DirectVmProducer does when the route was never bound. Reaching it at all // is the defect, so the substitute fails the same way instead of quietly succeeding. _producer.Process(Arg.Any(), Arg.Any()) .Returns(_ => throw new InvalidOperationException( "No consumer registered for direct-vm endpoint 'direct-vm://identity-account-register'.")); var sp = new ServiceCollection().AddSingleton(_registry).BuildServiceProvider(); _ctx.GetServiceProvider().Returns(sp); _sut = new AccountRegistrationController { Context = _ctx }; } private static RegisterAccountRequest Request() => new() { Login = "newcomer", Email = "newcomer@example.test", Password = "Test@Password123", }; [Fact] public async Task An_unbound_route_answers_not_found_instead_of_failing() { var result = await _sut.Register(Request()); var error = result.Should().BeOfType().Subject.Error; error.Should().Be("not_found", "the deployment does not expose this operation, which is a 404 and not an error the " + "caller can do anything about"); ManagementErrorCodes.ToStatusCode(error!).Should().Be(404, "this is the answer IdentityClient reads back as registration_disabled"); } [Fact] public async Task An_unbound_route_is_not_even_sent_to() { await _sut.Register(Request()); await _producer.DidNotReceive().Process(Arg.Any(), Arg.Any()); } [Fact] public async Task A_bound_route_is_forwarded_as_before() { // The guard must cost nothing when the feature is on: with a consumer in the registry the // call goes through to the producer exactly as it always did. IExchange? captured = null; _producer.Process(Arg.Do(e => captured = e), Arg.Any()) .Returns(Task.CompletedTask); _registry.TryRegisterProcessor(IdentityEndpoints.AccountRegister, Substitute.For()) .Should().BeTrue(); await _sut.Register(Request()); captured.Should().NotBeNull(); captured!.In.Headers["operation"].Should().Be("register"); } } Path: redb-identity/tests/redb.Identity.Tests/Http/Controllers/GroupsControllerTests.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/Http/Controllers/GroupsControllerTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Identity.Contracts.Groups; using redb.Identity.Contracts.Routes; using redb.Identity.Management.Controllers;using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Http.Controllers; public class GroupsControllerTests { private readonly IRouteContext _ctx = Substitute.For(); private readonly IEndpoint _endpoint = Substitute.For(); private readonly IProducer _producer = Substitute.For(); private readonly GroupsController _sut; private IExchange? _captured; public GroupsControllerTests() { _ctx.GetEndpoint(IdentityEndpoints.ManageGroups).Returns(_endpoint); _endpoint.CreateProducer().Returns(_producer); _producer.Process(Arg.Do(e => _captured = e), Arg.Any()) .Returns(Task.CompletedTask); _sut = new GroupsController(); _sut.Context = _ctx; } [Fact] public async Task Get_NumericId() { await _sut.Get("5"); _captured!.In.Headers["operation"].Should().Be("read"); var body = _captured.In.Body as Dictionary; body!["groupId"].Should().Be(5L); } [Fact] public async Task Get_StringId() { await _sut.Get("admins"); _captured!.In.Headers["operation"].Should().Be("read"); var body = _captured.In.Body as Dictionary; body!["groupId"].Should().Be("admins"); } [Fact] public async Task Update_ForwardsIdAndBody() { var req = new UpdateGroupRequest { Name = "updated" }; await _sut.Update("42", req); _captured!.In.Headers["operation"].Should().Be("update"); var body = _captured.In.Body as Dictionary; body!["groupId"].Should().Be(42L); body["name"].Should().Be("updated"); } [Fact] public async Task Delete_NumericId() { await _sut.Delete("10"); _captured!.In.Headers["operation"].Should().Be("delete"); var body = _captured.In.Body as Dictionary; body!["groupId"].Should().Be(10L); } [Fact] public async Task AddMember_ForwardsGroupIdAndBody() { var req = new AddMemberRequest { UserId = 5L }; await _sut.AddMember("42", req); _captured!.In.Headers["operation"].Should().Be("add-member"); var body = _captured.In.Body as Dictionary; body!["groupId"].Should().Be(42L); body["userId"].Should().Be(5L); } [Fact] public async Task RemoveMember_ForwardsIds() { await _sut.RemoveMember("42", "5"); _captured!.In.Headers["operation"].Should().Be("remove-member"); var body = _captured.In.Body as Dictionary; body!["groupId"].Should().Be(42L); body["userId"].Should().Be(5L); } [Fact] public async Task CreateChild_ForwardsParentId() { var req = new CreateGroupRequest { Name = "ChildTeam", GroupType = "team" }; await _sut.CreateChild("42", req); _captured!.In.Headers["operation"].Should().Be("create-child"); var body = _captured.In.Body as Dictionary; body!["parentGroupId"].Should().Be(42L); body["name"].Should().Be("ChildTeam"); } [Fact] public async Task Move_ForwardsGroupId() { var req = new MoveGroupRequest { NewParentGroupId = 99L }; await _sut.Move("42", req); _captured!.In.Headers["operation"].Should().Be("move"); var body = _captured.In.Body as Dictionary; body!["groupId"].Should().Be(42L); body["newParentGroupId"].Should().Be(99L); } [Fact] public async Task Tree_ForwardsGroupId() { await _sut.Tree("42"); _captured!.In.Headers["operation"].Should().Be("tree"); var body = _captured.In.Body as Dictionary; body!["groupId"].Should().Be(42L); } [Fact] public async Task ListMembers_ForwardsGroupId() { await _sut.ListMembers("42"); _captured!.In.Headers["operation"].Should().Be("list-members"); var body = _captured.In.Body as Dictionary; body!["groupId"].Should().Be(42L); } [Fact] public async Task UserGroups_ForwardsUserId() { await _sut.UserGroups("5"); _captured!.In.Headers["operation"].Should().Be("user-groups"); var body = _captured.In.Body as Dictionary; body!["userId"].Should().Be(5L); } [Fact] public async Task IsMember_ForwardsIds() { await _sut.IsMember("42", "5"); _captured!.In.Headers["operation"].Should().Be("is-member"); var body = _captured.In.Body as Dictionary; body!["groupId"].Should().Be(42L); body["userId"].Should().Be(5L); } } Path: redb-identity/tests/redb.Identity.Tests/Http/Controllers/ScopesControllerTests.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/Http/Controllers/ScopesControllerTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Scopes; using redb.Identity.Contracts.Routes; using redb.Identity.Management.Controllers;using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Http.Controllers; public class ScopesControllerTests { private readonly IRouteContext _ctx = Substitute.For(); private readonly IEndpoint _endpoint = Substitute.For(); private readonly IProducer _producer = Substitute.For(); private readonly ScopesController _sut; private IExchange? _captured; public ScopesControllerTests() { _ctx.GetEndpoint(IdentityEndpoints.ManageScopes).Returns(_endpoint); _endpoint.CreateProducer().Returns(_producer); _producer.Process(Arg.Do(e => _captured = e), Arg.Any()) .Returns(Task.CompletedTask); _sut = new ScopesController(); _sut.Context = _ctx; } [Fact] public async Task Get_NumericId_ForwardsNumeric() { await _sut.Get("7"); _captured!.In.Headers["operation"].Should().Be("read"); var body = _captured.In.Body as Dictionary; body!["id"].Should().Be(7L); } [Fact] public async Task Get_StringId_ForwardsAsName() { await _sut.Get("openid"); _captured!.In.Headers["operation"].Should().Be("read"); var body = _captured.In.Body as Dictionary; body!["name"].Should().Be("openid"); } [Fact] public async Task Update_SetsIdOnRequest() { var req = new UpdateScopeRequest { DisplayName = "API Scope" }; await _sut.Update("scope-1", req); _captured!.In.Headers["operation"].Should().Be("update"); req.Id.Should().Be("scope-1"); _captured.In.Body.Should().BeSameAs(req); } [Fact] public async Task Delete_NumericId() { await _sut.Delete("15"); _captured!.In.Headers["operation"].Should().Be("delete"); var body = _captured.In.Body as Dictionary; body!["id"].Should().Be(15L); } [Fact] public async Task Delete_StringId_ForwardsAsName() { await _sut.Delete("profile"); _captured!.In.Headers["operation"].Should().Be("delete"); var body = _captured.In.Body as Dictionary; body!["name"].Should().Be("profile"); } } Path: redb-identity/tests/redb.Identity.Tests/Http/Controllers/SessionsControllerTests.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/Http/Controllers/SessionsControllerTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Identity.Contracts.Routes; using redb.Identity.Management.Controllers;using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Http.Controllers; public class SessionsControllerTests { private readonly IRouteContext _ctx = Substitute.For(); private readonly IEndpoint _endpoint = Substitute.For(); private readonly IProducer _producer = Substitute.For(); private readonly SessionsController _sut; private IExchange? _captured; public SessionsControllerTests() { _ctx.GetEndpoint(IdentityEndpoints.ManageSessions).Returns(_endpoint); _endpoint.CreateProducer().Returns(_producer); _producer.Process(Arg.Do(e => _captured = e), Arg.Any()) .Returns(Task.CompletedTask); _sut = new SessionsController(); _sut.Context = _ctx; } // ── List ── // // SessionsController.List dispatches on whether userId was supplied — // null/empty routes to the new "list-all" admin-wide browse, a // value routes to the targeted per-user "list". [Fact] public async Task List_NumericUserId_ForwardsAsLongAndPicksListOp() { await _sut.List(userId: "42"); _captured!.In.Headers["operation"].Should().Be("list"); var body = _captured.In.Body as Dictionary; body.Should().NotBeNull(); body!["userId"].Should().Be(42L); } [Fact] public async Task List_NonNumericUserId_DefaultsToZero() { await _sut.List(userId: "abc"); _captured!.In.Headers["operation"].Should().Be("list"); var body = _captured.In.Body as Dictionary; body!["userId"].Should().Be(0L); } [Fact] public async Task List_NoUserId_RoutesToListAllWithPagination() { await _sut.List(userId: null, offset: "50", count: "100"); _captured!.In.Headers["operation"].Should().Be("list-all"); var body = _captured.In.Body as Dictionary; body.Should().NotBeNull(); body!["offset"].Should().Be(50L); body!["count"].Should().Be(100L); } [Fact] public async Task List_NoUserId_DefaultsPagination() { await _sut.List(userId: null); _captured!.In.Headers["operation"].Should().Be("list-all"); var body = _captured.In.Body as Dictionary; body!["offset"].Should().Be(0L); body!["count"].Should().Be(25L); } // ── Revoke ── [Fact] public async Task Revoke_NumericId_ForwardsSessionId() { await _sut.Revoke("99"); _captured!.In.Headers["operation"].Should().Be("revoke"); var body = _captured.In.Body as Dictionary; body!["sessionId"].Should().Be(99L); } [Fact] public async Task Revoke_NonNumericId_DefaultsToZero() { await _sut.Revoke("not-a-number"); var body = _captured!.In.Body as Dictionary; body!["sessionId"].Should().Be(0L); } // ── RevokeAll ── [Fact] public async Task RevokeAll_NumericId_ForwardsUserId() { await _sut.RevokeAll("7"); _captured!.In.Headers["operation"].Should().Be("revoke-all"); var body = _captured.In.Body as Dictionary; body!["userId"].Should().Be(7L); } // ── Logout ── [Fact] public async Task Logout_NumericId_ForwardsUserId() { await _sut.Logout("100"); _captured!.In.Headers["operation"].Should().Be("logout"); var body = _captured.In.Body as Dictionary; body!["userId"].Should().Be(100L); } [Fact] public async Task Logout_NonNumericId_DefaultsToZero() { await _sut.Logout("xyz"); _captured!.In.Headers["operation"].Should().Be("logout"); var body = _captured.In.Body as Dictionary; body!["userId"].Should().Be(0L); } // ── Exchange pattern ── [Fact] public async Task Forward_SetsInOutPattern() { await _sut.List(userId: "1"); _captured!.Pattern.Should().Be(ExchangePattern.InOut); } } Path: redb-identity/tests/redb.Identity.Tests/Http/Controllers/TokensControllerTests.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/Http/Controllers/TokensControllerTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Identity.Contracts.Routes; using redb.Identity.Management.Controllers;using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Http.Controllers; public class TokensControllerTests { private readonly IRouteContext _ctx = Substitute.For(); private readonly IEndpoint _endpoint = Substitute.For(); private readonly IProducer _producer = Substitute.For(); private readonly TokensController _sut; private IExchange? _captured; public TokensControllerTests() { _ctx.GetEndpoint(IdentityEndpoints.ManageTokens).Returns(_endpoint); _endpoint.CreateProducer().Returns(_producer); _producer.Process(Arg.Do(e => _captured = e), Arg.Any()) .Returns(Task.CompletedTask); _sut = new TokensController(); _sut.Context = _ctx; } [Fact] public async Task List_WithGuidSubject() { var subject = Guid.NewGuid().ToString("D"); await _sut.List(subject: subject, offset: 0, count: 10); var body = _captured!.In.Body as Dictionary; body!["subject"].Should().Be(subject, "subject is now a per-user GUID — controller forwards the raw string"); } [Fact] public async Task List_WithStringSubject() { await _sut.List(subject: "admin"); var body = _captured!.In.Body as Dictionary; body!["subject"].Should().Be("admin"); } [Fact] public async Task Revoke_NumericId() { await _sut.Revoke("99"); _captured!.In.Headers["operation"].Should().Be("revoke"); var body = _captured.In.Body as Dictionary; body!["tokenId"].Should().Be(99L); } [Fact] public async Task Revoke_StringId() { await _sut.Revoke("abc-token"); _captured!.In.Headers["operation"].Should().Be("revoke"); var body = _captured.In.Body as Dictionary; body!["tokenId"].Should().Be("abc-token"); } [Fact] public async Task RevokeBySubject_ForwardsRequestDict() { var request = new Dictionary { ["subject"] = "user-123", ["type"] = "access_token" }; await _sut.RevokeBySubject(request); _captured!.In.Headers["operation"].Should().Be("revoke-by-user"); _captured.In.Body.Should().BeSameAs(request); } [Fact] public async Task Prune_ForwardsWithPruneOperation() { await _sut.Prune(); _captured!.In.Headers["operation"].Should().Be("prune"); } [Fact] public async Task Prune_SetsInOutPattern() { await _sut.Prune(); _captured!.Pattern.Should().Be(ExchangePattern.InOut); } } Path: redb-identity/tests/redb.Identity.Tests/Http/Controllers/UsersControllerTests.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/Http/Controllers/UsersControllerTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Users; using redb.Identity.Contracts.Routes; using redb.Identity.Management.Controllers;using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Http.Controllers; public class UsersControllerTests { private readonly IRouteContext _ctx = Substitute.For(); private readonly IEndpoint _endpoint = Substitute.For(); private readonly IProducer _producer = Substitute.For(); private readonly UsersController _sut; private IExchange? _captured; public UsersControllerTests() { _ctx.GetEndpoint(IdentityEndpoints.ManageUsers).Returns(_endpoint); _endpoint.CreateProducer().Returns(_producer); _producer.Process(Arg.Do(e => _captured = e), Arg.Any()) .Returns(Task.CompletedTask); _sut = new UsersController(); _sut.Context = _ctx; } [Fact] public async Task Get_NumericId() { await _sut.Get("100"); _captured!.In.Headers["operation"].Should().Be("read"); var body = _captured.In.Body as Dictionary; body!["id"].Should().Be(100L); } [Fact] public async Task Get_StringId_ForwardsAsLogin() { await _sut.Get("admin"); _captured!.In.Headers["operation"].Should().Be("read"); var body = _captured.In.Body as Dictionary; body!["login"].Should().Be("admin"); } [Fact] public async Task Update_SetsNumericId() { var req = new UpdateUserRequest { DisplayName = "John" }; await _sut.Update("55", req); _captured!.In.Headers["operation"].Should().Be("update"); req.Id.Should().Be(55L); _captured.In.Body.Should().BeSameAs(req); } [Fact] public async Task Update_NonNumericId_DoesNotSetId() { var req = new UpdateUserRequest { DisplayName = "John" }; await _sut.Update("admin", req); _captured!.In.Headers["operation"].Should().Be("update"); req.Id.Should().Be(0L); } [Fact] public async Task Delete_NumericId() { await _sut.Delete("10"); _captured!.In.Headers["operation"].Should().Be("delete"); var body = _captured.In.Body as Dictionary; body!["id"].Should().Be(10L); } [Fact] public async Task ChangePassword_SetsNumericId() { var req = new ChangePasswordRequest { OldPassword = "old", NewPassword = "new" }; await _sut.ChangePassword("77", req); _captured!.In.Headers["operation"].Should().Be("change-password"); req.Id.Should().Be(77L); } } Path: redb-identity/tests/redb.Identity.Tests/Http/CorsTests.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/Http/CorsTests.cs ---- using System.Net; using System.Net.Http.Headers; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http; /// /// G9 — CORS preflight behaviour of the discovery / JWKS endpoints. /// /// emits /// corsOrigins=* for /.well-known/* so every relying party (any SPA, /// any CLI) can fetch discovery and JWKS without being registered in advance. This /// matches RFC 8414 §3 and OIDC Core §10.1.1 (JWKS is public by design). /// /// /// The test asserts two things: /// /// An OPTIONS preflight with an arbitrary Origin succeeds and /// returns Access-Control-Allow-Origin: *; /// Token/userinfo endpoints (protected-ish) do NOT echo an arbitrary /// unregistered origin — the resolver composes the registered-client whitelist /// and AdditionalAllowedOrigins, and a stranger origin gets no ACAO header. /// /// Without these invariants an attacker could (a) tamper with discovery via a CORS /// reflection attack on a misconfigured browser, or (b) exfiltrate tokens from any /// origin via /connect/token XHR. /// /// [Collection("HttpIdentity")] public sealed class CorsTests { private readonly HttpIdentityFixture _fx; public CorsTests(HttpIdentityFixture fx) => _fx = fx; [Theory] [InlineData("/.well-known/openid-configuration")] [InlineData("/.well-known/oauth-authorization-server")] [InlineData("/.well-known/jwks")] public async Task Discovery_OptionsPreflight_AllowsAnyOrigin(string path) { using var req = new HttpRequestMessage(HttpMethod.Options, path); req.Headers.Add("Origin", "https://evil.example.com"); req.Headers.Add("Access-Control-Request-Method", "GET"); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().BeInRange(200, 299, "OPTIONS preflight on public discovery MUST succeed regardless of origin — " + "RFC 8414 §3 requires the metadata document be world-readable. Got {0} for {1}.", resp.StatusCode, path); var allow = resp.Headers.TryGetValues("Access-Control-Allow-Origin", out var v) ? string.Join(",", v) : null; allow.Should().Be("*", "public discovery endpoints emit corsOrigins=* (HttpFacadeRouteBuilder.PublicCorsParams). " + "Any relying party — SPAs, CLIs, new clients not yet registered — must be able to " + "read discovery and JWKS. Anything narrower breaks zero-config OIDC consumers."); } [Fact] public async Task TokenEndpoint_OptionsPreflightFromUnregisteredOrigin_DoesNotEchoOrigin() { // /connect/token uses ClientCorsParams which runs through the registered-client // resolver. A stranger origin that is NOT registered and NOT in // AdditionalAllowedOrigins must receive NO Access-Control-Allow-Origin header. // The preflight itself may return 200 / 204 (the middleware replies method-agnostic), // but the absence of ACAO means the browser blocks the actual CORS request. using var req = new HttpRequestMessage(HttpMethod.Options, "/connect/token"); req.Headers.Add("Origin", "https://evil.example.com"); req.Headers.Add("Access-Control-Request-Method", "POST"); var resp = await _fx.Http.SendAsync(req); var allow = resp.Headers.TryGetValues("Access-Control-Allow-Origin", out var v) ? string.Join(",", v) : null; allow.Should().NotBe("*", "/connect/token must NEVER echo '*' — it carries refresh-token credentials " + "and wildcards+credentials would allow cross-origin token theft."); if (!string.IsNullOrEmpty(allow)) { allow.Should().NotBe("https://evil.example.com", "an unregistered origin must not be echoed — otherwise any random site " + "could mount XHR token-endpoint attacks against authenticated browsers."); } } } Path: redb-identity/tests/redb.Identity.Tests/Http/E2E/ApiVersioningTests.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/Http/E2E/ApiVersioningTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http.E2E; /// /// Validates the URL-versioning contract of the HTTP facade: /// /// Custom management API lives under /api/v1/identity/. /// The pre-E3 path /api/identity/ is no longer routed (404). /// OIDC discovery + RFC 8414 server metadata are both exposed, /// unversioned, and return identical documents. /// SCIM 2.0 stays at /scim/v2/ (RFC 7644 §3.13) and is /// not also exposed under /api/v1/. /// /// [Collection("HttpIdentity")] public class ApiVersioningTests { private readonly HttpIdentityFixture _fixture; private readonly HttpClient _http; public ApiVersioningTests(HttpIdentityFixture fixture) { _fixture = fixture; _http = fixture.Http; } // ── Management API path ── [Fact] public async Task ManagementApi_Versioned_Path_Is_Routed() { var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fixture.ManagementToken); var resp = await _http.SendAsync(req); // The fixture provides a valid management token, so a properly routed + // authorized GET must succeed. Anything else (including 401) means the // route did not resolve as expected. resp.StatusCode.Should().Be(HttpStatusCode.OK, "/api/v1/identity/* must be served by the management facade with a valid bearer"); } [Fact] public async Task ManagementApi_Legacy_Unversioned_Path_Is_Not_Routed() { var req = new HttpRequestMessage(HttpMethod.Get, "/api/identity/applications"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fixture.ManagementToken); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.NotFound, "the pre-E3 /api/identity/* path is not retained"); } // ── OIDC + RFC 8414 discovery ── [Fact] public async Task Discovery_Oidc_Endpoint_Is_Reachable_Without_Version_Prefix() { var resp = await _http.GetAsync("/.well-known/openid-configuration"); resp.StatusCode.Should().Be(HttpStatusCode.OK, "OIDC Discovery 1.0 fixes this URL — never version it"); resp.Content.Headers.ContentType!.MediaType.Should().Be("application/json"); } [Fact] public async Task Discovery_Rfc8414_OAuthServer_Endpoint_Is_Reachable() { var resp = await _http.GetAsync("/.well-known/oauth-authorization-server"); resp.StatusCode.Should().Be(HttpStatusCode.OK, "RFC 8414 metadata must be served for non-OIDC OAuth 2.0 clients"); resp.Content.Headers.ContentType!.MediaType.Should().Be("application/json"); } [Fact] public async Task Discovery_Oidc_And_Rfc8414_Return_Equivalent_Issuer() { var oidc = await GetJson("/.well-known/openid-configuration"); var oauth = await GetJson("/.well-known/oauth-authorization-server"); oidc.TryGetProperty("issuer", out var oidcIssuer).Should().BeTrue(); oauth.TryGetProperty("issuer", out var oauthIssuer).Should().BeTrue( "RFC 8414 §2: 'issuer' is REQUIRED"); oauthIssuer.GetString().Should().Be(oidcIssuer.GetString(), "both metadata documents describe the same authorization server"); } // ── SCIM stays SCIM ── // // The positive case ("/scim/v2/* is reachable") is exercised across many // tests in tests/Scim/, against ProductionHttpFixture which actually // enables the SCIM facade. Here we only assert the negative: SCIM must // NOT also be mounted under /api/v1/: RFC 7644 fixes its own path. [Fact] public async Task Scim_Endpoint_Is_Not_Also_Mounted_Under_V1_Prefix() { var resp = await _http.GetAsync("/api/v1/scim/v2/ServiceProviderConfig"); resp.StatusCode.Should().Be(HttpStatusCode.NotFound, "the original E3 draft mentioned /api/v1/scim/* — we do not ship that, " + "SCIM lives only at the RFC-defined /scim/v2/* path"); } // ── Helpers ── private async Task GetJson(string url) { var resp = await _http.GetAsync(url); resp.StatusCode.Should().Be(HttpStatusCode.OK); var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/Http/E2E/AuthorizationCodeFlowTests.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/Http/E2E/AuthorizationCodeFlowTests.cs ---- using System.Net; using System.Security.Cryptography; using System.Text; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http.E2E; /// /// E2E test: Authorization Code + PKCE flow over real HTTP. /// Tests the multi-step exchange: /connect/authorize → login stub → token exchange. /// [Collection("HttpIdentity")] public class AuthorizationCodeFlowTests { private readonly HttpIdentityFixture _fixture; public AuthorizationCodeFlowTests(HttpIdentityFixture fixture) { _fixture = fixture; } [Fact] public async Task AuthorizeEndpoint_Get_ReturnsLoginStubOrRedirect() { var codeVerifier = GenerateCodeVerifier(); var codeChallenge = GenerateCodeChallenge(codeVerifier); var url = "/connect/authorize" + "?response_type=code" + "&client_id=pkce-test-client" + "&redirect_uri=http://localhost/callback" + $"&code_challenge={codeChallenge}" + "&code_challenge_method=S256" + "&scope=openid"; var response = await _fixture.Http.GetAsync(url); // Degraded mode with login stub enabled: expect 200 (HTML login form), 302 (redirect), // 400 (bad request), or 500 (degraded mode can't authenticate without a session provider) response.StatusCode.Should().BeOneOf( HttpStatusCode.OK, HttpStatusCode.Redirect, HttpStatusCode.BadRequest, HttpStatusCode.InternalServerError); var body = await response.Content.ReadAsStringAsync(); body.Should().NotBeNullOrEmpty("endpoint should always return a body"); if (response.StatusCode == HttpStatusCode.OK) { // Should be login stub HTML or JSON — not empty (body.Contains("html", StringComparison.OrdinalIgnoreCase) || body.TrimStart().StartsWith("{")).Should().BeTrue( "200 body should be HTML or JSON, got: " + body[..Math.Min(200, body.Length)]); } if (response.StatusCode == HttpStatusCode.Redirect) { response.Headers.Location.Should().NotBeNull("302 must have Location header"); } if (response.StatusCode == HttpStatusCode.InternalServerError) { // Degraded mode error — verify it's a structured response, not a raw exception var isJson = body.TrimStart().StartsWith("{"); var isHtml = body.TrimStart().StartsWith("<"); (isJson || isHtml).Should().BeTrue( "500 should be a structured error response, not a raw stack trace"); } } [Fact] public async Task AuthorizeEndpoint_Post_SendsFormData() { var codeVerifier = GenerateCodeVerifier(); var codeChallenge = GenerateCodeChallenge(codeVerifier); var content = new FormUrlEncodedContent(new Dictionary { ["response_type"] = "code", ["client_id"] = "pkce-post-client", ["redirect_uri"] = "http://localhost/callback", ["code_challenge"] = codeChallenge, ["code_challenge_method"] = "S256", ["scope"] = "openid" }); var response = await _fixture.Http.PostAsync("/connect/authorize", content); // POST without session cookie: expect 302 redirect to login, // 400 (bad request), or 500 (degraded mode) response.StatusCode.Should().BeOneOf( HttpStatusCode.OK, HttpStatusCode.Redirect, HttpStatusCode.BadRequest, HttpStatusCode.Forbidden, HttpStatusCode.InternalServerError); if (response.StatusCode == HttpStatusCode.Redirect) { response.Headers.Location.Should().NotBeNull("redirect must include Location"); } if (response.StatusCode == HttpStatusCode.InternalServerError) { var body = await response.Content.ReadAsStringAsync(); body.Should().NotBeNullOrEmpty("500 should have a response body"); } } private static string GenerateCodeVerifier() { var bytes = new byte[32]; RandomNumberGenerator.Fill(bytes); return Convert.ToBase64String(bytes) .TrimEnd('=') .Replace('+', '-') .Replace('/', '_'); } private static string GenerateCodeChallenge(string codeVerifier) { var hash = SHA256.HashData(Encoding.ASCII.GetBytes(codeVerifier)); return Convert.ToBase64String(hash) .TrimEnd('=') .Replace('+', '-') .Replace('/', '_'); } } Path: redb-identity/tests/redb.Identity.Tests/Http/E2E/ClientCredentialsFlowTests.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/Http/E2E/ClientCredentialsFlowTests.cs ---- using System.Net; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http.E2E; /// /// E2E test: OAuth 2.0 Client Credentials flow over real HTTP. /// Uses with real PostgreSQL + Kestrel. /// [Collection("HttpIdentity")] public class ClientCredentialsFlowTests { private readonly HttpIdentityFixture _fixture; public ClientCredentialsFlowTests(HttpIdentityFixture fixture) { _fixture = fixture; } [Fact] public async Task TokenEndpoint_ClientCredentials_ReturnsAccessToken() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "e2e-test-client", ["client_secret"] = "e2e-test-secret" }); var response = await _fixture.Http.PostAsync("/connect/token", content); response.StatusCode.Should().Be(HttpStatusCode.OK); var body = await response.Content.ReadAsStringAsync(); var json = JsonDocument.Parse(body).RootElement; // Verify we got a token response (access_token) or an error response if (json.TryGetProperty("access_token", out var token)) { token.GetString().Should().NotBeNullOrEmpty(); json.GetProperty("token_type").GetString().Should().Be("Bearer"); } else { // If error, surface it for diagnostics json.TryGetProperty("error", out var error).Should().BeTrue( $"expected either access_token or error in response: {body}"); Assert.Fail($"Token endpoint returned error: {error}, body: {body}"); } } [Fact] public async Task TokenEndpoint_ClientCredentials_WithScopes_ReturnsToken() { // In degraded mode, scopes are not validated by the store, // so any scope string is accepted by the ClaimsPrincipal handler var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "scoped-client", ["client_secret"] = "scoped-secret", ["scope"] = "api profile" }); var response = await _fixture.Http.PostAsync("/connect/token", content); // Degraded mode may return 200+token or 400+error response.StatusCode.Should().BeOneOf(HttpStatusCode.OK, HttpStatusCode.BadRequest); var body = await response.Content.ReadAsStringAsync(); body.Should().NotBeNullOrEmpty("token endpoint should return a JSON response"); var json = JsonDocument.Parse(body).RootElement; // Degraded mode may or may not issue scoped tokens; verify we got a valid JSON response var hasToken = json.TryGetProperty("access_token", out _); var hasError = json.TryGetProperty("error", out _); (hasToken || hasError).Should().BeTrue( $"expected either access_token or error in response: {body}"); } [Fact] public async Task TokenEndpoint_BasicAuth_ClientCredentials() { var credentials = Convert.ToBase64String("basic-client:basic-secret"u8); var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials" }); var request = new HttpRequestMessage(HttpMethod.Post, "/connect/token") { Content = content }; request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials); var response = await _fixture.Http.SendAsync(request); response.StatusCode.Should().Be(HttpStatusCode.OK); var json = await response.Content.ReadFromJsonAsync(); json.GetProperty("access_token").GetString().Should().NotBeNullOrEmpty(); } [Fact] public async Task TokenEndpoint_MissingGrantType_ReturnsErrorResponse() { var content = new FormUrlEncodedContent(new Dictionary { ["client_id"] = "bad-client" }); var response = await _fixture.Http.PostAsync("/connect/token", content); // In degraded mode, OpenIddict may still process the request; // verify we get a parseable response (error or success) var body = await response.Content.ReadAsStringAsync(); body.Should().NotBeNullOrEmpty(); } [Fact] public async Task TokenEndpoint_ResponseContainsRequiredFields() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "fields-test-client", ["client_secret"] = "fields-test-secret" }); var response = await _fixture.Http.PostAsync("/connect/token", content); response.StatusCode.Should().Be(HttpStatusCode.OK); var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement; json.GetProperty("access_token").GetString().Should().NotBeNullOrEmpty(); json.GetProperty("token_type").GetString().Should().Be("Bearer"); json.TryGetProperty("expires_in", out var expiresIn).Should().BeTrue(); expiresIn.GetInt32().Should().BeGreaterThan(0); } [Fact] public async Task UserinfoEndpoint_WithAccessToken_ReturnsSubject() { // First, get an access token var tokenContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "userinfo-client", ["client_secret"] = "userinfo-secret" }); var tokenResp = await _fixture.Http.PostAsync("/connect/token", tokenContent); tokenResp.StatusCode.Should().Be(HttpStatusCode.OK); var tokenJson = JsonDocument.Parse(await tokenResp.Content.ReadAsStringAsync()).RootElement; var accessToken = tokenJson.GetProperty("access_token").GetString()!; // Call userinfo with the Bearer token var request = new HttpRequestMessage(HttpMethod.Get, "/connect/userinfo"); request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); var response = await _fixture.Http.SendAsync(request); // Degraded mode may return 200 with claims or 401/400 response.StatusCode.Should().BeOneOf(HttpStatusCode.OK, HttpStatusCode.Unauthorized, HttpStatusCode.BadRequest); if (response.StatusCode == HttpStatusCode.OK) { var body = await response.Content.ReadAsStringAsync(); body.Should().NotBeNullOrEmpty("userinfo should return claims data"); } } [Fact] public async Task RevocationEndpoint_AcceptsToken() { // Get a token to revoke var tokenContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "revoke-client", ["client_secret"] = "revoke-secret" }); var tokenResp = await _fixture.Http.PostAsync("/connect/token", tokenContent); tokenResp.StatusCode.Should().Be(HttpStatusCode.OK); var tokenJson = JsonDocument.Parse(await tokenResp.Content.ReadAsStringAsync()).RootElement; var accessToken = tokenJson.GetProperty("access_token").GetString()!; // Revoke the token var revokeContent = new FormUrlEncodedContent(new Dictionary { ["token"] = accessToken, ["client_id"] = "revoke-client", ["client_secret"] = "revoke-secret" }); var response = await _fixture.Http.PostAsync("/connect/revocation", revokeContent); // RFC 7009: revocation always returns 200 OK (even for invalid tokens) response.StatusCode.Should().Be(HttpStatusCode.OK, "revocation response: {0}", await response.Content.ReadAsStringAsync()); } [Fact] public async Task IntrospectionEndpoint_ReturnsActiveFlag() { // Get a token to introspect var tokenContent = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "introspect-client", ["client_secret"] = "introspect-secret" }); var tokenResp = await _fixture.Http.PostAsync("/connect/token", tokenContent); tokenResp.StatusCode.Should().Be(HttpStatusCode.OK); var tokenJson = JsonDocument.Parse(await tokenResp.Content.ReadAsStringAsync()).RootElement; var accessToken = tokenJson.GetProperty("access_token").GetString()!; // Introspect the token var introspectContent = new FormUrlEncodedContent(new Dictionary { ["token"] = accessToken, ["client_id"] = "introspect-client", ["client_secret"] = "introspect-secret" }); var response = await _fixture.Http.PostAsync("/connect/introspect", introspectContent); response.StatusCode.Should().Be(HttpStatusCode.OK, "introspection response: {0}", await response.Content.ReadAsStringAsync()); var body = await response.Content.ReadAsStringAsync(); body.Should().NotBeNullOrEmpty(); var json = JsonDocument.Parse(body).RootElement; json.TryGetProperty("active", out var active).Should().BeTrue( "RFC 7662: introspection must return 'active' field; got: {0}", body); active.GetBoolean().Should().BeTrue("freshly issued token should be active"); } } Path: redb-identity/tests/redb.Identity.Tests/Http/E2E/CorsE2ETests.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/Http/E2E/CorsE2ETests.cs ---- using System.Net; using System.Net.Http.Headers; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http.E2E; /// /// E2E tests verifying the per-route CORS policy applied by HttpFacadeRouteBuilder. /// /// Three policy classes are exercised: /// /// /// Public (/.well-known/*): wildcard origin, no credentials. /// Client (/connect/token, /connect/userinfo, /// /connect/introspect, ...): origin must match either a registered application's /// redirect URI or HttpTransportOptions.Http.AdditionalAllowedOrigins. /// None (/api/v1/identity/*, /connect/authorize): no CORS headers /// ever \u2014 these endpoints are not reachable from cross-origin browser fetch. /// /// The fixture configures AdditionalAllowedOrigins = "http://localhost:3000, http://localhost:5173". /// [Collection("HttpIdentity")] public class CorsE2ETests { private const string AllowedOrigin1 = "http://localhost:3000"; private const string AllowedOrigin2 = "http://localhost:5173"; private const string DisallowedOrigin = "https://evil.example.com"; private readonly HttpIdentityFixture _fixture; private readonly HttpClient _http; public CorsE2ETests(HttpIdentityFixture fixture) { _fixture = fixture; _http = fixture.Http; } // ── Public policy (/.well-known/*): wildcard, no Origin needed ── [Fact] public async Task Discovery_Get_ReturnsWildcardCorsHeader() { var response = await _http.GetAsync("/.well-known/openid-configuration"); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Headers.GetValues("Access-Control-Allow-Origin").Single() .Should().Be("*", "well-known endpoints are public per RFC 8414"); response.Headers.Should().Contain(h => h.Key == "Vary", "Vary: Origin must be emitted whenever CORS dispatch runs"); } [Fact] public async Task Discovery_Preflight_AnyOrigin_Returns204WithWildcard() { var request = new HttpRequestMessage(HttpMethod.Options, "/.well-known/openid-configuration"); request.Headers.Add("Origin", DisallowedOrigin); request.Headers.Add("Access-Control-Request-Method", "GET"); var response = await _http.SendAsync(request); response.StatusCode.Should().Be(HttpStatusCode.NoContent); response.Headers.GetValues("Access-Control-Allow-Origin").Single().Should().Be("*"); } [Fact] public async Task Jwks_Get_ReturnsWildcardCorsHeader() { var response = await _http.GetAsync("/.well-known/jwks"); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Headers.GetValues("Access-Control-Allow-Origin").Single().Should().Be("*"); } // ── Client policy (token / userinfo / introspect): per-request resolver ── [Fact] public async Task Token_Post_AllowedOrigin_EchoesSingleOrigin() { var request = new HttpRequestMessage(HttpMethod.Post, "/connect/token") { Content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "test-client" }) }; request.Headers.Add("Origin", AllowedOrigin1); var response = await _http.SendAsync(request); response.Headers.GetValues("Access-Control-Allow-Origin").Single() .Should().Be(AllowedOrigin1, "the resolver must echo a single matching origin"); } [Fact] public async Task Token_Post_DisallowedOrigin_OmitsCorsHeader() { var request = new HttpRequestMessage(HttpMethod.Post, "/connect/token") { Content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "test-client" }) }; request.Headers.Add("Origin", DisallowedOrigin); var response = await _http.SendAsync(request); response.Headers.Contains("Access-Control-Allow-Origin").Should().BeFalse( "an unregistered/un-listed origin must NOT receive CORS headers"); } [Fact] public async Task Token_Preflight_AllowedOrigin_Returns204WithEcho() { var request = new HttpRequestMessage(HttpMethod.Options, "/connect/token"); request.Headers.Add("Origin", AllowedOrigin1); request.Headers.Add("Access-Control-Request-Method", "POST"); request.Headers.Add("Access-Control-Request-Headers", "content-type"); var response = await _http.SendAsync(request); response.StatusCode.Should().Be(HttpStatusCode.NoContent); response.Headers.GetValues("Access-Control-Allow-Origin").Single().Should().Be(AllowedOrigin1); response.Headers.GetValues("Access-Control-Allow-Methods").Single() .Should().Contain("POST"); response.Headers.GetValues("Access-Control-Allow-Headers").Single() .Should().Contain("content-type"); } [Fact] public async Task Userinfo_Preflight_AllowedOrigin_Returns204WithEcho() { var request = new HttpRequestMessage(HttpMethod.Options, "/connect/userinfo"); request.Headers.Add("Origin", AllowedOrigin2); request.Headers.Add("Access-Control-Request-Method", "GET"); var response = await _http.SendAsync(request); response.StatusCode.Should().Be(HttpStatusCode.NoContent); response.Headers.GetValues("Access-Control-Allow-Origin").Single().Should().Be(AllowedOrigin2); } [Fact] public async Task Introspect_Post_AllowedOrigin_EchoesOrigin() { var request = new HttpRequestMessage(HttpMethod.Post, "/connect/introspect") { Content = new FormUrlEncodedContent(new Dictionary { ["token"] = "some-token", ["client_id"] = "test-client", ["client_secret"] = "secret" }) }; request.Headers.Add("Origin", AllowedOrigin1); var response = await _http.SendAsync(request); response.Headers.GetValues("Access-Control-Allow-Origin").Single().Should().Be(AllowedOrigin1); } // ── No-CORS policy: management API and authorize endpoint ── [Fact] public async Task ManagementApi_NeverEmitsCorsHeaders() { // The management API and SCIM are admin-only: no browser-side access path exists, // so even when CORS is globally enabled they remain transparent. var request = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fixture.ManagementToken); request.Headers.Add("Origin", AllowedOrigin1); var response = await _http.SendAsync(request); response.Headers.Contains("Access-Control-Allow-Origin").Should().BeFalse( "management API must never expose CORS \u2014 it is not browser-callable"); } [Fact] public async Task Authorize_NeverEmitsCorsHeaders() { // /connect/authorize is a redirect endpoint (full-page navigation) \u2014 browsers // never issue cross-origin fetch against it, so emitting CORS headers would be // misleading. var request = new HttpRequestMessage( HttpMethod.Get, "/connect/authorize?response_type=code&client_id=x&redirect_uri=http://localhost/cb"); request.Headers.Add("Origin", AllowedOrigin1); var response = await _http.SendAsync(request); response.Headers.Contains("Access-Control-Allow-Origin").Should().BeFalse( "authorize endpoint is browser-redirect-only"); } } Path: redb-identity/tests/redb.Identity.Tests/Http/E2E/DiscoveryJwksE2ETests.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/Http/E2E/DiscoveryJwksE2ETests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http.E2E; /// /// E2E tests for Discovery and JWKS endpoints over real HTTP. /// Validates OpenID Connect Discovery 1.0 and RFC 7517 (JWK Set) compliance. /// [Collection("HttpIdentity")] public class DiscoveryJwksE2ETests { private readonly HttpClient _http; public DiscoveryJwksE2ETests(HttpIdentityFixture fixture) => _http = fixture.Http; // ── Discovery ── [Fact] public async Task Discovery_ReturnsJson_WithCorrectContentType() { var response = await _http.GetAsync("/.well-known/openid-configuration"); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Content.Headers.ContentType!.MediaType.Should().Be("application/json"); } [Fact] public async Task Discovery_ContainsIssuer() { var json = await GetDiscovery(); json.TryGetProperty("issuer", out var issuer).Should().BeTrue( "discovery must contain 'issuer'"); issuer.GetString().Should().Contain("localhost", "issuer should match the configured base URL"); } [Fact] public async Task Discovery_ContainsTokenEndpoint() { var json = await GetDiscovery(); json.TryGetProperty("token_endpoint", out var ep).Should().BeTrue(); ep.GetString().Should().Contain("/connect/token"); } [Fact] public async Task Discovery_ContainsIntrospectionEndpoint() { var json = await GetDiscovery(); json.TryGetProperty("introspection_endpoint", out var ep).Should().BeTrue( "discovery must advertise introspection endpoint for resource servers"); ep.GetString().Should().Contain("/connect/introspect"); } [Fact] public async Task Discovery_ContainsRevocationEndpoint() { var json = await GetDiscovery(); json.TryGetProperty("revocation_endpoint", out var ep).Should().BeTrue( "discovery must advertise revocation endpoint"); ep.GetString().Should().Contain("/connect/revok"); } [Fact] public async Task Discovery_ContainsJwksUri() { var json = await GetDiscovery(); json.TryGetProperty("jwks_uri", out var uri).Should().BeTrue(); uri.GetString().Should().Contain("/.well-known/jwks"); } [Fact] public async Task Discovery_ContainsGrantTypesSupported() { var json = await GetDiscovery(); json.TryGetProperty("grant_types_supported", out var grants).Should().BeTrue(); var grantList = grants.EnumerateArray().Select(g => g.GetString()).ToList(); grantList.Should().Contain("client_credentials"); } [Fact] public async Task Discovery_ContainsResponseTypesSupported() { var json = await GetDiscovery(); json.TryGetProperty("response_types_supported", out var types).Should().BeTrue( "OpenID Connect Discovery 1.0 §3: response_types_supported is REQUIRED"); var typeList = types.EnumerateArray().Select(t => t.GetString()).ToList(); typeList.Should().Contain("code", "authorization_code flow is enabled — 'code' must be advertised"); } // ── Discovery: conditional feature endpoints ── [Fact] public async Task Discovery_DoesNotContainRegistrationEndpoint_WhenDisabled() { var json = await GetDiscovery(); json.TryGetProperty("registration_endpoint", out _).Should().BeFalse( "registration_endpoint must NOT appear when EnableDynamicRegistration=false"); } [Fact] public async Task Discovery_DoesNotContainDeviceAuthorizationEndpoint_WhenDisabled() { var json = await GetDiscovery(); json.TryGetProperty("device_authorization_endpoint", out _).Should().BeFalse( "device_authorization_endpoint must NOT appear when EnableDeviceCodeFlow=false"); } [Fact] public async Task Discovery_GrantTypes_DoNotContainDeviceCode_WhenDisabled() { var json = await GetDiscovery(); json.TryGetProperty("grant_types_supported", out var grants).Should().BeTrue(); var grantList = grants.EnumerateArray().Select(g => g.GetString()).ToList(); grantList.Should().NotContain("urn:ietf:params:oauth:grant-type:device_code", "device_code grant type must NOT be advertised when EnableDeviceCodeFlow=false"); } // ── JWKS ── [Fact] public async Task Jwks_ReturnsJson_WithCorrectContentType() { var response = await _http.GetAsync("/.well-known/jwks"); response.StatusCode.Should().Be(HttpStatusCode.OK); response.Content.Headers.ContentType!.MediaType.Should().Be("application/json"); } [Fact] public async Task Jwks_ContainsAtLeastOneKey() { var json = await GetJsonElement("/.well-known/jwks"); json.TryGetProperty("keys", out var keys).Should().BeTrue( "JWKS must contain 'keys' array"); keys.ValueKind.Should().Be(JsonValueKind.Array, "'keys' must be a JSON array, not a serialized string"); keys.GetArrayLength().Should().BeGreaterThan(0, "server must expose at least one signing key"); } [Fact] public async Task Jwks_KeysContainRequiredJwkFields() { var json = await GetJsonElement("/.well-known/jwks"); var keys = json.GetProperty("keys"); keys.ValueKind.Should().Be(JsonValueKind.Array); foreach (var key in keys.EnumerateArray()) { // RFC 7517 §4: 'kty' is required key.TryGetProperty("kty", out _).Should().BeTrue( "each JWK must have 'kty' (key type)"); } } // ── Helpers ── private async Task GetDiscovery() => await GetJsonElement("/.well-known/openid-configuration"); private async Task GetJsonElement(string url) { var response = await _http.GetAsync(url); response.StatusCode.Should().Be(HttpStatusCode.OK); var body = await response.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/Http/E2E/IntrospectionRevocationE2ETests.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/Http/E2E/IntrospectionRevocationE2ETests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http.E2E; /// /// E2E tests for RFC 7662 (Token Introspection) and RFC 7009 (Token Revocation) /// over real HTTP. Validates the full pipeline: /// HttpClient → Kestrel → HTTP facade → direct-vm:// → OpenIddict → response. /// [Collection("HttpIdentity")] public class IntrospectionRevocationE2ETests { private readonly HttpClient _http; public IntrospectionRevocationE2ETests(HttpIdentityFixture fixture) => _http = fixture.Http; // ── Token helper ── private async Task ObtainAccessToken(string clientId = "e2e-intr-client") { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = clientId, ["client_secret"] = "e2e-secret" }); var resp = await _http.PostAsync("/connect/token", content); resp.StatusCode.Should().Be(HttpStatusCode.OK, "token endpoint failed: {0}", await resp.Content.ReadAsStringAsync()); var json = JsonDocument.Parse(await resp.Content.ReadAsStringAsync()).RootElement; return json.GetProperty("access_token").GetString()!; } private FormUrlEncodedContent IntrospectBody(string token, string clientId = "e2e-intr-client") => new(new Dictionary { ["token"] = token, ["client_id"] = clientId, ["client_secret"] = "e2e-secret" }); private FormUrlEncodedContent RevokeBody(string token, string clientId = "e2e-intr-client") => new(new Dictionary { ["token"] = token, ["client_id"] = clientId, ["client_secret"] = "e2e-secret" }); // ══════════════════════════════════════════════ // RFC 7662 — Token Introspection // ══════════════════════════════════════════════ [Fact] public async Task Introspect_ValidToken_ReturnsActiveTrue() { var token = await ObtainAccessToken(); var resp = await _http.PostAsync("/connect/introspect", IntrospectBody(token)); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.GetProperty("active").GetBoolean().Should().BeTrue( "freshly issued token must be active"); } [Fact] public async Task Introspect_ValidToken_ContainsSubjectClaim() { var token = await ObtainAccessToken("sub-test-client"); var resp = await _http.PostAsync("/connect/introspect", IntrospectBody(token, "sub-test-client")); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.GetProperty("active").GetBoolean().Should().BeTrue(); json.TryGetProperty("sub", out var sub).Should().BeTrue( "introspection of active token must include 'sub' claim"); sub.GetString().Should().Be("sub-test-client"); } [Fact] public async Task Introspect_ValidToken_ContainsIssuer() { var token = await ObtainAccessToken(); var resp = await _http.PostAsync("/connect/introspect", IntrospectBody(token)); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.TryGetProperty("iss", out var iss).Should().BeTrue( "introspection should include issuer"); iss.GetString().Should().Contain("localhost"); } [Fact] public async Task Introspect_ValidToken_ReturnsJsonContentType() { var token = await ObtainAccessToken(); var resp = await _http.PostAsync("/connect/introspect", IntrospectBody(token)); resp.StatusCode.Should().Be(HttpStatusCode.OK); resp.Content.Headers.ContentType!.MediaType.Should().Be("application/json"); } [Fact] public async Task Introspect_InvalidToken_ReturnsError() { var resp = await _http.PostAsync("/connect/introspect", IntrospectBody("this-is-not-a-valid-jwt")); // RFC 7662: invalid token → 200 with {active:false}, or OAuth error with proper status resp.StatusCode.Should().BeOneOf( HttpStatusCode.OK, HttpStatusCode.BadRequest, HttpStatusCode.Unauthorized); var json = await ParseJson(resp); var hasError = json.TryGetProperty("error", out _); var hasActive = json.TryGetProperty("active", out _); (hasError || hasActive).Should().BeTrue( "invalid token should produce an error or inactive response"); } [Fact] public async Task Introspect_MissingTokenParam_ReturnsBadRequest() { var content = new FormUrlEncodedContent(new Dictionary { // no "token" field ["client_id"] = "e2e-intr-client", ["client_secret"] = "e2e-secret" }); var resp = await _http.PostAsync("/connect/introspect", content); // RFC 6749 §5.2: invalid_request → 400 Bad Request resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_request"); } [Fact] public async Task Introspect_WithBasicAuth_ReturnsActiveTrue() { var token = await ObtainAccessToken("basic-intr-client"); var credentials = Convert.ToBase64String("basic-intr-client:e2e-secret"u8); var request = new HttpRequestMessage(HttpMethod.Post, "/connect/introspect") { Content = new FormUrlEncodedContent(new Dictionary { ["token"] = token }) }; request.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials); var resp = await _http.SendAsync(request); resp.StatusCode.Should().Be(HttpStatusCode.OK); var json = await ParseJson(resp); json.GetProperty("active").GetBoolean().Should().BeTrue(); } // ══════════════════════════════════════════════ // RFC 7009 — Token Revocation // ══════════════════════════════════════════════ [Fact] public async Task Revoke_ValidToken_Returns200() { var token = await ObtainAccessToken(); var resp = await _http.PostAsync("/connect/revocation", RevokeBody(token)); // RFC 7009 §2.1: always returns 200 OK — even if token was already revoked resp.StatusCode.Should().Be(HttpStatusCode.OK); } [Fact] public async Task Revoke_InvalidToken_Returns200() { // RFC 7009 §2.1: "The authorization server responds with HTTP status code 200 // for both valid and invalid tokens." var resp = await _http.PostAsync("/connect/revocation", RevokeBody("garbage-token-value")); resp.StatusCode.Should().Be(HttpStatusCode.OK, "RFC 7009: revocation must return 200 even for invalid tokens; got: {0}", await resp.Content.ReadAsStringAsync()); } [Fact] public async Task Revoke_MissingTokenParam_Answers400_BecauseRevocationErrorsFollowRfc6749() { var content = new FormUrlEncodedContent(new Dictionary { ["client_id"] = "e2e-intr-client", ["client_secret"] = "e2e-secret" // no "token" field }); var resp = await _http.PostAsync("/connect/revocation", content); // RFC 7009 2.2.1: an error answers as RFC 6749 5.2 says; 200 is only for the token itself, valid or not. resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("invalid_request"); } [Fact] public async Task Revoke_WithTokenTypeHint_Returns200() { var token = await ObtainAccessToken(); var content = new FormUrlEncodedContent(new Dictionary { ["token"] = token, ["token_type_hint"] = "access_token", ["client_id"] = "e2e-intr-client", ["client_secret"] = "e2e-secret" }); var resp = await _http.PostAsync("/connect/revocation", content); resp.StatusCode.Should().Be(HttpStatusCode.OK); } // ══════════════════════════════════════════════ // Revoke → Introspect flow (the real integration test) // ══════════════════════════════════════════════ [Fact] public async Task RevokeAndIntrospect_RevokedToken_BecomesInactive() { // 1. Obtain token var token = await ObtainAccessToken("flow-client"); // 2. Verify it's active var introspect1 = await _http.PostAsync("/connect/introspect", IntrospectBody(token, "flow-client")); introspect1.StatusCode.Should().Be(HttpStatusCode.OK); var json1 = await ParseJson(introspect1); json1.GetProperty("active").GetBoolean().Should().BeTrue( "token should be active before revocation"); // 3. Revoke it var revokeResp = await _http.PostAsync("/connect/revocation", RevokeBody(token, "flow-client")); revokeResp.StatusCode.Should().Be(HttpStatusCode.OK); // 4. Introspect again — should be inactive now // Note: In degraded mode (no token store), the self-contained JWT may still // validate since there's no revocation list. We verify the pipeline completes // without error. With a real store, this would return active=false. var introspect2 = await _http.PostAsync("/connect/introspect", IntrospectBody(token, "flow-client")); introspect2.StatusCode.Should().Be(HttpStatusCode.OK, "introspection after revocation must not fail"); } [Fact] public async Task Revoke_ThenRevoke_IsIdempotent() { var token = await ObtainAccessToken("idempotent-client"); // First revocation var resp1 = await _http.PostAsync("/connect/revocation", RevokeBody(token, "idempotent-client")); resp1.StatusCode.Should().Be(HttpStatusCode.OK); // Second revocation — must also succeed (RFC 7009 idempotency) var resp2 = await _http.PostAsync("/connect/revocation", RevokeBody(token, "idempotent-client")); resp2.StatusCode.Should().Be(HttpStatusCode.OK); } // ══════════════════════════════════════════════ // HTTP status code precision tests // ══════════════════════════════════════════════ [Fact] public async Task Token_UnsupportedGrant_Returns400() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "password", ["client_id"] = "e2e-intr-client", ["client_secret"] = "e2e-secret", ["username"] = "test", ["password"] = "test" }); var resp = await _http.PostAsync("/connect/token", content); // RFC 6749 §5.2: unsupported_grant_type → 400 Bad Request resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.GetProperty("error").GetString().Should().Be("unsupported_grant_type"); } [Fact] public async Task Token_MissingClientId_ReturnsError() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials" // no client_id or Authorization header }); var resp = await _http.PostAsync("/connect/token", content); // RFC 6749 §5.2: invalid_request → 400 Bad Request resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); var json = await ParseJson(resp); json.TryGetProperty("error", out var error).Should().BeTrue(); error.GetString().Should().Be("invalid_request"); } // ── Helpers ── private static async Task ParseJson(HttpResponseMessage resp) { var body = await resp.Content.ReadAsStringAsync(); return JsonDocument.Parse(body).RootElement; } } Path: redb-identity/tests/redb.Identity.Tests/Http/E2E/ManagementApiCrudTests.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/Http/E2E/ManagementApiCrudTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using OpenIddict.Abstractions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http.E2E; /// /// E2E test: Management REST API (CRUD) over real HTTP. /// Uses with real PostgreSQL + Kestrel. /// Exercises the full pipeline: HTTP → StripPrefix → Controller → direct-vm:// → processor → PostgreSQL. /// [Collection("HttpIdentity")] public class ManagementApiCrudTests { private readonly HttpIdentityFixture _fixture; private readonly HttpClient _http; public ManagementApiCrudTests(HttpIdentityFixture fixture) { _fixture = fixture; _http = fixture.Http; } private HttpRequestMessage WithAuth(HttpRequestMessage request) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fixture.ManagementToken); return request; } // ── Applications ── [Fact] public async Task Applications_CrudLifecycle() { // Create var createReq = WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/applications") { Content = JsonContent.Create(new { clientId = $"crud-test-{Guid.NewGuid():N}", clientSecret = "test-secret", displayName = "CRUD Test App" }) }); var createResp = await _http.SendAsync(createReq); createResp.StatusCode.Should().Be(HttpStatusCode.OK, "create should succeed; body: {0}", await createResp.Content.ReadAsStringAsync()); var created = await createResp.Content.ReadFromJsonAsync(); // List var listReq = WithAuth(new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications")); var listResp = await _http.SendAsync(listReq); listResp.StatusCode.Should().Be(HttpStatusCode.OK); // Delete (cleanup) var id = GetIdFromResponse(created); if (id is not null) { var deleteReq = WithAuth(new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/identity/applications/{id}")); var deleteResp = await _http.SendAsync(deleteReq); deleteResp.StatusCode.Should().Be(HttpStatusCode.OK); } } // ── Scopes ── [Fact] public async Task Scopes_CrudLifecycle() { var scopeName = $"test-scope-{Guid.NewGuid():N}"; // Create var createReq = WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/scopes") { Content = JsonContent.Create(new { name = scopeName, displayName = "Test Scope" }) }); var createResp = await _http.SendAsync(createReq); createResp.StatusCode.Should().Be(HttpStatusCode.OK, "create should succeed; body: {0}", await createResp.Content.ReadAsStringAsync()); // List var listReq = WithAuth(new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/scopes")); var listResp = await _http.SendAsync(listReq); listResp.StatusCode.Should().Be(HttpStatusCode.OK); } // ── Users ── [Fact] public async Task Users_CrudLifecycle() { var login = $"test-user-{Guid.NewGuid():N}"; // Create var createReq = WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/users") { Content = JsonContent.Create(new { login, password = "P@ssw0rd123!" }) }); var createResp = await _http.SendAsync(createReq); createResp.StatusCode.Should().Be(HttpStatusCode.OK, "create should succeed; body: {0}", await createResp.Content.ReadAsStringAsync()); // List var listReq = WithAuth(new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/users")); var listResp = await _http.SendAsync(listReq); listResp.StatusCode.Should().Be(HttpStatusCode.OK); } // ── Tokens ── [Fact] public async Task Tokens_ListAndPrune() { // List var listReq = WithAuth(new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/tokens")); var listResp = await _http.SendAsync(listReq); listResp.StatusCode.Should().Be(HttpStatusCode.OK); // Prune var pruneReq = WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/tokens/prune")); var pruneResp = await _http.SendAsync(pruneReq); pruneResp.StatusCode.Should().Be(HttpStatusCode.OK); } // ── Bearer token validation ── [Fact] public async Task ManagementApi_NoBearerToken_Returns401() { var response = await _http.GetAsync("/api/v1/identity/applications"); response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); } [Fact] public async Task ManagementApi_InvalidBearerToken_Returns401() { var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "invalid-garbage-token"); var response = await _http.SendAsync(req); response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); } // ── Discovery ── [Fact] public async Task Discovery_ReturnsOpenIdConfiguration() { var response = await _http.GetAsync("/.well-known/openid-configuration"); response.StatusCode.Should().Be(HttpStatusCode.OK); var body = await response.Content.ReadAsStringAsync(); var json = JsonDocument.Parse(body).RootElement; json.GetProperty("issuer").GetString().Should().Contain("localhost"); json.TryGetProperty("token_endpoint", out _).Should().BeTrue( "discovery must include token_endpoint"); json.TryGetProperty("grant_types_supported", out _).Should().BeTrue( "discovery must include grant_types_supported"); } [Fact] public async Task Jwks_ReturnsKeySet() { var response = await _http.GetAsync("/.well-known/jwks"); response.StatusCode.Should().Be(HttpStatusCode.OK); var body = await response.Content.ReadAsStringAsync(); var json = JsonDocument.Parse(body).RootElement; json.TryGetProperty("keys", out var keys).Should().BeTrue( "JWKS must contain 'keys' array"); keys.ValueKind.Should().Be(JsonValueKind.Array, "'keys' must be a native JSON array"); keys.GetArrayLength().Should().BeGreaterThan(0, "JWKS must contain at least one signing key"); } private static string? GetIdFromResponse(JsonElement element) { if (element.TryGetProperty("id", out var id)) return id.ToString(); if (element.TryGetProperty("Id", out id)) return id.ToString(); return null; } // ── Rotate client_secret (W-3 follow-up) ── /// /// Happy path: create confidential client with secret S1, rotate via /// POST {id}/rotate-secret, then verify against the live store that /// (a) the response carries a non-empty newSecret, /// (b) the stored BCrypt hash of ClientSecret has changed (proves persistence /// committed across the full HTTP → controller → direct-vm → processor → store path), /// (c) the new plaintext verifies against the new hash via the same OpenIddict /// password hasher used by the token endpoint (proves the hash format is the one /// credential validation expects, not a foreign encoding that would silently fail). /// /// Why we do not POST /connect/token with the old/new secret in this test: /// runs OpenIddict in EnableDegradedMode() /// and short-circuits ValidateTokenRequestContext, so credential validation is /// bypassed entirely — any secret would succeed and the assertion would be meaningless. /// We assert against the storage layer instead. /// /// [Fact] public async Task RotateSecret_returns_new_secret_and_changes_stored_hash() { var clientId = $"rotate-test-{Guid.NewGuid():N}"; const string oldSecret = "S1-original-secret"; var createReq = WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/applications") { Content = JsonContent.Create(new { clientId, clientSecret = oldSecret, clientType = "confidential", displayName = "Rotate-Test" }) }); var createResp = await _http.SendAsync(createReq); createResp.StatusCode.Should().Be(HttpStatusCode.OK, "create should succeed; body: {0}", await createResp.Content.ReadAsStringAsync()); var id = GetIdFromResponse(await createResp.Content.ReadFromJsonAsync())!; var numericId = long.Parse(id); try { // Snapshot the BCrypt hash that CreateAsync stored. We verify rotation by // checking this value changes — there is no way to recover plaintext from a // BCrypt digest, so this is the strongest property we can assert. var beforeApp = await _fixture.Redb.LoadAsync(numericId); beforeApp.Should().NotBeNull("the freshly created application must be loadable"); var beforeHash = beforeApp!.Props.ClientSecret; beforeHash.Should().NotBeNullOrEmpty("create must have stored a hashed secret"); // Rotate via the public HTTP API. var rotateReq = WithAuth(new HttpRequestMessage( HttpMethod.Post, $"/api/v1/identity/applications/{id}/rotate-secret")); var rotateResp = await _http.SendAsync(rotateReq); rotateResp.StatusCode.Should().Be(HttpStatusCode.OK, "rotate should succeed; body: {0}", await rotateResp.Content.ReadAsStringAsync()); var rotated = await rotateResp.Content.ReadFromJsonAsync(); rotated.TryGetProperty("newSecret", out var newSecretProp).Should().BeTrue( "response must carry newSecret exactly once"); var newSecret = newSecretProp.GetString(); newSecret.Should().NotBeNullOrWhiteSpace(); newSecret.Should().NotBe(oldSecret, "rotation must produce a different plaintext"); // Re-load and confirm the stored hash actually changed in the database. var afterApp = await _fixture.Redb.LoadAsync(numericId); afterApp.Should().NotBeNull(); var afterHash = afterApp!.Props.ClientSecret; afterHash.Should().NotBeNullOrEmpty("after rotation a hash must still be present"); afterHash.Should().NotBe(beforeHash, "rotate must replace the stored hash; if these match the SaveAsync path is a no-op"); // Verify the new plaintext verifies against the new hash through the SAME // OpenIddict pipeline the token endpoint uses for client_credentials. This // guards against a silent regression where rotation stores a hash in a format // (or with a salt) that ValidateClientSecretAsync cannot read back. using var verifyScope = _fixture.ServiceProvider.CreateScope(); var manager = verifyScope.ServiceProvider.GetRequiredService(); var entity = await manager.FindByIdAsync(id, default); entity.Should().NotBeNull(); (await manager.ValidateClientSecretAsync(entity!, newSecret!, default)) .Should().BeTrue("the freshly returned plaintext must verify against the freshly stored hash"); (await manager.ValidateClientSecretAsync(entity!, oldSecret, default)) .Should().BeFalse("the previous plaintext must no longer verify against the new hash"); } finally { var deleteReq = WithAuth(new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/identity/applications/{id}")); await _http.SendAsync(deleteReq); } } /// /// Public clients have no client_secret by definition (RFC 6749 §2.1) — rotation /// must reject them with HTTP 400 instead of silently generating a secret nobody /// can use at the token endpoint. /// [Fact] public async Task RotateSecret_rejects_public_client_with_400() { var clientId = $"rotate-public-{Guid.NewGuid():N}"; var createReq = WithAuth(new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/applications") { Content = JsonContent.Create(new { clientId, clientType = "public", displayName = "Rotate-Public-Reject" }) }); var createResp = await _http.SendAsync(createReq); createResp.StatusCode.Should().Be(HttpStatusCode.OK, "create public client should succeed; body: {0}", await createResp.Content.ReadAsStringAsync()); var id = GetIdFromResponse(await createResp.Content.ReadFromJsonAsync())!; try { var rotateReq = WithAuth(new HttpRequestMessage( HttpMethod.Post, $"/api/v1/identity/applications/{id}/rotate-secret")); var rotateResp = await _http.SendAsync(rotateReq); rotateResp.StatusCode.Should().Be(HttpStatusCode.BadRequest, "public clients must be refused; body: {0}", await rotateResp.Content.ReadAsStringAsync()); var body = await rotateResp.Content.ReadAsStringAsync(); body.Should().Contain("invalid_client_type", "error code must let callers distinguish this from generic validation failures"); } finally { var deleteReq = WithAuth(new HttpRequestMessage(HttpMethod.Delete, $"/api/v1/identity/applications/{id}")); await _http.SendAsync(deleteReq); } } } Path: redb-identity/tests/redb.Identity.Tests/Http/E2E/ManagementBearerAuthTests.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/Http/E2E/ManagementBearerAuthTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http.E2E; /// /// E2E tests for management API bearer token authentication. /// Exercises the full pipeline: HTTP request → ManagementBearerAuthProcessor /// → OpenIddict Validation (server-local) → scope check. /// [Collection("HttpIdentity")] public class ManagementBearerAuthTests { private readonly HttpIdentityFixture _fixture; private readonly HttpClient _http; public ManagementBearerAuthTests(HttpIdentityFixture fixture) { _fixture = fixture; _http = fixture.Http; } [Fact] public async Task ValidToken_CorrectScope_AllowsAccess() { var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fixture.ManagementToken); var response = await _http.SendAsync(req); response.StatusCode.Should().Be(HttpStatusCode.OK); } [Fact] public async Task NoAuthorizationHeader_Returns401() { var response = await _http.GetAsync("/api/v1/identity/applications"); response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); var body = await ReadErrorBody(response); body.GetProperty("error").GetString().Should().Be("missing_token"); } [Fact] public async Task BearerInQueryParameter_NoHeader_Returns401() { // RFC 6750 §2.3: query-parameter bearer transport is deprecated. // The management API only honours Authorization: Bearer; even a syntactically // valid token presented via ?access_token= must not authorise the request. // Source: G9 / D6. var url = $"/api/v1/identity/applications?access_token={Uri.EscapeDataString(_fixture.ManagementToken)}"; var response = await _http.GetAsync(url); response.StatusCode.Should().Be(HttpStatusCode.Unauthorized, "query-string bearer must NOT be accepted on the management API"); var body = await ReadErrorBody(response); body.GetProperty("error").GetString().Should().Be("missing_token"); } [Fact] public async Task InvalidToken_GarbageString_Returns401() { var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "not-a-valid-token"); var response = await _http.SendAsync(req); response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); var body = await ReadErrorBody(response); body.GetProperty("error").GetString().Should().Be("invalid_token"); } [Fact] public async Task EmptyBearerToken_Returns401() { var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); req.Headers.TryAddWithoutValidation("Authorization", "Bearer "); var response = await _http.SendAsync(req); response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); } [Fact] public async Task WrongScheme_BasicAuth_Returns401() { var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); req.Headers.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String("user:pass"u8)); var response = await _http.SendAsync(req); response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); var body = await ReadErrorBody(response); body.GetProperty("error").GetString().Should().Be("missing_token"); } [Fact] public async Task TokenWithoutManageScope_Returns403() { // Issue a token WITHOUT identity:manage scope var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "no-scope-client", ["client_secret"] = "some-secret", ["scope"] = "openid profile" }); var tokenResp = await _http.PostAsync("/connect/token", content); tokenResp.StatusCode.Should().Be(HttpStatusCode.OK); var tokenJson = await JsonSerializer.DeserializeAsync( await tokenResp.Content.ReadAsStreamAsync()); var token = tokenJson.GetProperty("access_token").GetString()!; // Use the limited token for management API var req = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/applications"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); var response = await _http.SendAsync(req); response.StatusCode.Should().Be(HttpStatusCode.Forbidden); var body = await ReadErrorBody(response); body.GetProperty("error").GetString().Should().Be("insufficient_scope"); } [Fact] public async Task AllManagementEndpoints_RequireBearerToken() { // All management paths should reject unauthenticated requests var paths = new[] { "/api/v1/identity/applications", "/api/v1/identity/scopes", "/api/v1/identity/users", "/api/v1/identity/tokens", "/api/v1/identity/groups" }; foreach (var path in paths) { var response = await _http.GetAsync(path); response.StatusCode.Should().Be(HttpStatusCode.Unauthorized, $"GET {path} should require bearer token"); } } [Fact] public async Task ValidToken_PostRequest_Works() { var req = new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/applications") { Content = JsonContent.Create(new { clientId = $"auth-test-{Guid.NewGuid():N}", clientSecret = "test-secret", displayName = "Auth Test App" }) }; req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fixture.ManagementToken); var response = await _http.SendAsync(req); response.StatusCode.Should().Be(HttpStatusCode.OK, "POST with valid bearer token should succeed"); } private static async Task ReadErrorBody(HttpResponseMessage response) { var stream = await response.Content.ReadAsStreamAsync(); return await JsonSerializer.DeserializeAsync(stream); } } Path: redb-identity/tests/redb.Identity.Tests/Http/E2E/RevokedSidsApiTests.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/Http/E2E/RevokedSidsApiTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Contracts.Sessions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http.E2E; /// /// W6-0: E2E test of the backchannel revoked-sids list. Exercises the full pipeline: /// HTTP \u2192 RevokedSidsController \u2192 direct-vm://identity-revoked-sids \u2192 /// RevokedSidsManagementProcessor \u2192 redb PROPS. Uses real PostgreSQL + Kestrel via /// . /// [Collection("HttpIdentity")] public class RevokedSidsApiTests { private const string Base = "/api/v1/identity/revoked-sids"; private readonly HttpIdentityFixture _fixture; private readonly HttpClient _http; public RevokedSidsApiTests(HttpIdentityFixture fixture) { _fixture = fixture; _http = fixture.Http; } private HttpRequestMessage WithAuth(HttpRequestMessage request) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fixture.ManagementToken); return request; } private async Task AddAsync(string? sid, string? sub, string? clientId = null, DateTimeOffset? expiresAt = null) { var req = WithAuth(new HttpRequestMessage(HttpMethod.Post, Base) { Content = JsonContent.Create(new RevokedSidsAddRequest { Sid = sid, Sub = sub, ClientId = clientId, ExpiresAt = expiresAt }) }); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, "add should succeed; body: {0}", await resp.Content.ReadAsStringAsync()); return (await resp.Content.ReadFromJsonAsync())!; } private async Task SinceAsync(DateTimeOffset? cursor = null) { var url = cursor.HasValue ? $"{Base}/since?cursor={Uri.EscapeDataString(cursor.Value.ToString("O"))}" : $"{Base}/since"; var req = WithAuth(new HttpRequestMessage(HttpMethod.Get, url)); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.OK, "since should succeed; body: {0}", await resp.Content.ReadAsStringAsync()); return (await resp.Content.ReadFromJsonAsync())!; } [Fact] public async Task Add_then_Since_returns_entry() { var sid = $"sid-{Guid.NewGuid():N}"; // Take cursor BEFORE adding so we know our entry is included. var before = await SinceAsync(); var cursor = before.ServerTime; var added = await AddAsync(sid: sid, sub: "user-1"); added.Sid.Should().Be(sid); added.Sub.Should().Be("user-1"); added.RevokedAt.Should().BeAfter(DateTimeOffset.UtcNow.AddMinutes(-1)); added.ExpiresAt.Should().BeAfter(added.RevokedAt); var after = await SinceAsync(cursor); after.Entries.Should().Contain(e => e.Sid == sid); after.NextCursor.Should().BeOnOrAfter(cursor); } [Fact] public async Task Since_with_recent_cursor_returns_only_newer() { var sidOld = $"sid-old-{Guid.NewGuid():N}"; await AddAsync(sid: sidOld, sub: "user-1"); // Cursor between the two adds. var mid = (await SinceAsync()).ServerTime; await Task.Delay(50); // ensure DateCreate strictly > mid var sidNew = $"sid-new-{Guid.NewGuid():N}"; await AddAsync(sid: sidNew, sub: "user-1"); var after = await SinceAsync(mid); after.Entries.Should().Contain(e => e.Sid == sidNew); after.Entries.Should().NotContain(e => e.Sid == sidOld); } [Fact] public async Task Add_with_sub_only_publishes_sub_entry() { var sub = $"sub-{Guid.NewGuid():N}"; var cursor = (await SinceAsync()).ServerTime; var added = await AddAsync(sid: null, sub: sub); added.Sid.Should().BeNull(); added.Sub.Should().Be(sub); var after = await SinceAsync(cursor); after.Entries.Should().Contain(e => e.Sub == sub && e.Sid == null); } [Fact] public async Task Add_without_sid_or_sub_returns_400_invalid_request() { var req = WithAuth(new HttpRequestMessage(HttpMethod.Post, Base) { Content = JsonContent.Create(new RevokedSidsAddRequest { Sid = null, Sub = null, ClientId = "client-x" }) }); var resp = await _http.SendAsync(req); resp.StatusCode.Should().Be(HttpStatusCode.BadRequest); } [Fact] public async Task Add_clamps_excessive_expires_at_to_max_retention() { // Default RevokedSidsMaxRetention = 24h; request 30 days \u2192 server clamps. var huge = DateTimeOffset.UtcNow.AddDays(30); var sid = $"sid-clamp-{Guid.NewGuid():N}"; var added = await AddAsync(sid: sid, sub: null, expiresAt: huge); added.ExpiresAt.Should().BeBefore(DateTimeOffset.UtcNow.AddDays(2)); added.ExpiresAt.Should().BeAfter(DateTimeOffset.UtcNow.AddHours(23)); } [Fact] public async Task Add_requires_management_auth() { var req = new HttpRequestMessage(HttpMethod.Post, Base) { Content = JsonContent.Create(new RevokedSidsAddRequest { Sid = "sid-noauth", Sub = "user-1" }) }; // No Authorization header. var resp = await _http.SendAsync(req); resp.StatusCode.Should().BeOneOf(HttpStatusCode.Unauthorized, HttpStatusCode.Forbidden); } [Fact] public async Task Since_first_call_without_cursor_returns_baseline_window() { // Sanity: bootstrap call returns a populated response with ServerTime and a cursor. var resp = await SinceAsync(); resp.ServerTime.Should().BeAfter(DateTimeOffset.UtcNow.AddMinutes(-1)); resp.NextCursor.Should().BeOnOrBefore(resp.ServerTime); } } Path: redb-identity/tests/redb.Identity.Tests/Http/E2E/UnreadableBasicCredentialsTests.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/Http/E2E/UnreadableBasicCredentialsTests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http.E2E; /// /// A client that sends Authorization: Basic attempts client authentication through the header. /// When the value cannot be read (not base64, not its canonical spelling, which .NET 10 decodes and /// .NET 11 refuses, or no client_id:client_secret pair) the attempt failed: every endpoint that /// takes client authentication answers 401 invalid_client with a Basic challenge (RFC 6749 §5.2), /// on every runtime. Up to this change the token endpoint answered such a request with a 500. /// [Collection("ProductionHttp")] public sealed class UnreadableBasicCredentialsTests { private const string NotBase64 = "!!!not-base64!!!"; private readonly ProductionHttpFixture _fx; public UnreadableBasicCredentialsTests(ProductionHttpFixture fx) => _fx = fx; public static TheoryData Cases() { var data = new TheoryData(); foreach (var endpoint in new[] { "/connect/token", "/connect/introspect", "/connect/revocation", "/connect/deviceauthorization", "/connect/par", }) { data.Add(endpoint, NotBase64); data.Add(endpoint, NonCanonical(ProductionHttpFixture.TestClientId + ":" + ProductionHttpFixture.TestClientSecret)); data.Add(endpoint, Convert.ToBase64String("no-colon-here"u8)); } return data; } [Theory] [MemberData(nameof(Cases))] public async Task UnreadableBasicValue_AnswersInvalidClient_WithABasicChallenge(string endpoint, string basic) { var (status, error, challenge, body) = await Post(endpoint, basic); status.Should().Be(HttpStatusCode.Unauthorized, body); error.Should().Be("invalid_client", body); challenge.Should().StartWith("Basic ", body); } [Fact] public async Task ReadableBasicCredentials_StillAuthenticate() { var basic = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes(ProductionHttpFixture.TestClientId + ":" + ProductionHttpFixture.TestClientSecret)); var (status, error, _, body) = await Post("/connect/token", basic); status.Should().Be(HttpStatusCode.OK, body); error.Should().BeNull(body); } /// /// Device authorization and PAR read Basic credentials as the token endpoint does, so discovery /// names client_secret_basic for them wherever it lists their authentication methods. /// [Fact] public async Task Discovery_NamesClientSecretBasic_ForEveryClientAuthenticatedEndpoint() { using var response = await _fx.Http.GetAsync("/.well-known/openid-configuration"); var body = await response.Content.ReadAsStringAsync(); response.StatusCode.Should().Be(HttpStatusCode.OK, body); var root = JsonDocument.Parse(body).RootElement; foreach (var name in new[] { "token_endpoint_auth_methods_supported", "introspection_endpoint_auth_methods_supported", "revocation_endpoint_auth_methods_supported", "device_authorization_endpoint_auth_methods_supported", "pushed_authorization_request_endpoint_auth_methods_supported", }) { if (!root.TryGetProperty(name, out var methods)) continue; methods.EnumerateArray().Select(m => m.GetString()).Should().Contain("client_secret_basic", $"{name}: {methods}"); } } private async Task<(HttpStatusCode Status, string? Error, string? Challenge, string Body)> Post(string endpoint, string basic) { var form = endpoint switch { "/connect/token" => new Dictionary { ["grant_type"] = "client_credentials" }, "/connect/introspect" or "/connect/revocation" => new Dictionary { ["token"] = "opaque" }, "/connect/deviceauthorization" => new Dictionary { ["scope"] = "openid" }, _ => new Dictionary { ["response_type"] = "code", ["redirect_uri"] = "https://client.example/cb", ["scope"] = "openid", }, }; using var request = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new FormUrlEncodedContent(form) }; request.Headers.TryAddWithoutValidation("Authorization", $"Basic {basic}"); using var response = await _fx.Http.SendAsync(request); var body = await response.Content.ReadAsStringAsync(); string? error = null; if (body.TrimStart().StartsWith('{') && JsonDocument.Parse(body).RootElement.TryGetProperty("error", out var e)) error = e.GetString(); var challenge = response.Headers.WwwAuthenticate.Count > 0 ? response.Headers.WwwAuthenticate.ToString() : null; return (response.StatusCode, error, challenge, body); } /// The same bytes spelled with a non-zero unused bit in the last character. private static string NonCanonical(string text) { const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var canonical = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); var data = canonical.TrimEnd('='); if (data.Length == canonical.Length) throw new InvalidOperationException($"'{text}' encodes without padding; pick a length that is not a multiple of three."); var last = alphabet.IndexOf(data[^1]); return data[..^1] + alphabet[last | 1] + canonical[data.Length..]; } } Path: redb-identity/tests/redb.Identity.Tests/Http/HttpFacadeRouteBuilderTests.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/Http/HttpFacadeRouteBuilderTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NSubstitute; using OpenIddict.Server; using redb.Core; using redb.Identity.Contracts.Configuration; using redb.Identity.Core.Configuration; using redb.Identity.Core.OpenIddict; using redb.Identity.Core.Services; using redb.Identity.Http; using redb.Identity.Http.Security; using redb.Route.Abstractions; using redb.Route.Definitions; using Xunit; namespace redb.Identity.Tests.Http; public class HttpFacadeRouteBuilderTests { private readonly HttpFacadeRouteBuilder _builder; public HttpFacadeRouteBuilderTests() { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); services.AddSingleton(Options.Create(new RedbIdentityOptions())); services.AddSingleton(Options.Create(new IdentityTransportOptions())); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddOpenIddict() .AddServer(options => { options.EnableDegradedMode(); options.SetIssuer(new Uri("https://identity.test.local/")); options.SetTokenEndpointUris("/connect/token"); options.AllowClientCredentialsFlow(); options.AddEphemeralEncryptionKey(); options.AddEphemeralSigningKey(); options.DisableAccessTokenEncryption(); options.UseRedbRoute(); }); var sp = services.BuildServiceProvider(); var ticketService = new SessionTicketService(sp.GetRequiredService()); _builder = new HttpFacadeRouteBuilder( ticketService, sp.GetRequiredService>()); ((IRouteBuilder)_builder).Configure(null!); } [Fact] public void Configure_DoesNotThrow() { _builder.Definitions.Should().NotBeEmpty(); } [Fact] public void Protocol_Routes_Have_Correct_Count() { // Always-mounted protocol routes with the fixture's default options // (Features = all-off, so ConfigureScimApi, federation-providers/public, // ConfigurePublicFederationProvidersEndpoint, the /scim/v2 resource routes, // PAR, DCR, device-code, and all other feature-gated mounts are absent): // // token, authorize-get, authorize-post, login-get, login-post, // consent-get, consent-post, userinfo-get, userinfo-post, // revoke, introspect, discovery (OIDC), discovery-oauth (RFC 8414), // jwks, management, // logout-get, logout-post, // mfa-get, mfa-post, mfa-recovery-get, mfa-recovery-post, // mfa-challenge-post, mfa-methods-post, // bootstrap-admin (B1 emergency-admin endpoint, mounted on management port), // scim/v2/ServiceProviderConfig, scim/v2/ResourceTypes, scim/v2/Schemas, // scim/v2/ResourceTypes/{id}, scim/v2/Schemas/{id} // (RFC 7644 §4 SCIM discovery — unauthenticated and mounted UNCONDITIONALLY // on the management port so RPs can discover the SCIM surface even when // EnableScim=false; the resource endpoints under /scim/v2 stay gated. // The two single-resource routes were missing: a provisioning client is pointed // at ONE base URL, walks ResourceTypes and then fetches each Schema BY ID — // which 404'd. Same registry, same controller; only the routes were absent.) // = 29 _builder.Definitions.Should().HaveCount(29); } [Theory] [InlineData("http-token")] [InlineData("http-authorize-get")] [InlineData("http-authorize-post")] [InlineData("http-userinfo-get")] [InlineData("http-userinfo-post")] [InlineData("http-revoke")] [InlineData("http-introspect")] [InlineData("http-discovery")] [InlineData("http-jwks")] [InlineData("http-management-api")] public void Route_With_Id_Exists(string routeId) { _builder.Definitions .Select(d => d.GetRouteId()) .Should().Contain(routeId); } [Theory] [InlineData("http-token", "/connect/token")] [InlineData("http-authorize-get", "/connect/authorize")] [InlineData("http-authorize-post", "/connect/authorize")] [InlineData("http-userinfo-get", "/connect/userinfo")] [InlineData("http-userinfo-post", "/connect/userinfo")] [InlineData("http-revoke", "/connect/revocation")] [InlineData("http-introspect", "/connect/introspect")] [InlineData("http-discovery", "/.well-known/openid-configuration")] [InlineData("http-jwks", "/.well-known/jwks")] public void Protocol_Route_FromUri_ContainsExpectedPath(string routeId, string expectedPath) { var route = _builder.Definitions.First(d => d.GetRouteId() == routeId); route.GetFromUri().Should().Contain(expectedPath); } [Fact] public void Management_Route_Uses_CatchAll_Path() { var route = _builder.Definitions.First(d => d.GetRouteId() == "http-management-api"); var fromUri = route.GetFromUri(); fromUri.Should().Contain("/api/v1/identity/{**path}"); fromUri.Should().Contain("inOut=true"); } [Fact] public void CustomHostAndPort_Config_Reflected_In_Routes() { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); services.AddSingleton(Options.Create(new RedbIdentityOptions())); services.AddSingleton(Options.Create(new IdentityTransportOptions { Http = new HttpTransportOptions { Host = "127.0.0.1", PublicPort = 9090 } })); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddOpenIddict() .AddServer(options => { options.EnableDegradedMode(); options.SetIssuer(new Uri("https://identity.test.local/")); options.SetTokenEndpointUris("/connect/token"); options.AllowClientCredentialsFlow(); options.AddEphemeralEncryptionKey(); options.AddEphemeralSigningKey(); options.DisableAccessTokenEncryption(); options.UseRedbRoute(); }); var sp = services.BuildServiceProvider(); var ts = new SessionTicketService(sp.GetRequiredService()); var builder = new HttpFacadeRouteBuilder( ts, sp.GetRequiredService>()); ((IRouteBuilder)builder).Configure(null!); // Every listener binds the configured address; none falls back to every interface. builder.Definitions.Should().AllSatisfy(d => { d.GetFromUri().Should().Contain("127.0.0.1:9090"); d.GetFromUri().Should().NotContain("0.0.0.0"); }); } [Fact] public void SeparateManagementPort_Config_Works() { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); services.AddSingleton(Options.Create(new RedbIdentityOptions())); services.AddSingleton(Options.Create(new IdentityTransportOptions { Http = new HttpTransportOptions { PublicPort = 8080, ManagementPort = 8081 } })); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddOpenIddict() .AddServer(options => { options.EnableDegradedMode(); options.SetIssuer(new Uri("https://identity.test.local/")); options.SetTokenEndpointUris("/connect/token"); options.AllowClientCredentialsFlow(); options.AddEphemeralEncryptionKey(); options.AddEphemeralSigningKey(); options.DisableAccessTokenEncryption(); options.UseRedbRoute(); }); var sp = services.BuildServiceProvider(); var ts = new SessionTicketService(sp.GetRequiredService()); var builder = new HttpFacadeRouteBuilder( ts, sp.GetRequiredService>()); ((IRouteBuilder)builder).Configure(null!); var mgmtRoute = builder.Definitions.First(d => d.GetRouteId() == "http-management-api"); mgmtRoute.GetFromUri().Should().Contain("8081"); var tokenRoute = builder.Definitions.First(d => d.GetRouteId() == "http-token"); tokenRoute.GetFromUri().Should().Contain("8080"); } // ── Conditional feature routes ── [Fact] public void DynamicRegistration_Disabled_NoRegisterRoute() { // Default builder has EnableDynamicRegistration=false _builder.Definitions .Select(d => d.GetRouteId()) .Should().NotContain("http-dynamic-register"); } [Fact] public void DynamicRegistration_Enabled_RegisterRouteExists() { var builder = CreateBuilder( transport: new IdentityTransportOptions { Features = new IdentityFeatureFlags { EnableDynamicRegistration = true } }); builder.Definitions .Select(d => d.GetRouteId()) .Should().Contain("http-dynamic-register"); } [Fact] public void DynamicRegistration_Enabled_RegisterRoute_PointsToConnectRegister() { var builder = CreateBuilder( transport: new IdentityTransportOptions { Features = new IdentityFeatureFlags { EnableDynamicRegistration = true } }); var route = builder.Definitions.First(d => d.GetRouteId() == "http-dynamic-register"); route.GetFromUri().Should().Contain("/connect/register"); } [Fact] public void DeviceCodeFlow_Disabled_NoDeviceRoutes() { // Default builder has EnableDeviceCodeFlow=false _builder.Definitions .Select(d => d.GetRouteId()) .Should().NotContain(id => id.Contains("device", StringComparison.OrdinalIgnoreCase)); } [Fact] public void DeviceCodeFlow_Enabled_DeviceRouteExists() { var builder = CreateBuilder( transport: new IdentityTransportOptions { Features = new IdentityFeatureFlags { EnableDeviceCodeFlow = true } }); builder.Definitions .Select(d => d.GetRouteId()) .Should().Contain(id => id.Contains("device", StringComparison.OrdinalIgnoreCase)); } [Fact] public void DynamicRegistration_Enabled_RouteCount_Increases() { var defaultCount = _builder.Definitions.Count; var builder = CreateBuilder( transport: new IdentityTransportOptions { Features = new IdentityFeatureFlags { EnableDynamicRegistration = true } }); builder.Definitions.Count.Should().Be(defaultCount + 2, "enabling dynamic registration should add the registration and management routes (RFC 7591 + 7592)"); } private static HttpFacadeRouteBuilder CreateBuilder( RedbIdentityOptions? identity = null, IdentityTransportOptions? transport = null) { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); services.AddSingleton(Options.Create(identity ?? new RedbIdentityOptions())); services.AddSingleton(Options.Create(transport ?? new IdentityTransportOptions())); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddOpenIddict() .AddServer(options => { options.EnableDegradedMode(); options.SetIssuer(new Uri("https://identity.test.local/")); options.SetTokenEndpointUris("/connect/token"); options.AllowClientCredentialsFlow(); options.AddEphemeralEncryptionKey(); options.AddEphemeralSigningKey(); options.DisableAccessTokenEncryption(); options.UseRedbRoute(); }); var sp = services.BuildServiceProvider(); var ts = new SessionTicketService(sp.GetRequiredService()); var builder = new HttpFacadeRouteBuilder( ts, sp.GetRequiredService>()); ((IRouteBuilder)builder).Configure(null!); return builder; } } Path: redb-identity/tests/redb.Identity.Tests/Http/HttpIdentityProcessorsTests.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/Http/HttpIdentityProcessorsTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Identity.Http.Processors; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using Xunit; namespace redb.Identity.Tests.Http; public class HttpIdentityProcessorsTests { // ── MapHttpToIdentityHeaders ── [Fact] public async Task MapHttpToIdentityHeaders_BasicAuth_SetsClientIdAndSecret() { var exchange = CreateExchange(); var encoded = Convert.ToBase64String("my-client:my-secret"u8); exchange.In.Headers[HttpHeaders.Authorization] = $"Basic {encoded}"; await HttpIdentityProcessors.MapHttpToIdentityHeaders(exchange, CancellationToken.None); exchange.In.GetHeader("client_id").Should().Be("my-client"); exchange.In.GetHeader("client_secret").Should().Be("my-secret"); } [Fact] public async Task MapHttpToIdentityHeaders_BasicAuth_NoSecret_SetsOnlyClientId() { var exchange = CreateExchange(); var encoded = Convert.ToBase64String("client-only"u8); exchange.In.Headers[HttpHeaders.Authorization] = $"Basic {encoded}"; await HttpIdentityProcessors.MapHttpToIdentityHeaders(exchange, CancellationToken.None); exchange.In.GetHeader("client_id").Should().Be("client-only"); exchange.In.Headers.ContainsKey("client_secret").Should().BeFalse(); } [Fact] public async Task MapHttpToIdentityHeaders_UrlEncodedCredentials_Decoded() { var exchange = CreateExchange(); var encoded = Convert.ToBase64String("client%3Aid:secret%26value"u8); exchange.In.Headers[HttpHeaders.Authorization] = $"Basic {encoded}"; await HttpIdentityProcessors.MapHttpToIdentityHeaders(exchange, CancellationToken.None); exchange.In.GetHeader("client_id").Should().Be("client:id"); exchange.In.GetHeader("client_secret").Should().Be("secret&value"); } [Fact] public async Task MapHttpToIdentityHeaders_NoAuth_DoesNotThrow() { var exchange = CreateExchange(); await HttpIdentityProcessors.MapHttpToIdentityHeaders(exchange, CancellationToken.None); exchange.In.Headers.ContainsKey("client_id").Should().BeFalse(); } [Fact] public async Task MapHttpToIdentityHeaders_PropagatesContentType() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.ContentType] = "application/x-www-form-urlencoded"; await HttpIdentityProcessors.MapHttpToIdentityHeaders(exchange, CancellationToken.None); exchange.In.GetHeader("Content-Type").Should().Be("application/x-www-form-urlencoded"); } // ── ExtractBearerToken ── [Fact] public async Task ExtractBearerToken_ValidBearer_SetsAccessToken() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Authorization] = "Bearer eyJhbGciOiJSUzI1NiJ9.test"; await HttpIdentityProcessors.ExtractBearerToken(exchange, CancellationToken.None); exchange.In.GetHeader("access_token").Should().Be("eyJhbGciOiJSUzI1NiJ9.test"); } [Fact] public async Task ExtractBearerToken_CaseInsensitive() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Authorization] = "bearer my-token"; await HttpIdentityProcessors.ExtractBearerToken(exchange, CancellationToken.None); exchange.In.GetHeader("access_token").Should().Be("my-token"); } [Fact] public async Task ExtractBearerToken_NotBearer_Ignores() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Authorization] = "Basic abc"; await HttpIdentityProcessors.ExtractBearerToken(exchange, CancellationToken.None); exchange.In.Headers.ContainsKey("access_token").Should().BeFalse(); } // ── MapQueryToBody ── [Fact] public async Task MapQueryToBody_ParsesQueryString() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Query] = "client_id=app&response_type=code&scope=openid+profile"; await HttpIdentityProcessors.MapQueryToBody(exchange, CancellationToken.None); var body = exchange.In.Body as IDictionary; body.Should().NotBeNull(); body!["client_id"].Should().Be("app"); body["response_type"].Should().Be("code"); body["scope"].Should().Be("openid profile"); } [Fact] public async Task MapQueryToBody_EmptyQuery_NoChange() { var exchange = CreateExchange(); exchange.In.Body = "original"; await HttpIdentityProcessors.MapQueryToBody(exchange, CancellationToken.None); exchange.In.Body.Should().Be("original"); } // ── MapFormToBody ── [Fact] public async Task MapFormToBody_ParsesFormBody() { var exchange = CreateExchange(); exchange.In.Body = "grant_type=client_credentials&client_id=app"; await HttpIdentityProcessors.MapFormToBody(exchange, CancellationToken.None); var body = exchange.In.Body as IDictionary; body.Should().NotBeNull(); body!["grant_type"].Should().Be("client_credentials"); body["client_id"].Should().Be("app"); } // ── HandleRedirectResponse ── [Fact] public async Task HandleRedirectResponse_SetsRedirectHeaders() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Headers["redirect_uri"] = "https://app.test/callback?code=abc&state=xyz"; await HttpIdentityProcessors.HandleRedirectResponse(exchange, CancellationToken.None); exchange.Out.GetHeader(HttpHeaders.ResponseCode).Should().Be(302); exchange.Out.GetHeader("Location") .Should().Be("https://app.test/callback?code=abc&state=xyz"); } [Fact] public async Task HandleRedirectResponse_NoRedirect_NoChange() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = "normal response"; await HttpIdentityProcessors.HandleRedirectResponse(exchange, CancellationToken.None); exchange.Out.Headers.ContainsKey("Location").Should().BeFalse(); } // ── StripManagementPrefix ── [Fact] public async Task StripManagementPrefix_RemovesApiIdentityPrefix() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Path] = "/api/v1/identity/applications/123"; await HttpIdentityProcessors.StripManagementPrefix(exchange, CancellationToken.None); exchange.In.GetHeader(HttpHeaders.Path).Should().Be("/applications/123"); } [Fact] public async Task StripManagementPrefix_RootPath_BecomesSingleSlash() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Path] = "/api/v1/identity/"; await HttpIdentityProcessors.StripManagementPrefix(exchange, CancellationToken.None); exchange.In.GetHeader(HttpHeaders.Path).Should().Be("/"); } [Fact] public async Task StripManagementPrefix_NoPrefix_Unchanged() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Path] = "/connect/token"; await HttpIdentityProcessors.StripManagementPrefix(exchange, CancellationToken.None); exchange.In.GetHeader(HttpHeaders.Path).Should().Be("/connect/token"); } // ── Helper ── private static IExchange CreateExchange() => new Exchange(new Message()); } Path: redb-identity/tests/redb.Identity.Tests/Http/InboundSetCookieTests.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/Http/InboundSetCookieTests.cs ---- using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Http; /// /// A Set-Cookie the caller puts on its request never comes back in the response. /// /// The HTTP consumer copies every request header into the exchange, and Identity's routes answer on the /// same message. The consumer refuses to echo a request header, but since it learned to tell a value the /// client sent from one the route wrote (it compares the very object it placed there), it only refuses the /// untouched value. Identity's cookie writers add to whatever Set-Cookie is already on the /// message — which, on a login answered on the request message, was the caller's own. The new array held /// the caller's cookie and ours, it was no longer the object the client sent, and both lines went out. /// A browser cannot send Set-Cookie on a request (a forbidden header name), so this only ever /// reached the caller itself; it is still a value the server must not repeat. The name is stripped on /// ingress with the other names a caller must never supply. /// /// [Collection("ProductionHttp")] public sealed class InboundSetCookieTests { private readonly ProductionHttpFixture _fx; public InboundSetCookieTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task A_set_cookie_sent_by_the_caller_is_never_returned_to_it() { using var http = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = false }) { BaseAddress = new Uri(_fx.BaseUrl), }; using var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, "/login") { Content = new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, }), }; request.Headers.TryAddWithoutValidation("Set-Cookie", "injected=from-the-caller; Path=/") .Should().BeTrue("the test needs the header on the request to prove it does not come back"); using var response = await http.SendAsync(request); var lines = response.Headers.TryGetValues("Set-Cookie", out var values) ? values.ToList() : new List(); lines.Should().Contain(l => l.Contains("redb.identity.session"), "the login must still issue its session cookie — otherwise this test would prove nothing"); lines.Should().NotContain(l => l.Contains("injected"), "a value the caller sent is not the server's to repeat, least of all as a cookie"); } } Path: redb-identity/tests/redb.Identity.Tests/Http/LoginPageProcessorsTests.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/Http/LoginPageProcessorsTests.cs ---- using System.Net; using AwesomeAssertions; using redb.Identity.Http.Processors; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using Xunit; namespace redb.Identity.Tests.Http; public class LoginPageProcessorsTests { [Fact] public async Task RenderLoginPage_RendersHtml() { var exchange = CreateExchange(); await LoginPageProcessors.RenderLoginPage(exchange, CancellationToken.None); exchange.Out.Should().NotBeNull(); var body = exchange.Out!.Body as string; body.Should().NotBeNull(); body.Should().Contain("Sign In"); body.Should().Contain("(HttpHeaders.ResponseContentType).Should().Contain("text/html"); exchange.Out.GetHeader(HttpHeaders.ResponseCode).Should().Be(200); } [Fact] public async Task RenderLoginPage_PreservesReturnUrl() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Query] = "returnUrl=%2Fconnect%2Fauthorize%3Fclient_id%3Dapp"; await LoginPageProcessors.RenderLoginPage(exchange, CancellationToken.None); var body = exchange.Out!.Body as string; body.Should().Contain("/connect/authorize?client_id=app"); } [Fact] public async Task RenderLoginPage_HtmlEncodesReturnUrl() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Query] = "returnUrl=%3Cscript%3Ealert(1)%3C%2Fscript%3E"; await LoginPageProcessors.RenderLoginPage(exchange, CancellationToken.None); var body = exchange.Out!.Body as string; body.Should().NotContain(""); body.Should().Contain("<script>"); } [Fact] public async Task HandleLoginResponse_SuccessWithReturnUrl_Redirects() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["returnUrl"] = "/connect/authorize?client_id=app" }; await LoginPageProcessors.HandleLoginResponse(exchange, CancellationToken.None); exchange.Out.GetHeader(HttpHeaders.ResponseCode).Should().Be(302); exchange.Out.GetHeader("Location").Should().Be("/connect/authorize?client_id=app"); } [Fact] public async Task HandleLoginResponse_SuccessNoReturnUrl_ReturnsJson() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = true }; await LoginPageProcessors.HandleLoginResponse(exchange, CancellationToken.None); var body = exchange.Out.Body as Dictionary; body.Should().NotBeNull(); body!["message"].Should().Be("Login successful"); } [Fact] public async Task HandleLoginResponse_OpenRedirect_Blocked() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["returnUrl"] = "//evil.com/phish" }; await LoginPageProcessors.HandleLoginResponse(exchange, CancellationToken.None); // Should NOT redirect — treated as open redirect var body = exchange.Out.Body as Dictionary; body.Should().NotBeNull(); body!["message"].Should().Be("Login successful"); } [Fact] public async Task HandleLoginResponse_AbsoluteUrl_Blocked() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["returnUrl"] = "https://evil.com" }; await LoginPageProcessors.HandleLoginResponse(exchange, CancellationToken.None); // Should NOT redirect — absolute URL var body = exchange.Out.Body as Dictionary; body.Should().NotBeNull(); } [Fact] public async Task HandleLoginResponse_BackslashRedirect_Blocked() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["returnUrl"] = "/\\evil.com" }; await LoginPageProcessors.HandleLoginResponse(exchange, CancellationToken.None); // Should NOT redirect — /\ is open redirect vector var body = exchange.Out.Body as Dictionary; body.Should().NotBeNull(); } [Fact] public async Task HandleLoginResponse_Failure_RendersFormWithError() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = false, ["error_description"] = "Invalid username or password" }; await LoginPageProcessors.HandleLoginResponse(exchange, CancellationToken.None); var body = exchange.Out.Body as string; body.Should().NotBeNull(); body.Should().Contain("Invalid username or password"); body.Should().Contain("Sign In"); } private static IExchange CreateExchange() => new Exchange(new Message()); } Path: redb-identity/tests/redb.Identity.Tests/Http/ManagementStatusPreservationTests.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/Http/ManagementStatusPreservationTests.cs ---- using System.Net.Http.Headers; using System.Text; using AwesomeAssertions; using Grpc.Core; using redb.Identity.Grpc.Processors; using redb.Identity.Http.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using redb.Route.Grpc; using RouteHttpHeaders = redb.Route.Http.HttpHeaders; using Xunit; namespace redb.Identity.Tests.Http; /// /// A status the dispatcher already decided survives the management error table. /// /// The table in ManagementErrorCodes exists because controllers report failure as an error /// document wrapped in a 200. The facades read that document and pick the status. They also read it when /// the controller dispatcher had written a verdict of its own — NotFound 404 for a path no action /// matches, InternalError 500 for an action that threw — and since neither string is in the table, /// both came out as 400. A missing route told the caller their request was malformed; an exception in our /// own code reached them as their fault, which is exactly how a disabled feature once showed up as a 400 /// while the log held an unhandled exception. On gRPC the same path produced INVALID_ARGUMENT. /// /// [Collection("ProductionHttp")] public sealed class ManagementStatusPreservationTests { private readonly ProductionHttpFixture _fx; public ManagementStatusPreservationTests(ProductionHttpFixture fx) => _fx = fx; private static byte[] Json(string json) => Encoding.UTF8.GetBytes(json); private static readonly byte[] DispatcherNotFound = Json("""{"error":"NotFound","message":"No action matches GET /no-such-resource","statusCode":404}"""); private static readonly byte[] DispatcherInternalError = Json("""{"error":"InternalError","message":"An unexpected error occurred","statusCode":500}"""); /// The status a response leaves with: the mapper's Out if it made one, else what it was handed. private static int EffectiveHttpStatus(IExchange e) { var source = e.HasOut && e.Out!.Headers.ContainsKey(RouteHttpHeaders.ResponseCode) ? e.Out! : e.In; return Convert.ToInt32(source.Headers[RouteHttpHeaders.ResponseCode]); } // ── Through the real HTTP pipeline ────────────────────────────────────────────────── [Fact] public async Task An_unknown_management_path_answers_404() { using var req = new HttpRequestMessage(System.Net.Http.HttpMethod.Get, "/api/v1/identity/no-such-resource"); req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); var resp = await _fx.Http.SendAsync(req); ((int)resp.StatusCode).Should().Be(404, "the dispatcher found no action for the path and said so; the error table must not turn " + "\"no such endpoint\" into \"your request is malformed\""); } // ── HTTP facade mapper ────────────────────────────────────────────────────────────── [Fact] public async Task Http_keeps_the_dispatchers_404() { IExchange e = new TestExchange(); e.In.Body = DispatcherNotFound; e.In.Headers[RouteHttpHeaders.ResponseCode] = 404; e.In.Headers["status.code"] = 404; await HttpIdentityProcessors.MapManagementErrorToHttpStatus(e, CancellationToken.None); EffectiveHttpStatus(e).Should().Be(404); } [Fact] public async Task Http_keeps_the_dispatchers_500() { IExchange e = new TestExchange(); e.In.Body = DispatcherInternalError; e.In.Headers[RouteHttpHeaders.ResponseCode] = 500; e.In.Headers["status.code"] = 500; await HttpIdentityProcessors.MapManagementErrorToHttpStatus(e, CancellationToken.None); EffectiveHttpStatus(e).Should().Be(500, "an action that threw is our failure; reporting it as 400 blames the caller for it"); } [Theory] [InlineData("not_found", 404)] [InlineData("duplicate", 409)] [InlineData("weak_password", 400)] public async Task Http_still_maps_a_controller_error_document_wrapped_in_200(string error, int expected) { IExchange e = new TestExchange(); e.In.Body = Json($$"""{"error":"{{error}}","error_description":"from the controller"}"""); e.In.Headers[RouteHttpHeaders.ResponseCode] = 200; e.In.Headers["status.code"] = 200; await HttpIdentityProcessors.MapManagementErrorToHttpStatus(e, CancellationToken.None); EffectiveHttpStatus(e).Should().Be(expected, "this is the case the table exists for, and it must keep working"); } // ── gRPC facade mapper ────────────────────────────────────────────────────────────── private static int GrpcStatusOf(IExchange e) { var target = e.HasOut ? e.Out! : e.In; return Convert.ToInt32(target.Headers[GrpcHeaders.StatusCode]); } [Fact] public async Task Grpc_answers_not_found_for_the_dispatchers_404() { // The gRPC dispatcher writes only status.code, never redbHttp.ResponseCode. IExchange e = new TestExchange(); e.In.Body = DispatcherNotFound; e.In.Headers["status.code"] = 404; await GrpcManagementProcessors.MapControllerErrorToGrpcStatus(e, CancellationToken.None); GrpcStatusOf(e).Should().Be((int)StatusCode.NotFound); } [Fact] public async Task Grpc_answers_internal_for_the_dispatchers_500() { IExchange e = new TestExchange(); e.In.Body = DispatcherInternalError; e.In.Headers["status.code"] = 500; await GrpcManagementProcessors.MapControllerErrorToGrpcStatus(e, CancellationToken.None); GrpcStatusOf(e).Should().Be((int)StatusCode.Internal, "INVALID_ARGUMENT would tell the caller to change a request that was never the problem"); } [Fact] public async Task Grpc_still_maps_a_controller_error_document_wrapped_in_200() { IExchange e = new TestExchange(); e.In.Body = Json("""{"error":"not_found","error_description":"from the controller"}"""); e.In.Headers["status.code"] = 200; await GrpcManagementProcessors.MapControllerErrorToGrpcStatus(e, CancellationToken.None); GrpcStatusOf(e).Should().Be((int)StatusCode.NotFound); } } Path: redb-identity/tests/redb.Identity.Tests/Http/SessionCookieProcessorsTests.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/Http/SessionCookieProcessorsTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using redb.Identity.Core.Configuration; using redb.Identity.Http.Security; using redb.Identity.Http.Processors; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; using Xunit; using redb.Identity.Contracts.Configuration; namespace redb.Identity.Tests.Http; public class SessionCookieProcessorsTests { private readonly SessionTicketService _ticketService; private readonly TimeSpan _maxAge = TimeSpan.FromHours(8); public SessionCookieProcessorsTests() { var provider = new EphemeralDataProtectionProvider(); _ticketService = new SessionTicketService(provider); } // ── ReadSessionCookie ── [Fact] public async Task ReadSessionCookie_ValidCookie_SetsHeaders() { var ticket = _ticketService.Protect(42, 100, "admin"); var exchange = CreateExchange(); exchange.In.Headers["Cookie"] = $"redb.identity.session={ticket}"; await SessionCookieProcessors.ReadSessionCookie(exchange, CancellationToken.None, _ticketService, _maxAge, SessionCookieProcessors.DefaultCookieName); exchange.In.GetHeader("session_user_id").Should().Be(42); exchange.In.GetHeader("session_username").Should().Be("admin"); exchange.In.GetHeader("session_id").Should().Be(100); } [Fact] public async Task ReadSessionCookie_NoCookie_NoHeaders() { var exchange = CreateExchange(); await SessionCookieProcessors.ReadSessionCookie(exchange, CancellationToken.None, _ticketService, _maxAge, SessionCookieProcessors.DefaultCookieName); exchange.In.Headers.ContainsKey("session_user_id").Should().BeFalse(); } [Fact] public async Task ReadSessionCookie_InvalidTicket_NoHeaders() { var exchange = CreateExchange(); exchange.In.Headers["Cookie"] = "redb.identity.session=garbage-value"; await SessionCookieProcessors.ReadSessionCookie(exchange, CancellationToken.None, _ticketService, _maxAge, SessionCookieProcessors.DefaultCookieName); exchange.In.Headers.ContainsKey("session_user_id").Should().BeFalse(); } [Fact] public async Task ReadSessionCookie_MultipleCookies_FindsCorrectOne() { var ticket = _ticketService.Protect(7, 50, "user"); var exchange = CreateExchange(); exchange.In.Headers["Cookie"] = $"other=value; redb.identity.session={ticket}; another=x"; await SessionCookieProcessors.ReadSessionCookie(exchange, CancellationToken.None, _ticketService, _maxAge, SessionCookieProcessors.DefaultCookieName); exchange.In.GetHeader("session_user_id").Should().Be(7); } // ── WriteSessionCookie ── [Fact] public async Task WriteSessionCookie_SuccessfulLogin_SetsCookie() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["userId"] = 42L, ["username"] = "admin" }; await SessionCookieProcessors.WriteSessionCookie(exchange, CancellationToken.None, _ticketService, _maxAge, secure: true, SessionCookieProcessors.DefaultCookieName, CookieSameSiteMode.Lax, useHostPrefix: false); var setCookie = exchange.Out.GetHeader("Set-Cookie"); setCookie.Should().NotBeNull(); setCookie.Should().StartWith("redb.identity.session="); setCookie.Should().Contain("HttpOnly"); setCookie.Should().Contain("Secure"); setCookie.Should().Contain("SameSite=Lax"); } [Fact] public async Task WriteSessionCookie_FailedLogin_NoCookie() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = false, ["error"] = "access_denied" }; await SessionCookieProcessors.WriteSessionCookie(exchange, CancellationToken.None, _ticketService, _maxAge, secure: true, SessionCookieProcessors.DefaultCookieName, CookieSameSiteMode.Lax, useHostPrefix: false); exchange.Out.Headers.ContainsKey("Set-Cookie").Should().BeFalse(); } // ── ClearSessionCookie ── [Fact] public async Task ClearSessionCookie_SetsMaxAgeZero() { var exchange = CreateExchange(); exchange.Out = new Message(); await SessionCookieProcessors.ClearSessionCookie(exchange, CancellationToken.None, secure: true, SessionCookieProcessors.DefaultCookieName, CookieSameSiteMode.Lax, useHostPrefix: false); var setCookie = exchange.Out.GetHeader("Set-Cookie"); setCookie.Should().Contain("Max-Age=0"); setCookie.Should().Contain("redb.identity.session="); } // ── RedirectToLogin ── [Fact] public async Task RedirectToLogin_LoginRequired_Redirects() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Query] = "client_id=app&response_type=code"; exchange.In.Headers[HttpHeaders.Path] = "/connect/authorize"; exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["error"] = "login_required" }; await SessionCookieProcessors.RedirectToLogin(exchange, CancellationToken.None, "/login"); exchange.Out.GetHeader(HttpHeaders.ResponseCode).Should().Be(302); var location = exchange.Out.GetHeader("Location"); location.Should().StartWith("/login?returnUrl="); location.Should().Contain("connect%2Fauthorize"); } [Fact] public async Task RedirectToLogin_NotLoginRequired_NoChange() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["code"] = "abc123" }; await SessionCookieProcessors.RedirectToLogin(exchange, CancellationToken.None, "/login"); exchange.Out.Headers.ContainsKey(HttpHeaders.ResponseCode).Should().BeFalse(); } [Fact] public async Task WriteSessionCookie_WithSessionId_EncodesInTicket() { var exchange = CreateExchange(); exchange.Out = new Message(); exchange.Out.Body = new Dictionary { ["success"] = true, ["userId"] = 42L, ["username"] = "admin", ["sessionId"] = 100L }; await SessionCookieProcessors.WriteSessionCookie(exchange, CancellationToken.None, _ticketService, _maxAge, secure: true, SessionCookieProcessors.DefaultCookieName, CookieSameSiteMode.Lax, useHostPrefix: false); var setCookie = exchange.Out.GetHeader("Set-Cookie"); setCookie.Should().NotBeNull(); // Extract ticket value and verify it roundtrips with sessionId var ticketValue = setCookie!.Split('=', 2)[1].Split(';')[0]; var ticket = _ticketService.Unprotect(ticketValue, _maxAge); ticket.Should().NotBeNull(); ticket!.SessionId.Should().Be(100); } [Fact] public async Task RedirectToLogin_GetRequest_ReturnUrlIsThePathAndQuery() { var exchange = LoginRequiredExchange(); exchange.In.Headers[HttpHeaders.Query] = "client_id=app&response_type=code"; await SessionCookieProcessors.RedirectToLogin(exchange, CancellationToken.None, "/login"); ReturnUrl(exchange).Should().Be("/connect/authorize?client_id=app&response_type=code"); } [Fact] public async Task RedirectToLogin_PostRequestWithoutSession_ReturnUrlCarriesTheForm() { // OIDC Core 3.1.2.1: the authorization request may come as a form POST. Up to 4.5 the // return trip was rebuilt from the (empty) query string, so after login the browser came // back to /connect/authorize without client_id. var form = new Dictionary { ["client_id"] = "app", ["response_type"] = "code", ["scope"] = "openid profile", ["redirect_uri"] = "https://rp.example/cb?dummy1=lorem&dummy2=ipsum", ["state"] = "s+1/2=3", }; var exchange = await PostedAuthorizeExchange(form); await SessionCookieProcessors.RedirectToLogin(exchange, CancellationToken.None, "/login"); var returnUrl = ReturnUrl(exchange); returnUrl.Should().StartWith("/connect/authorize?"); ParseQuery(returnUrl).Should().BeEquivalentTo(form.ToDictionary(kv => kv.Key, kv => (string)kv.Value!)); } [Fact] public async Task RedirectToLogin_PostedPushedRequest_KeepsClientIdAndRequestUriVerbatim() { const string requestUri = "urn:ietf:params:oauth:request_uri:6esc_11ACC5bwc014ltc14eY22c"; var exchange = await PostedAuthorizeExchange(new Dictionary { ["client_id"] = "app", ["request_uri"] = requestUri, }); await SessionCookieProcessors.RedirectToLogin(exchange, CancellationToken.None, "/login"); ReturnUrl(exchange).Should().Be("/connect/authorize?client_id=app&request_uri=" + Uri.EscapeDataString(requestUri)); } [Fact] public async Task RedirectToConsent_PostRequest_TicketReturnUrlCarriesTheForm() { var exchange = BuildConsentRequiredExchange(delegateHeader: null); exchange.In.Headers.Remove("redbHttp.Query"); exchange.In.Body = new Dictionary { ["client_id"] = "demo-client", ["scope"] = "openid profile" }; await SessionCookieProcessors.CaptureAuthorizeForm(exchange, CancellationToken.None); exchange.In.Body = new Dictionary { ["error"] = "consent_required" }; await SessionCookieProcessors.RedirectToConsent(exchange, CancellationToken.None, "/consent", _ticketService); var location = exchange.In.GetHeader("Location")!; var ticket = _ticketService.UnprotectConsent(Uri.UnescapeDataString(location["/consent?ct=".Length..]), TimeSpan.FromMinutes(10)); ticket!.ReturnUrl.Should().Be("/connect/authorize?client_id=demo-client&scope=openid%20profile"); } private static IExchange LoginRequiredExchange() { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Path] = "/connect/authorize"; exchange.Out = new Message { Body = new Dictionary { ["error"] = "login_required" } }; return exchange; } // The POST route as the facade runs it: MapFormToBody leaves the form on In.Body, // CaptureAuthorizeForm keeps it, then the authorize response replaces the body. private static async Task PostedAuthorizeExchange(Dictionary form) { var exchange = CreateExchange(); exchange.In.Headers[HttpHeaders.Path] = "/connect/authorize"; exchange.In.Body = form; await SessionCookieProcessors.CaptureAuthorizeForm(exchange, CancellationToken.None); exchange.In.Body = null; exchange.Out = new Message { Body = new Dictionary { ["error"] = "login_required" } }; return exchange; } private static string ReturnUrl(IExchange exchange) { exchange.Out!.GetHeader(HttpHeaders.ResponseCode).Should().Be(302); var location = exchange.Out.GetHeader("Location")!; location.Should().StartWith("/login?returnUrl="); return Uri.UnescapeDataString(location["/login?returnUrl=".Length..]); } private static Dictionary ParseQuery(string url) => url[(url.IndexOf('?') + 1)..].Split('&') .Select(p => p.Split('=', 2)) .ToDictionary(p => Uri.UnescapeDataString(p[0]), p => Uri.UnescapeDataString(p[1])); // ── RedirectToConsent (N-2 native BFF consent) ── [Fact] public async Task RedirectToConsent_NoDelegateHeader_Returns302() { var exchange = BuildConsentRequiredExchange(delegateHeader: null); await SessionCookieProcessors.RedirectToConsent(exchange, CancellationToken.None, "/consent", _ticketService); exchange.In.GetHeader("redbHttp.ResponseCode").Should().Be(302); var location = exchange.In.GetHeader("Location"); location.Should().NotBeNull(); // Consent parameters travel in a signed ticket, never as query fields the browser can craft. location!.Should().StartWith("/consent?ct="); location.Should().NotContain("client_id=").And.NotContain("app_name="); var ticketValue = Uri.UnescapeDataString(location!["/consent?ct=".Length..]); var ticket = _ticketService.UnprotectConsent(ticketValue, TimeSpan.FromMinutes(10)); ticket.Should().NotBeNull(); ticket!.ClientId.Should().Be("demo-client"); ticket.AppName.Should().Be("Demo App"); ticket.Scopes.Should().Be("openid profile"); ticket.UserId.Should().Be(42); ticket.ReturnUrl.Should().Be("/connect/authorize?client_id=demo-client"); } [Fact] public async Task RedirectToConsent_DelegateHeader_ReturnsJson400() { var exchange = BuildConsentRequiredExchange(delegateHeader: "1"); await SessionCookieProcessors.RedirectToConsent(exchange, CancellationToken.None, "/consent", _ticketService); exchange.In.GetHeader("redbHttp.ResponseCode").Should().Be(400); exchange.In.GetHeader("Content-Type").Should().Contain("application/json"); var body = exchange.In.Body as IDictionary; body.Should().NotBeNull(); body!["error"].Should().Be("consent_required"); body["clientId"].Should().Be("demo-client"); body["appName"].Should().Be("Demo App"); body["scopes"].Should().BeOfType() .Which.Should().Equal("openid", "profile"); body["userId"].Should().Be("42"); body["returnUrl"].Should().Be("/connect/authorize?client_id=demo-client"); } [Fact] public async Task RedirectToConsent_DelegateHeader_TrueLiteral_ReturnsJson400() { var exchange = BuildConsentRequiredExchange(delegateHeader: "True"); await SessionCookieProcessors.RedirectToConsent(exchange, CancellationToken.None, "/consent", _ticketService); exchange.In.GetHeader("redbHttp.ResponseCode").Should().Be(400); } private static Exchange BuildConsentRequiredExchange(string? delegateHeader) { var ex = new Exchange(new Message { Body = new Dictionary { ["error"] = "consent_required" }, }); ex.In.Headers["redbHttp.Path"] = "/connect/authorize"; ex.In.Headers["redbHttp.Query"] = "client_id=demo-client"; if (delegateHeader is not null) ex.In.Headers["X-Identity-Delegate-Consent"] = delegateHeader; ex.Properties["consent_client_id"] = "demo-client"; ex.Properties["consent_app_name"] = "Demo App"; ex.Properties["consent_scopes"] = "openid profile"; ex.Properties["consent_user_id"] = "42"; return ex; } private static IExchange CreateExchange() => new Exchange(new Message()); } Path: redb-identity/tests/redb.Identity.Tests/Http/SetCookieFoldingTests.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/Http/SetCookieFoldingTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using redb.Identity.Contracts.Configuration; using redb.Identity.Http.Processors; using redb.Identity.Http.Security; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Http; /// /// Two cookies in one response leave as two Set-Cookie lines, never folded into one. /// /// The federation callback answers with the new session cookie and with the expiry of the per-flow /// binding cookie. It joined them into one header value with ", ". A browser does not split /// Set-Cookie on commas (RFC 6265 §3: origin servers SHOULD NOT fold): everything after the first /// ; is read as attributes of the first cookie, and of several Max-Age attributes the /// last one wins (§5.3 step 3). The folded value ends in the binding cookie's Max-Age=0 — so the /// browser deleted the fresh session cookie the moment it arrived, and never cleared the binding cookie /// either. The HTTP consumer already writes an array value as one header line per entry; the fix is to /// hand it an array. /// /// /// The session-cookie writers had the neighbouring defect in latent form: each assigned the header, so a /// second cookie on the same response would silently replace the first. No route pairs two of them /// today, which is why that part is pinned rather than reported. /// /// public sealed class SetCookieFoldingTests { private const string BindingCookie = "redb_fed_b"; private static string SessionCookie() => IdentityCookieFormatter.Build( "redb.identity.session", "TICKET", maxAgeSeconds: 28800, secure: true, sameSite: CookieSameSiteMode.Lax, useHostPrefix: false); /// The header value as the separate lines the consumer will write. private static string[] Lines(object? value) => value switch { string s => new[] { s }, string[] a => a, _ => throw new InvalidOperationException($"Set-Cookie of unexpected shape: {value?.GetType().Name ?? "null"}"), }; /// A line read the way RFC 6265 §5.2-5.3 reads it: name, and the last Max-Age wins. private static (string Name, int? MaxAge) AsBrowserReadsIt(string line) { var parts = line.Split(';'); var name = parts[0].Split('=', 2)[0].Trim(); int? maxAge = null; foreach (var attribute in parts.Skip(1)) { var kv = attribute.Split('=', 2); if (kv.Length == 2 && kv[0].Trim().Equals("Max-Age", StringComparison.OrdinalIgnoreCase) && int.TryParse(kv[1].Trim(), out var seconds)) { maxAge = seconds; } } return (name, maxAge); } [Theory] [InlineData("/account")] // success with a return address: redirect [InlineData(null)] // success without one: the success page public async Task Federation_success_keeps_the_session_cookie_alive_and_clears_the_binding_cookie(string? returnUrl) { IExchange e = new TestExchange(); e.In.Body = new Dictionary { ["success"] = true, ["returnUrl"] = returnUrl }; e.In.Headers["Set-Cookie"] = SessionCookie(); // set upstream by the session-cookie writer e.Properties["federation-binding-secure"] = true; await FederationHttpProcessors.HandleCallbackResponse(e, CancellationToken.None, BindingCookie); var lines = Lines(e.Out!.Headers["Set-Cookie"]).Select(AsBrowserReadsIt).ToList(); lines.Should().ContainSingle(l => l.Name == "redb.identity.session") .Which.MaxAge.Should().Be(28800, "folded into one line, the binding cookie's Max-Age=0 becomes the session cookie's last Max-Age " + "and the browser deletes the session the moment it is set"); lines.Should().ContainSingle(l => l.Name == BindingCookie, "the binding cookie's expiry has to be a cookie of its own, or the browser never sees it") .Which.MaxAge.Should().Be(0); } [Fact] public async Task A_session_writer_adds_its_cookie_instead_of_replacing_one_already_there() { var ticketService = new SessionTicketService(new EphemeralDataProtectionProvider()); IExchange e = new TestExchange(); e.In.Body = new Dictionary { ["success"] = true, ["userId"] = 42L, ["username"] = "alice", ["sessionId"] = 7L, }; e.In.Headers["Set-Cookie"] = IdentityCookieFormatter.Build( "other", "x", maxAgeSeconds: 60, secure: true, sameSite: CookieSameSiteMode.Lax, useHostPrefix: false); await SessionCookieProcessors.WriteSessionCookie(e, CancellationToken.None, ticketService, TimeSpan.FromHours(8), secure: true, bareCookieName: "redb.identity.session", sameSite: CookieSameSiteMode.Lax, useHostPrefix: false); Lines(e.In.Headers["Set-Cookie"]).Select(l => AsBrowserReadsIt(l).Name) .Should().BeEquivalentTo(new[] { "other", "redb.identity.session" }); } [Fact] public async Task A_single_cookie_still_leaves_as_a_plain_string() { // The shape every other consumer of the header already reads; only a second cookie changes it. var ticketService = new SessionTicketService(new EphemeralDataProtectionProvider()); IExchange e = new TestExchange(); e.In.Body = new Dictionary { ["success"] = true, ["userId"] = 42L, ["username"] = "alice", }; await SessionCookieProcessors.WriteSessionCookie(e, CancellationToken.None, ticketService, TimeSpan.FromHours(8), secure: true, bareCookieName: "redb.identity.session", sameSite: CookieSameSiteMode.Lax, useHostPrefix: false); e.In.Headers["Set-Cookie"].Should().BeOfType(); } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/ExternalProviderFixture.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/Infrastructure/ExternalProviderFixture.cs ---- using redb.Identity.Core.Services; namespace redb.Identity.Tests.Infrastructure; /// /// A configurable fake external user provider for integration testing. /// Instantiated per-test (not via DI) and passed directly to LoginService constructor. /// public sealed class FakeExternalUserProvider : IExternalUserProvider { public string ProviderName { get; set; } = "fake-test"; public int Priority { get; set; } = 10; /// /// Map of username → result handler. Return null to skip, non-null to claim the user. /// public Dictionary> UserHandlers { get; } = new(); public Task AuthenticateAsync(string username, string password, CancellationToken ct = default) { if (!UserHandlers.TryGetValue(username, out var handler)) return Task.FromResult(null); return Task.FromResult(handler(password)); } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/FakeFederatedAuthProvider.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/Infrastructure/FakeFederatedAuthProvider.cs ---- using redb.Identity.Core.Services; namespace redb.Identity.Tests.Infrastructure; /// /// A configurable fake federated auth provider for integration testing. /// Allows tests to control challenge and callback behavior without a real OIDC server. /// public sealed class FakeFederatedAuthProvider : IFederatedAuthProvider { public string ProviderId { get; set; } = "fake-oidc"; public string DisplayName { get; set; } = "Fake OIDC Provider"; public int Priority { get; set; } = 10; /// /// Custom challenge handler. If null, returns a default challenge. /// public Func? ChallengeHandler { get; set; } /// /// Custom callback handler. If null, returns success with code-based sub. /// public Func? CallbackHandler { get; set; } public Task CreateChallengeAsync( string callbackUrl, string returnUrl, CancellationToken ct = default) { if (ChallengeHandler is not null) return Task.FromResult(ChallengeHandler(callbackUrl, returnUrl)); var state = Guid.NewGuid().ToString("N"); return Task.FromResult(new FederationChallenge { RedirectUri = $"https://fake-oidc.test/authorize?state={Uri.EscapeDataString(state)}&redirect_uri={Uri.EscapeDataString(callbackUrl)}", State = state, Nonce = Guid.NewGuid().ToString("N"), CodeVerifier = Guid.NewGuid().ToString("N") }); } public Task HandleCallbackAsync( string code, string callbackUrl, string? codeVerifier = null, string? nonce = null, CancellationToken ct = default) { if (CallbackHandler is not null) return Task.FromResult(CallbackHandler(code, codeVerifier, nonce)); return Task.FromResult(ExternalAuthResult.Success( externalId: $"fake-sub-{code}", displayName: $"FakeUser {code}", email: $"fake-{code}@test.com", givenName: "Fake", familyName: "User")); } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/FederationFixture.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/Infrastructure/FederationFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using Xunit; using redb.Identity.Contracts.Configuration; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Infrastructure; /// /// Integration fixture for federation (OIDC redirect-based auth) tests. /// Real PostgreSQL + production DI + federation enabled with . /// public sealed class FederationFixture : IAsyncLifetime { private ServiceProvider _sp = null!; private RouteContext _ctx = null!; public const string TestClientId = "federation-test-client"; public const string TestClientSecret = "federation-test-secret-value"; public const string TestUsername = "fed-testuser"; public const string TestPassword = "FedTest@Password123"; public const string TestRedirectUri = "http://localhost/callback"; public ProducerTemplate Producer { get; private set; } = null!; public IRedbService Redb { get; private set; } = null!; public IServiceProvider ServiceProvider => _sp; public long TestUserId { get; private set; } public FakeFederatedAuthProvider FakeProvider { get; } = new(); public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenRetentionDays = 30, TokenThrottleMaxPerPeriod = 1000, TokenThrottlePeriod = TimeSpan.FromSeconds(1), Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true, EnablePasswordFlow = true, Features = new IdentityFeatureFlags { EnableFederation = true }, FederationProviders = [ // Dummy config entry to satisfy the FederationProviders.Count > 0 guard // The actual IFederatedAuthProvider used in tests is FakeProvider below new FederationProviderConfig { ProviderId = "config-oidc-unused", DisplayName = "Unused Config OIDC", Authority = "http://localhost:19999", ClientId = "unused", ClientSecret = "unused" } ] }; services.AddSingleton(Options.Create(identityOptions)); // Register the fake federated auth provider (used by tests via ProviderId = "fake-oidc") services.AddSingleton(FakeProvider); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); Redb = _sp.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); await IndexFixHelper.FixValueStringIndexAsync(cs); await SeedTestClient(); await SeedTestUser(); _ctx = new RouteContext(_sp, "federation-integration"); _ctx.AddRoutes(new IdentityCoreRouteBuilder(_sp, Options.Create(identityOptions))); await _ctx.Start(); Producer = new ProducerTemplate(_ctx); Producer.Start(); } public async Task DisposeAsync() { Producer.Stop(); Producer.Dispose(); await _ctx.DisposeAsync(); await _sp.DisposeAsync(); } private async Task SeedTestClient() { var manager = _sp.GetRequiredService(); var existing = await manager.FindByClientIdAsync(TestClientId); if (existing is not null) await manager.DeleteAsync(existing); await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = TestClientId, ClientSecret = TestClientSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "Federation Test Client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.GrantTypes.Password, OpenIddictConstants.Permissions.GrantTypes.RefreshToken, OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Email, OpenIddictConstants.Permissions.Prefixes.Scope + "openid", OpenIddictConstants.Permissions.ResponseTypes.Code }, RedirectUris = { new Uri(TestRedirectUri) }, Requirements = { OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange } }); } private async Task SeedTestUser() { var coreUser = await Redb.UserProvider.GetUserByLoginAsync(TestUsername); if (coreUser is null) { coreUser = await Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = TestUsername, Password = TestPassword, Name = TestUsername, Email = "fed-testuser@example.com", Enabled = true }); } TestUserId = coreUser.Id; var oidcObj = await Redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync(); if (oidcObj is null) { oidcObj = new RedbObject(new UserProps()); oidcObj.name = TestUsername; oidcObj.key = coreUser.Id; oidcObj.value_guid = Guid.NewGuid(); } oidcObj.Props.EmailVerified = true; oidcObj.Props.GivenName = "Fed"; oidcObj.Props.FamilyName = "TestUser"; await Redb.SaveAsync(oidcObj); } public async Task Request(string endpointUri, object body) { return await Producer.RequestBody(endpointUri, body); } public async Task RequestWithHeaders( string endpointUri, object? body, IDictionary headers, ManagementCaller caller = ManagementCaller.Admin) { var message = new Message { Body = body }; foreach (var (key, value) in headers) message.Headers[key] = value; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOut }; // This fixture plays the facade: the core management routes refuse an exchange without a // management context, so say which caller we are. Admin unless the test probes the gate. ManagementCallerContext.Apply(exchange, caller); var endpoint = _ctx.GetEndpoint(endpointUri); var producer = endpoint.CreateProducer(); await producer.Process(exchange); // Identity convention: business processors write the response into exchange.In.Body // and PipelineProcessor (Camel-compliant) does not synthesise Out from In. Tests // historically read exchange.Out?.Body directly, so normalise Out := copy-of-In here. NormalizeOutFromIn(exchange); return exchange; } private static void NormalizeOutFromIn(Exchange exchange) { if (exchange.Out is not null) return; var inMsg = exchange.In; if (inMsg is null) return; var outMsg = new Message { Body = inMsg.Body, ContentType = inMsg.ContentType }; foreach (var (k, v) in inMsg.Headers) outMsg.Headers[k] = v; exchange.Out = outMsg; } } [CollectionDefinition("Federation")] public class FederationCollection : ICollectionFixture; Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/GrpcIdentityFixture.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/Infrastructure/GrpcIdentityFixture.cs ---- using System.Net; using System.Net.Sockets; using Google.Protobuf; using Grpc.Core; using GrpcMetadata = Grpc.Core.Metadata; using Grpc.Net.Client; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using redb.Identity.Core.Routes.Processors; using OpenIddict.Validation; using redb.Core; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Routes; using redb.Identity.Grpc; using redb.Route.Components; using redb.Route.Core; using redb.Route.Grpc; using Xunit; namespace redb.Identity.Tests.Infrastructure; /// /// Boots redb.Identity.Core plus the gRPC facade in one process against the real PostgreSQL store, with /// the production OpenIddict pipeline and a real client registry — not degraded mode. That matters: /// a degraded fixture skips client validation and keeps no token store, so it can neither refuse a wrong /// secret nor make a revoked token go inactive, and a test claiming either would be theatre. /// /// Calls go through raw byte marshallers rather than generated client stubs on purpose: the published /// contract compiles to messages only (GrpcServices="None"), and exercising it this way proves the /// wire contract itself instead of a convenience wrapper we also wrote. /// /// public class GrpcIdentityFixture : IAsyncLifetime { /// /// Last word on the server options, for fixtures that need a stack tuned differently. The base /// settings are deliberately permissive so that ordinary tests never trip a limiter by accident. /// protected virtual void Tune(RedbIdentityOptions options) { } /// /// Bind address. Loopback keeps the ordinary fixtures off every other interface on the machine; the /// interop fixture widens it because a client inside a container reaches the host through /// host.docker.internal, and a loopback-only listener is invisible from there. /// protected virtual string BindHost => "127.0.0.1"; /// /// Management port. Null means «share the public one», which is the single-node default and the only /// branch the ordinary fixtures exercise. takes the other /// branch, because a production deployment is expected to firewall the admin surface separately and /// an untried split is not a supported configuration. /// protected virtual int? ManagementPort => null; /// /// Whether Core gets a management authentication processor. False leaves /// direct-vm://identity-auth-management unregistered — a deployment mistake, and the one whose /// consequences must be checked rather than assumed. See . /// protected virtual bool RegisterManagementAuth => true; /// Where the admin surface actually listens, whichever branch this fixture took. public int EffectiveManagementPort { get; private set; } public const string ClientId = "grpc-e2e-client"; public const string ClientSecret = "grpc-e2e-secret"; public const string GrantedScope = "identity:manage"; /// /// A second client, permitted exactly one narrow scope. Without it "a narrow token is refused" cannot /// be asserted at all — the master-scope client passes every gate by design. /// public const string NarrowClientId = "grpc-e2e-narrow"; public const string NarrowClientSecret = "grpc-e2e-narrow-secret"; public const string NarrowScope = "identity:users:read"; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; private GrpcChannel _channel = null!; private GrpcChannel _managementChannel = null!; public int Port { get; private set; } public IRedbService Redb { get; private set; } = null!; public IServiceProvider ServiceProvider => _sp; public async Task InitializeAsync() { Port = GetFreePort(); var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var cs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenRetentionDays = 30, TokenThrottleMaxPerPeriod = 1000, TokenThrottlePeriod = TimeSpan.FromSeconds(1), Issuer = new Uri($"http://localhost:{Port}/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true, }; Tune(identityOptions); services.AddSingleton(Options.Create(identityOptions)); var transportOptions = new IdentityGrpcTransportOptions { // One shared instance, the same invariant the HTTP fixture keeps: issuer and feature flags // come from a single section rather than being mirrored property by property. Shared = identityOptions.Shared, }; transportOptions.Grpc.Host = BindHost; transportOptions.Grpc.PublicPort = Port; transportOptions.Grpc.ManagementPort = ManagementPort; EffectiveManagementPort = transportOptions.Grpc.EffectiveManagementPort; services.AddSingleton(Options.Create(transportOptions)); // Production bootstrap: real OpenIddict stores and pipeline, real client validation. services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); Redb = _sp.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); await SeedClient(); await SeedNarrowClient(); _ctx = new RouteContext(_sp, "identity-grpc-e2e"); _ctx.AddComponent(new GrpcComponent()); // The real bearer-auth processor, built exactly as the HTTP fixture builds it. Passing null here // would leave direct-vm://identity-auth-management unregistered, and a management route calling an // address that is not there fails open — the one direction an authentication gate must never fail. redb.Route.Abstractions.IProcessor? managementAuth = RegisterManagementAuth ? new ManagementBearerAuthProcessor( _sp.GetRequiredService(), new[] { identityOptions.ManagementScope, identityOptions.AccountScope, NarrowScope }) : null; _ctx.AddRoutes(new IdentityCoreRouteBuilder(_sp, Options.Create(identityOptions), auditOptions: null, managementAuth: managementAuth, scimAuth: null)); _ctx.AddRoutes(new GrpcFacadeRouteBuilder(Options.Create(transportOptions))); _ctx.AddRoutes(new GrpcManagementRouteBuilder(Options.Create(transportOptions))); await _ctx.Start(); _channel = GrpcChannel.ForAddress($"http://127.0.0.1:{Port}"); _managementChannel = EffectiveManagementPort == Port ? _channel : GrpcChannel.ForAddress($"http://127.0.0.1:{EffectiveManagementPort}"); } /// /// Registers the confidential client the tests authenticate as. The manager hashes the secret, which /// is what makes "a wrong secret is refused" a real assertion rather than a formality. /// private async Task SeedClient() { var manager = _sp.GetRequiredService(); var existing = await manager.FindByClientIdAsync(ClientId); if (existing is not null) await manager.DeleteAsync(existing); await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = ClientId, ClientSecret = ClientSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "gRPC E2E client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Introspection, OpenIddictConstants.Permissions.Endpoints.Revocation, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.Prefixes.Scope + GrantedScope, }, }); } /// /// Registers the narrow-scope client. It may read users and nothing else — which is what makes /// "a token that may read is refused a write" an assertion rather than a formality. /// private async Task SeedNarrowClient() { var manager = _sp.GetRequiredService(); var existing = await manager.FindByClientIdAsync(NarrowClientId); if (existing is not null) await manager.DeleteAsync(existing); await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = NarrowClientId, ClientSecret = NarrowClientSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "gRPC E2E narrow-scope client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.Prefixes.Scope + NarrowScope, }, }); } public async Task DisposeAsync() { if (!ReferenceEquals(_managementChannel, _channel)) _managementChannel.Dispose(); _channel.Dispose(); await _ctx.DisposeAsync(); await _sp.DisposeAsync(); } /// Calls a typed operation of the published contract. public async Task CallAsync( string method, TRequest request, MessageParser parser, GrpcMetadata? metadata = null) where TRequest : IMessage where TResponse : IMessage { var reply = await CallRawAsync($"/identity.v1.Identity/{method}", request.ToByteArray(), metadata); return parser.ParseFrom(reply); } /// Calls any method address with raw bytes — used by the envelope path and negative tests. public Task CallRawAsync(string methodPath, byte[] payload, GrpcMetadata? metadata = null) => InvokeAsync(_channel, methodPath, payload, metadata); /// /// Calls the admin surface on whichever port it actually listens on. Management tests go through this /// rather than so that they keep working — and keep meaning something — /// when the two ports are split. /// public Task CallManagementRawAsync(string methodPath, byte[] payload, GrpcMetadata? metadata = null) => InvokeAsync(_managementChannel, methodPath, payload, metadata); private static async Task InvokeAsync( GrpcChannel channel, string methodPath, byte[] payload, GrpcMetadata? metadata) { var slash = methodPath.LastIndexOf('/'); var marshaller = Marshallers.Create(b => (byte[])b, b => b); var descriptor = new Method( MethodType.Unary, methodPath[1..slash], methodPath[(slash + 1)..], marshaller, marshaller); var options = metadata is null ? new CallOptions() : new CallOptions(metadata); return await channel.CreateCallInvoker().AsyncUnaryCall(descriptor, null, options, payload); } private static int GetFreePort() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } } /// /// The same stack with the per-IP token throttle turned down to a level a test can actually reach. Its own /// fixture rather than a knob on the shared one: the limit is read once at boot, and a stack that starts /// throttled would make every other test in the suite race the bucket. /// public sealed class GrpcThrottledIdentityFixture : GrpcIdentityFixture { /// Requests one IP may make per minute before Core answers 429. public const int PerIpPerMinute = 3; protected override void Tune(RedbIdentityOptions options) { // C1, the per-IP limiter. It reads redbHttp.RemoteAddress, which over gRPC exists only because // the listener is built with EmitHttpCompatHeaders - so this fixture is what proves that bridge // carries a real protection rather than a header nobody reads. options.RateLimit.Enabled = true; options.RateLimit.PerIpPerMinute = PerIpPerMinute; } } /// /// The same stack, reachable from a container. Used by the interop test that drives an independent /// @grpc/grpc-js client generated from the published identity.v1.proto. /// public sealed class GrpcInteropIdentityFixture : GrpcIdentityFixture { protected override string BindHost => "0.0.0.0"; } /// /// The same stack with the admin surface on a port of its own — the production shape, and the branch of /// EffectiveManagementPort that no other fixture reaches. /// public sealed class GrpcSplitPortIdentityFixture : GrpcIdentityFixture { private readonly int _managementPort = FreePort(); protected override int? ManagementPort => _managementPort; private static int FreePort() { var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0); listener.Start(); var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } } /// /// Core wired WITHOUT a management authentication processor, so /// direct-vm://identity-auth-management is never registered while the gRPC management surface is. /// A deployment can reach this state, and what happens next is the whole question: an authentication hop /// pointing at an address nobody serves must refuse, never wave the call through. /// public sealed class GrpcManagementWithoutAuthFixture : GrpcIdentityFixture { protected override bool RegisterManagementAuth => false; } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/HttpIdentityFixture.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/Infrastructure/HttpIdentityFixture.cs ---- using System.Net; using System.Net.Sockets; using System.Security.Claims; using System.Text.Json; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NSubstitute; using OpenIddict.Abstractions; using OpenIddict.Server; using OpenIddict.Validation; using redb.Core; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Routes.Processors; using redb.Identity.Core.Services; using redb.Identity.Http.Security; using redb.Identity.Http; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Http; using Xunit; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Infrastructure; /// /// Full integration fixture: real PostgreSQL + RouteContext with Core + HTTP facade routes /// + Kestrel on a random port. Provides both for HTTP E2E /// and for direct-vm:// access. /// public sealed class HttpIdentityFixture : IAsyncLifetime { private ServiceProvider _sp = null!; private RouteContext _ctx = null!; public int Port { get; private set; } public string BaseUrl => $"http://localhost:{Port}"; public HttpClient Http { get; private set; } = null!; public ProducerTemplate Producer { get; private set; } = null!; public IRedbService Redb { get; private set; } = null!; public IServiceProvider ServiceProvider => _sp; /// /// Bearer token with identity:manage scope issued during fixture setup. /// Use via Authorization: Bearer {ManagementToken}. /// public string ManagementToken { get; private set; } = null!; public async Task InitializeAsync() { Port = GetFreePort(); var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); // Real PostgreSQL-backed IRedbService (free or Pro per REDB_USE_PRO env) services.AddRedbForTests(cs); // SharedVmRegistry (required for direct-vm) services.AddSingleton(); // DataProtection (needed for session cookies) services.AddDataProtection().UseEphemeralDataProtectionProvider(); // MFA protectors — required by IdentityCoreRouteBuilder.Configure() (line 175) // even when no MFA tests run. Lightweight; pulls only IDataProtectionProvider. services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); // Identity options var identityOptions = new RedbIdentityOptions { TokenRetentionDays = 30, TokenThrottleMaxPerPeriod = 1000, TokenThrottlePeriod = TimeSpan.FromSeconds(1), AllowEphemeralKeys = true }; services.AddSingleton(Options.Create(identityOptions)); // Transport options with the test port var transportOptions = new IdentityTransportOptions(); transportOptions.Http.PublicPort = Port; // Loopback only: a test listener on every interface makes the OS firewall ask about each new // test binary path. transportOptions.Http.Host = "localhost"; transportOptions.Http.CorsEnabled = true; // Use AdditionalAllowedOrigins (the new CSV slot) so the per-request resolver // matches and echoes a single origin verbatim. The deprecated CorsOrigins still // works (it is folded into AdditionalAllowedOrigins) but new tests should use // the modern slot. transportOptions.Http.AdditionalAllowedOrigins = "http://localhost:3000,http://localhost:5173"; services.AddSingleton(Options.Create(transportOptions)); // OpenIddict in degraded mode services.AddOpenIddict() .AddCore(core => core.UseRedbStores()) .AddServer(options => { options.EnableDegradedMode(); options.SetIssuer(new Uri($"http://localhost:{Port}/")); options.SetTokenEndpointUris("/connect/token"); options.SetAuthorizationEndpointUris("/connect/authorize"); options.SetIntrospectionEndpointUris("/connect/introspect"); options.SetRevocationEndpointUris("/connect/revoke"); options.SetConfigurationEndpointUris("/.well-known/openid-configuration"); options.AllowClientCredentialsFlow(); options.AllowAuthorizationCodeFlow(); options.AllowRefreshTokenFlow(); options.RegisterScopes( Scopes.OpenId, Scopes.Profile, Scopes.Email, Scopes.OfflineAccess, identityOptions.ManagementScope); options.AddEphemeralEncryptionKey(); options.AddEphemeralSigningKey(); options.DisableAccessTokenEncryption(); options.UseRedbRoute(); // Degraded mode: skip validation options.AddEventHandler(builder => builder.UseInlineHandler(context => default) .SetOrder(int.MaxValue - 100_000).Build()); options.AddEventHandler(builder => builder.UseInlineHandler(context => default) .SetOrder(int.MaxValue - 100_000).Build()); options.AddEventHandler(builder => builder.UseInlineHandler(context => default) .SetOrder(int.MaxValue - 100_000).Build()); options.AddEventHandler(builder => builder.UseInlineHandler(context => default) .SetOrder(int.MaxValue - 100_000).Build()); // Provide ClaimsPrincipal for client_credentials options.AddEventHandler(builder => builder.UseInlineHandler(context => { if (!context.Request.IsClientCredentialsGrantType()) return default; var identity = new ClaimsIdentity( authenticationType: "OpenIddict.Server", nameType: Claims.Name, roleType: Claims.Role); identity.SetClaim(Claims.Subject, context.Request.ClientId ?? "test-sub"); identity.SetScopes(context.Request.GetScopes()); context.Principal = new ClaimsPrincipal(identity); return default; }) .SetOrder(OpenIddictServerHandlers.Exchange.AttachPrincipal .Descriptor.Order + 100).Build()); }) .AddValidation(validation => { validation.UseLocalServer(); validation.UseDataProtection(); // Custom handler: inject bearer token for programmatic validation validation.AddEventHandler(builder => builder.UseInlineHandler(context => { if (context.Transaction.Properties.TryGetValue( ManagementBearerAuthProcessor.TokenPropertyKey, out var rawToken) && rawToken is string token) { context.AccessToken = token; context.ExtractAccessToken = false; } return default; }) .SetOrder(int.MinValue + 500) .Build()); }); _sp = services.BuildServiceProvider(); // Initialize PostgreSQL schema Redb = _sp.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); // Create RouteContext _ctx = new RouteContext(_sp, "identity-http-integration"); // Register HTTP component _ctx.AddComponent(new HttpComponent { ServerManager = new SharedHttpServerManager() }); // Bearer auth processors live in Core's RouteBuilder so they get exposed as // `direct-vm://identity-auth-{management,scim}` consumers; the HTTP facade // calls them inline via .To(...). var validationScopes = _sp.GetRequiredService(); var managementAuth = new ManagementBearerAuthProcessor( validationScopes, new[] { identityOptions.ManagementScope, identityOptions.AccountScope }, anonymousPathPrefixes: new[] { "/api/v1/identity/password/", "/api/v1/identity/account/" }); IProcessor? scimAuth = identityOptions.Features.EnableScim ? new ManagementBearerAuthProcessor(validationScopes, identityOptions.ScimScope) : null; // Register all 13 identity core routes _ctx.AddRoutes(new IdentityCoreRouteBuilder(_sp, Options.Create(identityOptions), auditOptions: null, managementAuth: managementAuth, scimAuth: scimAuth)); // Register HTTP facade routes (auth flows via direct-vm into Core) var ticketService = new SessionTicketService( _sp.GetRequiredService()); _ctx.AddRoutes(new HttpFacadeRouteBuilder( ticketService, Options.Create(transportOptions))); await _ctx.Start(); Producer = new ProducerTemplate(_ctx); Producer.Start(); Http = new HttpClient { BaseAddress = new Uri(BaseUrl) }; // Obtain a management bearer token for tests ManagementToken = await ObtainManagementTokenAsync(); } public async Task DisposeAsync() { Http.Dispose(); Producer.Stop(); Producer.Dispose(); await _ctx.DisposeAsync(); await _sp.DisposeAsync(); } /// /// Issues a management bearer token via the token endpoint (client_credentials + identity:manage scope). /// private async Task ObtainManagementTokenAsync() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "management-test-client", ["client_secret"] = "management-test-secret", ["scope"] = "identity:manage" }); var response = await Http.PostAsync("/connect/token", content); if (!response.IsSuccessStatusCode) { var errorBody = await response.Content.ReadAsStringAsync(); throw new InvalidOperationException( $"Token endpoint returned {response.StatusCode}: {errorBody}"); } var json = await JsonSerializer.DeserializeAsync( await response.Content.ReadAsStreamAsync()); return json.GetProperty("access_token").GetString() ?? throw new InvalidOperationException("Token endpoint did not return access_token"); } private static int GetFreePort() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); int port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } } [CollectionDefinition("HttpIdentity")] public class HttpIdentityCollection : ICollectionFixture; Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/IdentityRouteFixture.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/Infrastructure/IdentityRouteFixture.cs ---- using System.Security.Claims; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using NSubstitute; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Core; using redb.Core.Providers; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using Xunit; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Infrastructure; /// /// Shared fixture that boots a full RouteContext with all 13 Identity routes. /// Uses OpenIddict degraded mode + mocked IRedbService. /// Tests send messages via ProducerTemplate through direct-vm:// — exercises the complete pipeline: /// error handling → throttle → processor → WireTap → event dispatch. /// public sealed class IdentityRouteFixture : IAsyncLifetime { private ServiceProvider _sp = null!; private RouteContext _ctx = null!; public ProducerTemplate Producer { get; private set; } = null!; public IRedbService Redb { get; private set; } = null!; public IServiceProvider ServiceProvider => _sp; /// The From URIs of every route the fixture registered — lets a test check coverage instead of guessing. public IEnumerable RegisteredFromUris => _ctx.Routes.Select(r => r.FromUri); public async Task InitializeAsync() { var services = new ServiceCollection(); // Logging services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); // Mocked IRedbService Redb = Substitute.For(); var userProvider = Substitute.For(); Redb.UserProvider.Returns(userProvider); services.AddSingleton(Redb); // SharedVmRegistry (required for direct-vm) services.AddSingleton(); // DataProtection + MFA protectors — required by IdentityCoreRouteBuilder.Configure() // even when no MFA tests run. services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); // Identity options services.AddSingleton(Options.Create(new RedbIdentityOptions { TokenRetentionDays = 30, TokenThrottleMaxPerPeriod = 100, // relaxed for tests TokenThrottlePeriod = TimeSpan.FromSeconds(1) })); // OpenIddict in degraded mode services.AddOpenIddict() .AddCore(core => core.UseRedbStores()) .AddServer(options => { options.EnableDegradedMode(); options.SetIssuer(new Uri("https://identity.test.local/")); options.SetTokenEndpointUris("/connect/token"); options.SetAuthorizationEndpointUris("/connect/authorize"); options.SetIntrospectionEndpointUris("/connect/introspect"); options.SetRevocationEndpointUris("/connect/revoke"); options.SetConfigurationEndpointUris("/.well-known/openid-configuration"); options.AllowClientCredentialsFlow(); options.AllowAuthorizationCodeFlow(); options.AllowRefreshTokenFlow(); options.AddEphemeralEncryptionKey(); options.AddEphemeralSigningKey(); options.DisableAccessTokenEncryption(); options.UseRedbRoute(); // Degraded mode: skip validation for all enabled endpoints options.AddEventHandler(builder => builder .UseInlineHandler(context => default) .SetOrder(int.MaxValue - 100_000) .Build()); options.AddEventHandler(builder => builder .UseInlineHandler(context => default) .SetOrder(int.MaxValue - 100_000) .Build()); options.AddEventHandler(builder => builder .UseInlineHandler(context => default) .SetOrder(int.MaxValue - 100_000) .Build()); options.AddEventHandler(builder => builder .UseInlineHandler(context => default) .SetOrder(int.MaxValue - 100_000) .Build()); // Provide ClaimsPrincipal for client_credentials options.AddEventHandler(builder => builder .UseInlineHandler(context => { if (!context.Request.IsClientCredentialsGrantType()) return default; var identity = new ClaimsIdentity( authenticationType: "OpenIddict.Server", nameType: Claims.Name, roleType: Claims.Role); identity.SetClaim(Claims.Subject, context.Request.ClientId ?? "test-sub"); identity.SetScopes(context.Request.GetScopes()); context.Principal = new ClaimsPrincipal(identity); return default; }) .SetOrder(OpenIddictServerHandlers.Exchange.AttachPrincipal .Descriptor.Order + 100) .Build()); }); _sp = services.BuildServiceProvider(); // Create RouteContext with full DI _ctx = new RouteContext(_sp, "identity-integration"); // Register all 13 identity routes _ctx.AddRoutes(new IdentityCoreRouteBuilder(_sp, Options.Create(new RedbIdentityOptions { TokenThrottleMaxPerPeriod = 100, TokenThrottlePeriod = TimeSpan.FromSeconds(1), TokenRetentionDays = 30 }))); await _ctx.Start(); Producer = new ProducerTemplate(_ctx); Producer.Start(); } public async Task DisposeAsync() { Producer.Stop(); Producer.Dispose(); await _ctx.DisposeAsync(); await _sp.DisposeAsync(); } /// /// Sends a request through the route pipeline with InOut pattern (returns Out.Body). /// public async Task Request(string endpointUri, object body) { return await Producer.RequestBody(endpointUri, body); } /// /// Sends a request with custom headers (e.g. operation header for management endpoints). /// Returns the full exchange for inspection. /// public async Task RequestWithHeaders( string endpointUri, object? body, IDictionary headers, ManagementCaller caller = ManagementCaller.Admin) { var message = new Message { Body = body }; foreach (var (key, value) in headers) message.Headers[key] = value; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOut }; // This fixture plays the facade: the core management routes refuse an exchange without a // management context, so say which caller we are. Admin unless the test probes the gate. ManagementCallerContext.Apply(exchange, caller); var endpoint = _ctx.GetEndpoint(endpointUri); var producer = endpoint.CreateProducer(); await producer.Process(exchange); // Identity convention: business processors write the response into exchange.In.Body // and PipelineProcessor (Camel-compliant) does not synthesise Out from In. Tests // historically read exchange.Out?.Body directly, so normalise Out := copy-of-In here. NormalizeOutFromIn(exchange); return exchange; } private static void NormalizeOutFromIn(Exchange exchange) { if (exchange.Out is not null) return; var inMsg = exchange.In; if (inMsg is null) return; var outMsg = new Message { Body = inMsg.Body, ContentType = inMsg.ContentType }; foreach (var (k, v) in inMsg.Headers) outMsg.Headers[k] = v; exchange.Out = outMsg; } } [CollectionDefinition("IdentityRoute")] public class IdentityRouteCollection : ICollectionFixture; Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/InRouteTransactionHistoryStoreGuard.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/Infrastructure/InRouteTransactionHistoryStoreGuard.cs ---- using System.Collections.Concurrent; using System.Transactions; using redb.Core; using redb.Identity.Core.Security; namespace redb.Identity.Tests.Infrastructure; /// /// Wraps the password history store of the production fixture and refuses the overloads that open a scope of /// their own while an ambient transaction is active, that is, inside a transacted route. In a deployment that /// scope's connection is a second one inside the route's transaction, which promotes it to a distributed /// transaction, and stock PostgreSQL (max_prepared_transactions = 0) refuses it. In this test host the second /// connection does not show, so the rule is checked here instead of by the database. /// public sealed class InRouteTransactionHistoryStoreGuard(IPasswordHistoryStore inner) : IPasswordHistoryStore { /// Every refused call, also those a caller swallowed (history recording does). public static ConcurrentQueue Violations { get; } = new(); public Task IsRecentlyUsedAsync(long userId, string password, int count, CancellationToken ct) { Refuse(nameof(IsRecentlyUsedAsync)); return inner.IsRecentlyUsedAsync(userId, password, count, ct); } public Task IsRecentlyUsedAsync(IRedbService redb, long userId, string password, int count, CancellationToken ct) => inner.IsRecentlyUsedAsync(redb, userId, password, count, ct); public Task RecordAsync(long userId, string password, int keep, CancellationToken ct) { Refuse(nameof(RecordAsync)); return inner.RecordAsync(userId, password, keep, ct); } private static void Refuse(string method) { if (Transaction.Current is null) return; var message = $"IPasswordHistoryStore.{method} without the exchange's IRedbService inside a route transaction"; Violations.Enqueue(message); throw new InvalidOperationException(message); } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/IndexFixHelper.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/Infrastructure/IndexFixHelper.cs ---- using Npgsql; namespace redb.Identity.Tests.Infrastructure; /// /// Fixes btree indexes on _values that include _string in the index tuple. /// Without this fix, tokens with large Payload values (e.g., 4+ scope authorization codes) /// exceed the btree 2704-byte row limit and cause PostgresException 54000. /// /// PostgreSQL only. The 2704-byte limit is a PostgreSQL btree implementation detail; /// neither SQLite nor SQL Server has it, and the SQL below is Postgres-specific /// (INCLUDE, deduplicate_items). Every fixture calls this unconditionally, so /// the provider check lives HERE rather than at the five call sites — a check a caller can /// forget is a check that will be forgotten. Under sqlite/mssql this is a no-op. /// /// internal static class IndexFixHelper { /// /// Drops and recreates _values indexes that include _string, removing _string from /// the index to avoid btree row overflow on large payloads. /// Call after InitializeAsync() and SyncScheme calls. /// private static readonly SemaphoreSlim _lock = new(1, 1); private static bool _applied; public static async Task FixValueStringIndexAsync(string connectionString) { // Not our storage engine, not our problem — and opening an Npgsql connection here would // drag a PostgreSQL dependency into a run the operator explicitly pointed at SQLite, // failing every fixture at InitializeAsync before a single test body runs. if (TestRedbSetup.SelectedProvider != TestRedbSetup.Provider.Postgres) return; await _lock.WaitAsync(); try { if (_applied) return; await using var conn = new NpgsqlConnection(connectionString); await conn.OpenAsync(); await using var cmd = conn.CreateCommand(); cmd.CommandText = """ -- 1. Covering index: object→structure lookup (was INCLUDE _String) DROP INDEX IF EXISTS "IX__values__object_structure_lookup"; CREATE INDEX "IX__values__object_structure_lookup" ON _values (_id_object, _id_structure, _array_index) INCLUDE (_long, _double, _datetimeoffset, _boolean, _guid, _numeric, _listitem, _object) WITH (deduplicate_items=True); -- 2. Covering index: non-array values (was INCLUDE _String) DROP INDEX IF EXISTS "IX__values__object_array_null"; CREATE INDEX "IX__values__object_array_null" ON _values (_id_object, _id_structure) INCLUDE (_long, _double, _datetimeoffset, _boolean, _guid, _numeric, _listitem, _object) WHERE _array_index IS NULL; -- 3. Faceted search: structure→object (was KEY _String) DROP INDEX IF EXISTS "IX__values__structure_object_lookup"; CREATE INDEX "IX__values__structure_object_lookup" ON _values (_id_structure, _id_object, _Long, _DateTimeOffset, _Boolean, _Double, _Guid, _Numeric, _ListItem, _Object); -- 4. String value lookup: add length guard so large strings (JWT payloads) don't overflow btree DROP INDEX IF EXISTS "IX__values__String_not_null"; CREATE INDEX "IX__values__String_not_null" ON _values (_id_structure, _id_object, _string) WHERE (_string IS NOT NULL AND length(_string) < 2000); -- 5. Array parent batch: remove _string from INCLUDE DROP INDEX IF EXISTS "IX__values__structure_parent_batch"; CREATE INDEX "IX__values__structure_parent_batch" ON _values (_id_structure, _array_parent_id) INCLUDE (_long, _double, _boolean, _guid) WHERE _array_parent_id IS NOT NULL; """; await cmd.ExecuteNonQueryAsync(); _applied = true; } finally { _lock.Release(); } } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/LogoutFlow.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/Infrastructure/LogoutFlow.cs ---- using System.Net; using System.Text.RegularExpressions; using AwesomeAssertions; namespace redb.Identity.Tests.Infrastructure; /// /// The browser half of a logout without an id_token_hint: /connect/logout answers with a /// confirmation page whose form carries a state bound to the session, and posting that form back is the /// confirmation. Tests that sign out by cookie go through here, the way a person clicking the button does. /// internal static class LogoutFlow { private static readonly Regex HiddenInput = new( "", RegexOptions.Compiled); public static bool IsConfirmationPage(string html) => html.Contains("name=\"logout_state\"", StringComparison.Ordinal); /// Every hidden field of the confirmation form, HTML-decoded: the state and the relying party's own parameters. public static Dictionary HiddenFields(string html) { var fields = new Dictionary(); foreach (Match m in HiddenInput.Matches(html)) fields[m.Groups[1].Value] = WebUtility.HtmlDecode(m.Groups[2].Value); return fields; } /// Confirms the page in as the same browser and returns the final logout response. public static async Task ConfirmAsync(HttpClient browser, HttpResponseMessage page) { var html = await page.Content.ReadAsStringAsync(); IsConfirmationPage(html).Should().BeTrue( "a logout by cookie without an id_token_hint answers with the confirmation page first; got {0}: {1}", (int)page.StatusCode, html.Length > 300 ? html[..300] : html); return await browser.PostAsync("/connect/logout", new FormUrlEncodedContent(HiddenFields(html))); } /// GET with the browser's cookie, then confirm. Returns the final response. public static async Task SignOutAsync(HttpClient browser, string pathAndQuery = "/connect/logout") { var page = await browser.GetAsync(pathAndQuery); return await ConfirmAsync(browser, page); } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/ManagementCaller.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/Infrastructure/ManagementCaller.cs ---- using redb.Identity.Contracts.Configuration; using redb.Route.Abstractions; namespace redb.Identity.Tests.Infrastructure; /// /// Who a fixture stands in for when it sends straight to a core management route. /// /// The core routes (direct-vm://identity-manage-*, identity-me-*, identity-scim-*, /// identity-revoked-sids) never see a bearer token themselves: a facade validates it on the /// identity-auth-management hop and forwards the exchange with the identity:management-* /// properties attached. A fixture that sends to those routes directly is therefore playing the facade, /// and has to say which caller it plays — the routes refuse an exchange that carries no management /// context at all, whatever transport it arrived on. /// /// public enum ManagementCaller { /// A facade that validated a bearer carrying identity:manage: may target any user. Admin, /// /// No management context at all — what an in-process caller that never went through a facade looks /// like. Only for tests that probe the gate itself. /// None, } public static class ManagementCallerContext { public const string ScopesProperty = "identity:management-scopes"; /// /// Attaches what ManagementBearerAuthProcessor would have attached for . /// public static T Apply(T exchange, ManagementCaller caller) where T : IExchange { switch (caller) { case ManagementCaller.Admin: exchange.Properties[ScopesProperty] = new[] { IdentityScopes.Manage }; break; case ManagementCaller.None: exchange.Properties.Remove(ScopesProperty); break; } return exchange; } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/MockOidcE2EFixture.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/Infrastructure/MockOidcE2EFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using Xunit; using redb.Identity.Contracts.Configuration; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Infrastructure; /// /// E2E fixture for federation tests against a real mock-oauth2-server (navikt). /// Requires the route-mock-oauth2 container running on port 9199. /// Uses (real OIDC client) instead of FakeFederatedAuthProvider. /// public sealed class MockOidcE2EFixture : IAsyncLifetime { private ServiceProvider _sp = null!; private RouteContext _ctx = null!; /// mock-oauth2-server authority (issuer "default"). public const string Authority = "http://localhost:9199/default"; /// mock-oauth2-server accepts any client_id/secret. public const string MockClientId = "redb-e2e-client"; public const string MockClientSecret = "redb-e2e-secret"; public const string ProviderId = "mock-oidc"; public const string TestUsername = "e2e-fed-testuser"; public const string TestPassword = "E2eTest@Password123"; /// Callback URL that OidcFederatedAuthProvider embeds in authorize request. public const string CallbackUrl = "http://localhost/federation/callback"; public ProducerTemplate Producer { get; private set; } = null!; /// /// Captive root-scoped . NOT thread-safe across /// concurrent calls — see the same property on /// for the full rationale. Use /// / for any path that may /// run concurrently with the Worker's route processing. /// public IRedbService Redb { get; private set; } = null!; /// /// Run against a fresh, scoped /// . See /// for the rationale (concurrent-NpgsqlConnection / shared SqlConnection / /// SqliteException(SQLITE_BUSY) classes of failure when the captive Redb is /// accessed while the Worker's WireTap audit pipeline is mid-write). /// public async Task WithRedb(Func> action) { if (action is null) throw new ArgumentNullException(nameof(action)); using var scope = _sp.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); return await action(redb).ConfigureAwait(false); } /// Void-result overload of . public async Task WithRedb(Func action) { if (action is null) throw new ArgumentNullException(nameof(action)); using var scope = _sp.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); await action(redb).ConfigureAwait(false); } public IServiceProvider ServiceProvider => _sp; public long TestUserId { get; private set; } /// Pre-configured HttpClient for interacting with mock-oauth2-server. public HttpClient MockOidcHttpClient { get; } = new(new HttpClientHandler { AllowAutoRedirect = false }); /// Returns true if mock-oauth2-server is reachable. public bool IsServerAvailable { get; private set; } /// /// Fails the test when mock-oauth2-server is not reachable, so a run without it shows these tests as failed /// rather than passed. A run that cannot provide the server leaves the classes out by their traits /// (Requires=MockOAuth2, Category=Integration). /// public void RequireServer() { if (!IsServerAvailable) throw new InvalidOperationException( $"mock-oauth2-server is not reachable at {Authority}. Start it with: docker compose -f " + "redb.Route/docker-compose.tests.yml --profile oauth2 up -d mock-oauth2, or filter these tests out " + "with --filter Requires!=MockOAuth2."); } public async Task InitializeAsync() { // Check if mock-oauth2-server is available IsServerAvailable = await CheckServerAsync(); if (!IsServerAvailable) return; // every test then fails in RequireServer with how to start the server or filter the class out var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var providerConfig = new FederationProviderConfig { ProviderId = ProviderId, DisplayName = "Mock OIDC Server", Authority = Authority, ClientId = MockClientId, ClientSecret = MockClientSecret, Scopes = ["openid", "profile", "email"] }; var identityOptions = new RedbIdentityOptions { TokenRetentionDays = 30, TokenThrottleMaxPerPeriod = 1000, TokenThrottlePeriod = TimeSpan.FromSeconds(1), Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true, EnablePasswordFlow = true, Features = new IdentityFeatureFlags { EnableFederation = true }, FederationProviders = [providerConfig] }; services.AddSingleton(Options.Create(identityOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); Redb = _sp.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); await IndexFixHelper.FixValueStringIndexAsync(cs); await SeedTestUser(); _ctx = new RouteContext(_sp, "e2e-federation-integration"); _ctx.AddRoutes(new IdentityCoreRouteBuilder(_sp, Options.Create(identityOptions))); await _ctx.Start(); Producer = new ProducerTemplate(_ctx); Producer.Start(); } public async Task DisposeAsync() { MockOidcHttpClient.Dispose(); if (!IsServerAvailable) return; Producer.Stop(); Producer.Dispose(); await _ctx.DisposeAsync(); await _sp.DisposeAsync(); } public async Task Request(string endpointUri, object body) { return await Producer.RequestBody(endpointUri, body); } /// /// H8: send a request with explicit headers (needed by management processors that /// dispatch on the operation header). /// public async Task RequestWithHeaders( string endpointUri, object? body, IDictionary headers, ManagementCaller caller = ManagementCaller.Admin) { var message = new Message { Body = body }; foreach (var (key, value) in headers) message.Headers[key] = value; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOut }; // This fixture plays the facade: the core management routes refuse an exchange without a // management context, so say which caller we are. Admin unless the test probes the gate. ManagementCallerContext.Apply(exchange, caller); var endpoint = _ctx.GetEndpoint(endpointUri); var producer = endpoint.CreateProducer(); await producer.Process(exchange); // Identity convention: business processors write the response into exchange.In.Body // and PipelineProcessor (Camel-compliant) does not synthesise Out from In. Tests // historically read exchange.Out?.Body directly, so normalise Out := copy-of-In here. NormalizeOutFromIn(exchange); return exchange; } private static void NormalizeOutFromIn(Exchange exchange) { if (exchange.Out is not null) return; var inMsg = exchange.In; if (inMsg is null) return; var outMsg = new Message { Body = inMsg.Body, ContentType = inMsg.ContentType }; foreach (var (k, v) in inMsg.Headers) outMsg.Headers[k] = v; exchange.Out = outMsg; } /// /// Simulates the browser-side interactive login on mock-oauth2-server. /// POSTs username to the authorize URL → gets 302 redirect with code. /// Returns (code, state) from the redirect Location header. /// public async Task<(string code, string state)> SimulateInteractiveLogin( string authorizeUrl, string username = "e2e-test-user") { // POST to the authorize URL with username (mock-oauth2-server interactive login form) var formContent = new FormUrlEncodedContent(new Dictionary { ["username"] = username }); var response = await MockOidcHttpClient.PostAsync(authorizeUrl, formContent); if (response.StatusCode != System.Net.HttpStatusCode.Found) throw new InvalidOperationException( $"Expected 302 redirect from mock-oauth2-server, got {response.StatusCode}"); var location = response.Headers.Location?.ToString() ?? throw new InvalidOperationException("No Location header in mock-oauth2-server redirect"); var code = ExtractQueryParam(location, "code") ?? throw new InvalidOperationException("No 'code' parameter in redirect URL"); var state = ExtractQueryParam(location, "state") ?? throw new InvalidOperationException("No 'state' parameter in redirect URL"); return (code, state); } internal static string? ExtractQueryParam(string url, string paramName) { var uri = new Uri(url, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) uri = new Uri("http://dummy" + url); var query = uri.Query.TrimStart('?'); foreach (var pair in query.Split('&', StringSplitOptions.RemoveEmptyEntries)) { var parts = pair.Split('=', 2); if (parts.Length == 2 && parts[0] == paramName) return Uri.UnescapeDataString(parts[1]); } return null; } private async Task CheckServerAsync() { try { using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)); var response = await MockOidcHttpClient.GetAsync( $"{Authority}/.well-known/openid-configuration", cts.Token); return response.IsSuccessStatusCode; } catch { return false; } } private async Task SeedTestUser() { var coreUser = await Redb.UserProvider.GetUserByLoginAsync(TestUsername); if (coreUser is null) { coreUser = await Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = TestUsername, Password = TestPassword, Name = TestUsername, Email = "e2e-fed@example.com", Enabled = true }); } TestUserId = coreUser.Id; var oidcObj = await Redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync(); if (oidcObj is null) { oidcObj = new RedbObject(new UserProps()); oidcObj.name = TestUsername; oidcObj.key = coreUser.Id; oidcObj.value_guid = Guid.NewGuid(); } oidcObj.Props.EmailVerified = true; oidcObj.Props.GivenName = "E2E"; oidcObj.Props.FamilyName = "TestUser"; await Redb.SaveAsync(oidcObj); } } [CollectionDefinition("MockOidcE2E")] public class MockOidcE2ECollection : ICollectionFixture; Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/MockRedbQuery.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/Infrastructure/MockRedbQuery.cs ---- using System.Linq.Expressions; using NSubstitute; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Core.Query.Aggregation; using redb.Core.Query.Grouping; using redb.Core.Query.Window; using redb.Identity.Core.Models; namespace redb.Identity.Tests.Infrastructure; /// /// Configures mock to return a queryable over an in-memory list. /// Usage: MockRedbQuery.Setup(redb, items) /// internal static class MockRedbQuery { /// /// Makes redb.Query<TProps>() return a mock queryable over . /// The mock supports: Where, WhereRedb, OrderByRedb, Skip, Take, ToListAsync, CountAsync, FirstOrDefaultAsync, AnyAsync. /// public static void Setup(IRedbService redb, List> items) where TProps : class, new() { var queryable = new InMemoryRedbQueryable(items); redb.Query().Returns(_ => new InMemoryRedbQueryable(items)); } /// /// Creates a RedbObject with the given id, name, and props for testing. /// public static RedbObject CreateObject(long id, string name, TProps props) where TProps : class, new() { var obj = new RedbObject(props) { Id = id, Name = name, DateCreate = DateTimeOffset.UtcNow, DateModify = DateTimeOffset.UtcNow }; // Sync value_string for [RedbIgnore] identity fields obj.value_string = props switch { ApplicationProps a => a.ClientId, ScopeProps s => s.ScopeName, _ => null }; return obj; } } /// /// Minimal in-memory IRedbQueryable for unit tests. /// Supports basic fluent operations used by management processors. /// internal class InMemoryRedbQueryable : IRedbQueryable, IOrderedRedbQueryable where TProps : class, new() { private IEnumerable> _source; public InMemoryRedbQueryable(IEnumerable> source) => _source = source; public IRedbQueryable Where(Expression> predicate) { var compiled = predicate.Compile(); return new InMemoryRedbQueryable(_source.Where(o => compiled(o.Props))); } public IRedbQueryable WhereRedb(Expression> predicate) { var compiled = predicate.Compile(); return new InMemoryRedbQueryable(_source.Where(o => compiled(o))); } public IOrderedRedbQueryable OrderBy(Expression> keySelector) { var compiled = keySelector.Compile(); return new InMemoryRedbQueryable(_source.OrderBy(o => compiled(o.Props))); } public IOrderedRedbQueryable OrderByDescending(Expression> keySelector) { var compiled = keySelector.Compile(); return new InMemoryRedbQueryable(_source.OrderByDescending(o => compiled(o.Props))); } public IOrderedRedbQueryable OrderByRedb(Expression> keySelector) { var compiled = keySelector.Compile(); return new InMemoryRedbQueryable(_source.OrderBy(o => compiled(o))); } public IOrderedRedbQueryable OrderByDescendingRedb(Expression> keySelector) { var compiled = keySelector.Compile(); return new InMemoryRedbQueryable(_source.OrderByDescending(o => compiled(o))); } public IRedbQueryable Take(int count) => new InMemoryRedbQueryable(_source.Take(count)); public IRedbQueryable Skip(int count) => new InMemoryRedbQueryable(_source.Skip(count)); public Task>> ToListAsync(CancellationToken cancellationToken = default) => Task.FromResult(_source.ToList()); public Task CountAsync(CancellationToken cancellationToken = default) => Task.FromResult(_source.Count()); public Task?> FirstOrDefaultAsync(CancellationToken cancellationToken = default) => Task.FromResult(_source.FirstOrDefault()); public Task?> FirstOrDefaultAsync(Expression> predicate, CancellationToken cancellationToken = default) { var compiled = predicate.Compile(); return Task.FromResult(_source.FirstOrDefault(o => compiled(o.Props))); } public Task AnyAsync(CancellationToken cancellationToken = default) => Task.FromResult(_source.Any()); public Task AnyAsync(Expression> predicate, CancellationToken cancellationToken = default) { var compiled = predicate.Compile(); return Task.FromResult(_source.Any(o => compiled(o.Props))); } // ── Not used by management processors but required by interface ── public IRedbQueryable WhereIn(Expression> selector, IEnumerable values) => throw new NotSupportedException(); public IRedbQueryable WhereInRedb(Expression> selector, IEnumerable values) => throw new NotSupportedException(); public Task AllAsync(Expression> predicate, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public IRedbProjectedQueryable Select(Expression, TResult>> selector) { var compiled = selector.Compile(); return new InMemoryRedbProjectedQueryable(_source.Select(compiled)); } public IRedbQueryable Distinct() => new InMemoryRedbQueryable(_source.Distinct()); public IRedbQueryable DistinctRedb() => throw new NotSupportedException(); public IRedbQueryable DistinctBy(Expression> keySelector) => throw new NotSupportedException(); public IRedbQueryable DistinctByRedb(Expression> keySelector) => throw new NotSupportedException(); public IRedbQueryable WithMaxRecursionDepth(int depth) => throw new NotSupportedException(); public IRedbQueryable WithLazyReferences(bool enabled = true) => throw new NotSupportedException(); public IRedbQueryable WhereHasAncestor(Expression> ancestorCondition, int? maxDepth = null) where TTarget : class => throw new NotSupportedException(); public IRedbQueryable WhereHasDescendant(Expression> descendantCondition, int? maxDepth = null) where TTarget : class => throw new NotSupportedException(); public IRedbQueryable WhereLevel(int level) => throw new NotSupportedException(); public IRedbQueryable WhereLevel(Expression> levelCondition) => throw new NotSupportedException(); public IRedbQueryable WhereRoots() => throw new NotSupportedException(); public IRedbQueryable WhereLeaves() => throw new NotSupportedException(); public IRedbQueryable WhereChildrenOf(long parentId) => throw new NotSupportedException(); public IRedbQueryable WhereChildrenOf(IRedbObject parentObject) => throw new NotSupportedException(); public IRedbQueryable WhereDescendantsOf(long ancestorId, int? maxDepth = null) => throw new NotSupportedException(); public IRedbQueryable WhereDescendantsOf(IRedbObject ancestorObject, int? maxDepth = null) => throw new NotSupportedException(); public IRedbQueryable WithMaxDepth(int depth) => throw new NotSupportedException(); public IRedbQueryable WithPropsDepth(int depth) => throw new NotSupportedException(); public Task>> ToTreeListAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task> ToRootListAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task>> ToFlatListAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task DeleteAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task SumAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct => throw new NotSupportedException(); public Task AverageAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct => throw new NotSupportedException(); public Task MinAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct => throw new NotSupportedException(); public Task MaxAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct => throw new NotSupportedException(); public Task> GetStatisticsAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct => throw new NotSupportedException(); public Task AggregateAsync(Expression, TResult>> selector, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task SumRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct => throw new NotSupportedException(); public Task AverageRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct => throw new NotSupportedException(); public Task MinRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct => throw new NotSupportedException(); public Task MaxRedbAsync(Expression> selector, CancellationToken cancellationToken = default) where TField : struct => throw new NotSupportedException(); public Task AggregateRedbAsync(Expression> selector, CancellationToken cancellationToken = default) => throw new NotSupportedException(); public IRedbGroupedQueryable GroupBy(Expression> keySelector) => throw new NotSupportedException(); public IRedbGroupedQueryable GroupByRedb(Expression> keySelector) => throw new NotSupportedException(); public IRedbGroupedQueryable GroupByArray(Expression>> arraySelector, Expression> keySelector) => throw new NotSupportedException(); public IRedbWindowedQueryable WithWindow(Action> windowConfig) => throw new NotSupportedException(); public string ToSqlString() => throw new NotSupportedException(); public Task ToSqlStringAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); public Task ToFilterJsonAsync(CancellationToken cancellationToken = default) => throw new NotSupportedException(); // IOrderedRedbQueryable public IOrderedRedbQueryable ThenBy(Expression> keySelector) => throw new NotSupportedException(); public IOrderedRedbQueryable ThenByDescending(Expression> keySelector) => throw new NotSupportedException(); public IOrderedRedbQueryable ThenByRedb(Expression> keySelector) => throw new NotSupportedException(); public IOrderedRedbQueryable ThenByDescendingRedb(Expression> keySelector) => throw new NotSupportedException(); } /// /// In-memory projected queryable for unit tests. Supports Distinct, Take, ToListAsync. /// internal class InMemoryRedbProjectedQueryable : IRedbProjectedQueryable { private IEnumerable _source; public InMemoryRedbProjectedQueryable(IEnumerable source) => _source = source; public IRedbProjectedQueryable Where(Expression> predicate) { var compiled = predicate.Compile(); return new InMemoryRedbProjectedQueryable(_source.Where(compiled)); } public IRedbProjectedQueryable OrderBy(Expression> keySelector) { var compiled = keySelector.Compile(); return new InMemoryRedbProjectedQueryable(_source.OrderBy(compiled)); } public IRedbProjectedQueryable OrderByDescending(Expression> keySelector) { var compiled = keySelector.Compile(); return new InMemoryRedbProjectedQueryable(_source.OrderByDescending(compiled)); } public IRedbProjectedQueryable Take(int count) => new InMemoryRedbProjectedQueryable(_source.Take(count)); public IRedbProjectedQueryable Skip(int count) => new InMemoryRedbProjectedQueryable(_source.Skip(count)); public IRedbProjectedQueryable Distinct() => new InMemoryRedbProjectedQueryable(_source.Distinct()); public Task> ToListAsync(CancellationToken cancellationToken = default) => Task.FromResult(_source.ToList()); public Task CountAsync(CancellationToken cancellationToken = default) => Task.FromResult(_source.Count()); public Task FirstOrDefaultAsync(CancellationToken cancellationToken = default) => Task.FromResult(_source.FirstOrDefault()); public Task GetProjectionInfoAsync(CancellationToken cancellationToken = default) => Task.FromResult("in-memory-projection"); } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/MockRouteContext.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/Infrastructure/MockRouteContext.cs ---- using NSubstitute; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Abstractions; namespace redb.Identity.Tests.Infrastructure; /// /// Creates a mock that resolves the given /// via context.GetService<IRedbService>() (used by GetRedbService() extension). /// internal static class MockRouteContext { public static IRouteContext Create(IRedbService redb) { var context = Substitute.For(); context.GetService().Returns(redb); // NSubstitute auto-mocks interface return types — pin GetFromRegistry to null so // GetIdentityService falls through to the host SP instead of an empty auto-mocked scope. context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); return context; } /// /// Creates a mock that also exposes a service provider via /// context.GetServiceProvider(). Use when the processor under test resolves /// additional services (e.g. IOpenIddictApplicationManager) from the SP. /// public static IRouteContext CreateWithServices(IRedbService redb, params (Type, object)[] services) { var context = Substitute.For(); context.GetService().Returns(redb); // NSubstitute auto-mocks interface return types — pin GetFromRegistry to null so // GetIdentityService falls through to the host SP instead of an empty auto-mocked scope. context.GetFromRegistry(Arg.Any()).Returns((IServiceScopeFactory?)null); var sc = new ServiceCollection(); sc.AddSingleton(redb); foreach (var (type, instance) in services) sc.AddSingleton(type, instance); var sp = sc.BuildServiceProvider(); context.GetServiceProvider().Returns(sp); return context; } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/PostgresCollection.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/Infrastructure/PostgresCollection.cs ---- using Xunit; namespace redb.Identity.Tests.Infrastructure; [CollectionDefinition("Postgres")] public class PostgresCollection : ICollectionFixture { } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/PostgresFixture.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/Infrastructure/PostgresFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Xunit; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Postgres.Pro.Extensions; using redb.Identity.Core.Models; using redb.Identity.DataProtection; namespace redb.Identity.Tests.Infrastructure; public class PostgresFixture : IAsyncLifetime { public IRedbService Redb { get; private set; } = null!; public ServiceProvider Services { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found in appsettings.json"); var sc = new ServiceCollection(); sc.AddLogging(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); sc.AddRedbForTests(cs); Services = sc.BuildServiceProvider(); Redb = Services.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); // Fix btree index overflow for large Payload values (4+ scope tokens) await IndexFixHelper.FixValueStringIndexAsync(cs); } public async Task DisposeAsync() { if (Services is not null) await Services.DisposeAsync(); } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/ProductionBootstrapFixture.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/Infrastructure/ProductionBootstrapFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core; using redb.Identity.Contracts.Configuration; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using Xunit; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Infrastructure; /// /// Integration fixture using the PRODUCTION DI bootstrap (). /// Real PostgreSQL + real OpenIddict stores (no degraded mode, no mocks). /// Provides for direct-vm:// access. /// Creates a test client + test user in the database on startup. /// public sealed class ProductionBootstrapFixture : IAsyncLifetime { private ServiceProvider _sp = null!; private RouteContext _ctx = null!; public const string TestClientId = "integration-test-client"; public const string TestClientSecret = "integration-test-secret-value"; public const string TestClientIdPublic = "integration-test-pkce-client"; public const string TestUsername = "testuser"; public const string TestPassword = "Test@Password123"; public const string TestRedirectUri = "http://localhost/callback"; public ProducerTemplate Producer { get; private set; } = null!; /// /// Captive root-scoped . NOT thread-safe across /// concurrent calls — the underlying /// (Npgsql / Microsoft.Data.SqlClient) cannot multiplex commands. Reusing this /// instance from a test thread that also triggers Worker-side route processing /// (which fires its own DB writes through the same root-scoped service when /// resolved from _sp) produces: /// /// PG: NpgsqlOperationInProgressException : A command is already in progress /// SQL Server: SqlConnection does not support parallel transactions /// SQLite: SqliteException(SQLITE_BUSY) /// /// Use / instead from any test /// path that runs concurrently with the Worker (any test that goes through the /// HTTP/direct-vm pipeline). The captive property is retained /// for setup code that runs before the Worker is processing requests /// (, SyncSchemeAsync bootstrap, etc.) where /// the lack of concurrent access makes the captive resolution safe. /// public IRedbService Redb { get; private set; } = null!; /// /// Run against a fresh, scoped /// . Each call opens a brand-new /// , resolves a per-scope IRedbService (which in /// turn lazily opens its own provider connection on first use), runs the /// action, and disposes the scope on return — so no /// is shared with any concurrent caller. /// public async Task WithRedb(Func> action) { if (action is null) throw new ArgumentNullException(nameof(action)); using var scope = _sp.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); return await action(redb).ConfigureAwait(false); } /// /// Void-result overload of . /// public async Task WithRedb(Func action) { if (action is null) throw new ArgumentNullException(nameof(action)); using var scope = _sp.CreateScope(); var redb = scope.ServiceProvider.GetRequiredService(); await action(redb).ConfigureAwait(false); } public IServiceProvider ServiceProvider => _sp; public long TestUserId { get; private set; } /// /// The public per-user GUID (UserProps.value_guid) that surfaces in every /// JWT as the sub claim. Tests asserting on sub should compare /// against this — never against , which is the /// internal bigint mirrored into the redb:user_id claim. /// public Guid TestSubjectGuid { get; private set; } /// /// Shared fake external provider registered in DI. Tests configure handlers /// before each ROPC call. Empty handlers → returns null (skip) → no impact on other tests. /// public FakeExternalUserProvider FakeExternalProvider { get; } = new(); public async Task InitializeAsync() { var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); var services = new ServiceCollection(); services.AddLogging(b => b .SetMinimumLevel(LogLevel.Warning)); // Real PostgreSQL + Pro with DeleteInsert services.AddRedbForTests(cs); // SharedVmRegistry (required for direct-vm) services.AddSingleton(); // Identity options var identityOptions = new RedbIdentityOptions { TokenRetentionDays = 30, TokenThrottleMaxPerPeriod = 1000, TokenThrottlePeriod = TimeSpan.FromSeconds(1), Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true, Features = new IdentityFeatureFlags { EnableDeviceCodeFlow = true }, EnablePasswordFlow = true, EnableTokenExchange = true }; services.AddSingleton(Options.Create(identityOptions)); // Register fake external provider BEFORE identity server bootstrap. // Empty handlers = skip all users = no impact on existing tests. services.AddSingleton(FakeExternalProvider); // PRODUCTION bootstrap — the whole point of this fixture services.AddRedbIdentityServer(identityOptions); // E7: ValidateOnBuild detects captive dependencies (Singleton ctor depending on // Scoped) at build time — the cardinal anti-pattern Sprint E7 targets. We do NOT // turn ValidateScopes on here because this fixture intentionally resolves scoped // services via the root provider (long-standing test-bed convention; routing all // tests through per-scope resolution would touch dozens of files and is unrelated // to the captive-dep audit). _sp = services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = false, ValidateOnBuild = true, }); // Initialize PostgreSQL schema Redb = _sp.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); // Fix btree index overflow for large Payload values (4+ scope tokens) await IndexFixHelper.FixValueStringIndexAsync(cs); // Seed test data await SeedTestClient(); await SeedTestUser(); // Create RouteContext _ctx = new RouteContext(_sp, "production-bootstrap-integration"); _ctx.AddRoutes(new IdentityCoreRouteBuilder(_sp, Options.Create(identityOptions))); await _ctx.Start(); Producer = new ProducerTemplate(_ctx); Producer.Start(); } public async Task DisposeAsync() { Producer.Stop(); Producer.Dispose(); await _ctx.DisposeAsync(); await _sp.DisposeAsync(); } private async Task SeedTestClient() { var manager = _sp.GetRequiredService(); // Delete stale test apps (may have wrong secret format from prior runs) var existingConfidential = await manager.FindByClientIdAsync(TestClientId); if (existingConfidential is not null) await manager.DeleteAsync(existingConfidential); var existingPublic = await manager.FindByClientIdAsync(TestClientIdPublic); if (existingPublic is not null) await manager.DeleteAsync(existingPublic); // Confidential client — manager will BCrypt-hash the secret properly await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = TestClientId, ClientSecret = TestClientSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "Integration Test Client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.Endpoints.Introspection, OpenIddictConstants.Permissions.Endpoints.Revocation, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.GrantTypes.RefreshToken, OpenIddictConstants.Permissions.GrantTypes.Password, "gt:urn:ietf:params:oauth:grant-type:token-exchange", OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Email, OpenIddictConstants.Permissions.Scopes.Phone, OpenIddictConstants.Permissions.Scopes.Address, OpenIddictConstants.Permissions.Prefixes.Scope + "openid", OpenIddictConstants.Permissions.Prefixes.Scope + "offline_access", OpenIddictConstants.Permissions.Prefixes.Scope + "groups", OpenIddictConstants.Permissions.Prefixes.Scope + "roles", OpenIddictConstants.Permissions.ResponseTypes.Code }, RedirectUris = { new Uri(TestRedirectUri) }, Requirements = { OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange } }); // Public PKCE client — no secret await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = TestClientIdPublic, ClientType = OpenIddictConstants.ClientTypes.Public, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "Integration Test PKCE Client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.Endpoints.Revocation, OpenIddictConstants.Permissions.Endpoints.DeviceAuthorization, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.GrantTypes.RefreshToken, OpenIddictConstants.Permissions.GrantTypes.DeviceCode, OpenIddictConstants.Permissions.Prefixes.Scope + "openid", OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Email, OpenIddictConstants.Permissions.Scopes.Phone, OpenIddictConstants.Permissions.Scopes.Address, OpenIddictConstants.Permissions.Prefixes.Scope + "offline_access", OpenIddictConstants.Permissions.Prefixes.Scope + "groups", OpenIddictConstants.Permissions.Prefixes.Scope + "roles", OpenIddictConstants.Permissions.ResponseTypes.Code }, RedirectUris = { new Uri(TestRedirectUri) }, Requirements = { OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange } }); // The confidential client is the public client's backend: it introspects and revokes // the tokens the PKCE client obtains, so it must be an audience of them. Access tokens // carry `aud` now (RFC 9068), and OpenIddict admits only audience members to // introspection (RFC 7662) — the relationship has to be declared, not assumed. await WithRedb(async redb => { var publicApp = await redb.GetByUniqueAsync(p => p.ClientId, TestClientIdPublic); publicApp!.Props.AccessTokenAudiences = [TestClientId]; await redb.SaveAsync(publicApp); }); } private async Task SeedTestUser() { // Try to find existing user in _users table var coreUser = await Redb.UserProvider.GetUserByLoginAsync(TestUsername); if (coreUser is null) { // Create user in _users table coreUser = await Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = TestUsername, Password = TestPassword, Name = TestUsername, Email = "testuser@example.com", Phone = "+1234567890", Enabled = true }); } TestUserId = coreUser.Id; // Ensure OIDC profile extension exists (linked via key = _users._id) var oidcObj = await Redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync(); if (oidcObj is null) { oidcObj = new RedbObject(new UserProps()); oidcObj.name = TestUsername; oidcObj.key = coreUser.Id; oidcObj.value_guid = Guid.NewGuid(); } else if (oidcObj.value_guid is null || oidcObj.value_guid == Guid.Empty) { // First test run after migration may find a row without value_guid — backfill it. oidcObj.value_guid = Guid.NewGuid(); } TestSubjectGuid = oidcObj.value_guid!.Value; oidcObj.Props.EmailVerified = true; oidcObj.Props.GivenName = "Test"; oidcObj.Props.FamilyName = "User"; oidcObj.Props.PhoneNumberVerified = false; oidcObj.Props.Address = new AddressClaim { StreetAddress = "123 Test Street", Locality = "Testville", Region = "TS", PostalCode = "12345", Country = "US" }; oidcObj.Props.CustomClaims = new Dictionary { ["department"] = "Engineering", ["employee_id"] = "EMP-0042" }; await Redb.SaveAsync(oidcObj); } public async Task Request(string endpointUri, object body) { return await Producer.RequestBody(endpointUri, body); } /// /// Sends an authorize request with the test user's session pre-attached. /// Creates a session record (simulating login) and sets session_id header. /// public async Task RequestWithSession(string endpointUri, object body) { // Create a session record (simulates what LoginProcessor does at login time). // Goes through WithRedb so SessionService.CreateAsync owns a fresh NpgsqlConnection // for the BeginTransaction → SaveAsync chain — captive _fx.Redb is racy here // because callers (e.g. SessionIntegrationTests.ManageSessions_RevokeAll_*) chain // multiple Authorize() calls back-to-back; the previous call's WireTap audit // pipeline can still be flushing INSERTs onto the captive connection when the // next call's SessionService.CreateAsync arrives, surfacing as // "InvalidOperationException : Connection is busy" at BeginTransactionAsync. var session = await WithRedb(async redb => { var sessionService = new SessionService(redb); return await sessionService.CreateAsync(TestUserId, applicationObjectId: 0); }); var headers = new Dictionary { ["session_user_id"] = TestUserId, ["session_username"] = TestUsername, ["session_id"] = session.id }; var exchange = await RequestWithHeaders(endpointUri, body, headers); return exchange.HasOut ? exchange.Out!.Body : exchange.In.Body; } public async Task RequestWithHeaders( string endpointUri, object? body, IDictionary headers, ManagementCaller caller = ManagementCaller.Admin) { var message = new Message { Body = body }; foreach (var (key, value) in headers) message.Headers[key] = value; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOut }; // This fixture plays the facade: the core management routes refuse an exchange without a // management context, so say which caller we are. Admin unless the test probes the gate. ManagementCallerContext.Apply(exchange, caller); var endpoint = _ctx.GetEndpoint(endpointUri); var producer = endpoint.CreateProducer(); await producer.Process(exchange); // Identity convention: business processors write the response into exchange.In.Body // and PipelineProcessor (Camel-compliant) does not synthesise Out from In. Tests // historically read exchange.Out?.Body directly, so normalise Out := copy-of-In here. // Pure test-side adaptor; runtime contract (Out ?? In) is unchanged. NormalizeOutFromIn(exchange); return exchange; } private static void NormalizeOutFromIn(Exchange exchange) { if (exchange.Out is not null) return; var inMsg = exchange.In; if (inMsg is null) return; var outMsg = new Message { Body = inMsg.Body, ContentType = inMsg.ContentType }; foreach (var (k, v) in inMsg.Headers) outMsg.Headers[k] = v; exchange.Out = outMsg; } } [CollectionDefinition("ProductionBootstrap")] public class ProductionBootstrapCollection : ICollectionFixture; Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/ProductionHttpFixture.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/Infrastructure/ProductionHttpFixture.cs ---- using System.Net; using System.Net.Sockets; using System.Text.Json; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Validation; using redb.Core; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Core.Models.Entities; using redb.Core.Query; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.DataProtection; using redb.Identity.Contracts.Configuration; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Routes.Processors; using Microsoft.AspNetCore.DataProtection; using redb.Identity.Core.Services; using redb.Identity.Http.Security; using redb.Identity.Http; using redb.Postgres.Pro.Extensions; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Http; using Xunit; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Infrastructure; /// /// Full-stack integration fixture: PRODUCTION OpenIddict (real stores, no degraded mode) /// + real PostgreSQL + Kestrel HTTP on a random port. /// Validates the complete path: HTTP → controller → route → OpenIddict pipeline → redb stores → PostgreSQL. /// public sealed class ProductionHttpFixture : IAsyncLifetime { private ServiceProvider _sp = null!; private RouteContext _ctx = null!; /// The named redb instance the routes use, as a deployment's context.json names one. public const string RouteRedbName = "identity-e2e"; public const string TestClientId = "e2e-confidential"; public const string TestClientSecret = "e2e-secret-value-1234"; public const string TestPublicClientId = "e2e-public-pkce"; public const string TestMgmtClientId = "e2e-management"; public const string TestMgmtSecret = "e2e-mgmt-secret-1234"; public const string TestConsentClientId = "e2e-explicit-consent"; public const string TestUsername = "e2e-user"; public const string TestPassword = "E2E@Test123!"; public const string TestRedirectUri = "http://localhost/callback"; public const string DynamicRegAccessToken = "e2e-dynreg-initial-token-2026"; // Scope-authorization fixtures: a gated scope ("identity:admin") and a group // ("identity-admins") that user-bound flows must belong to in order to obtain // the gated scope. Configured via RedbIdentityOptions.ScopeRequiredGroups. public const string AdminGatedScope = "identity:admin"; public const string AdminGroupName = "identity-admins"; public const string TestAdminUsername = "e2e-admin"; public const string TestAdminPassword = "E2E@Admin123!"; // B1 — bootstrap-admin emergency endpoint. Tests in BootstrapAdminTests // toggle this on the live options instance and clean state per test. public const string BootstrapSecret = "test-bootstrap-secret-XYZ-32-chars-long-aaa"; // Bootstrap-suite isolated client_id. Was "identity-web" — same value as the // default SeedWebClientOptions.ClientId — and collided with anything in the // fixture lifetime that happened to seed "identity-web" (an earlier explicit // SeedWebClient run, a stale OpenIddict cache entry surviving a half-cleanup, // an unrelated test class that touched the same client). Even with the seed // turned off the collisions kept reappearing under the full-suite run because // they only required ONE stale entry across the entire xUnit fixture lifetime. // Using a unique value here removes the variable: nothing else in the codebase // refers to "bootstrap-admin-test-client", so the bootstrap tests own the // lifecycle of this client_id end-to-end. public const string BootstrapWebClientId = "bootstrap-admin-test-client"; public const string BootstrapAdminScope = "identity:admin-bootstrap-test"; public const string BootstrapAdminGroup = "identity-bootstrap-admins"; /// /// The one external audit target of this fixture, a direct-vm consumer in the fixture's own context: /// it sees exactly what Kafka, AMQP, a log endpoint or a consumer module would receive. /// public const string AuditTargetUri = "direct-vm://identity-test-audit-target"; /// What reached : each message's headers and its body as text. public System.Collections.Concurrent.ConcurrentQueue<(Dictionary Headers, string Body)> AuditTargetMessages { get; } = new(); private static IdentityAuditOptions AuditOptions() => new() { Enabled = true, Filter = "*", PersistToProps = true, Targets = [new AuditTarget { Name = "test-capture", Enabled = true, Uri = AuditTargetUri }] }; /// The audit targets of this fixture, as a delivery worker built by a test must know them. public IReadOnlyList AuditTargets { get; } = AuditOptions().Targets; private redb.Identity.Core.Routes.Processors.WebhookDeliveryWorker? _outboxWorker; /// /// Delivery worker passes over the outbox until a pass finds nothing due, waiting for what they /// started. The fixture's own timer worker is off (Delivery.PollInterval is infinite), so a test that /// expects a delivery runs this. Every event of every test leaves an audit-target row, so the limits are /// wide enough to clear that backlog quickly. /// public async Task DeliverOutboxAsync() { _outboxWorker ??= new redb.Identity.Core.Routes.Processors.WebhookDeliveryWorker( _sp, _ctx, new DeliveryOptions { BatchSize = 500, MaxParallel = 50, MaxParallelPerDestination = 50 }, TimeProvider.System, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, node: null, auditTargets: AuditTargets); for (var pass = 0; pass < 200; pass++) { var started = await _outboxWorker.RunOnceAsync(); await _outboxWorker.DrainAsync(); if (started == 0) return; } } public int Port { get; private set; } public string BaseUrl => $"http://localhost:{Port}"; public HttpClient Http { get; private set; } = null!; /// /// N-4 (Session C): captures every transactional e-mail dispatched by the identity /// system. Tests use this to extract reset tokens and to assert that anti-enumeration /// gates correctly suppress delivery. /// public InMemoryEmailNotificationChannel Emails => _sp.GetRequiredService(); public ProducerTemplate Producer { get; private set; } = null!; /// /// CAPTIVE — uses a single IRedbService resolved from the root provider, which means a /// single underlying NpgsqlConnection. Do NOT use from tests for ad-hoc reads/writes that /// can run in parallel with HTTP requests, OpenIddict pipeline work, or audit-sink fan-out /// — they will collide with "A command is already in progress" / "state 'Copy'". /// Use instead, which opens a fresh DI scope per call so each /// operation gets its own connection. /// /// Kept here only because (a) initial seed / schema-sync runs strictly serial during /// , and (b) some legacy tests still reach for it. New tests /// MUST go through . /// /// /// /// Per-call scoped . Each access opens a fresh DI scope from the /// fixture so the resolved uses its /// own NpgsqlConnection from the pool. Scopes are tracked in /// and disposed during . This keeps backwards compatibility with /// legacy tests that capture _fx.Redb into ad-hoc service objects (e.g. new /// ConsentService(_fx.Redb)) while removing the captive-singleton race that otherwise /// surfaces as NpgsqlOperationInProgressException ("command already in progress" / /// state 'Copy'). /// /// New tests SHOULD prefer when possible — it gives the scope a /// short, deterministic lifetime instead of leaking until fixture teardown. /// /// /// IMPORTANT: do NOT use this for explicit transactions — each access returns a different /// instance bound to a different connection. Use /// with a single delegate for transactional work. /// /// [Obsolete("Prefer UseRedbAsync(...) — _fx.Redb returns a single fixture-scoped IRedbService that shares one NpgsqlConnection; safe only for sequential test-side reads/writes.")] public IRedbService Redb { get { // Lazily create ONE long-lived DI scope and resolve a single IRedbService from it. // Previous implementation created a new scope per access and stashed it in a bag // that was only drained at fixture teardown — leaking one NpgsqlConnection per // access and exhausting the pool (200) within a single full-suite run. // Tests that need their own connection MUST use UseRedbAsync(...) which scopes // properly per delegate. if (_captiveRedb is not null) return _captiveRedb; lock (_captiveRedbLock) { if (_captiveRedb is null) { _captiveScope = _sp.CreateAsyncScope(); _captiveRedb = _captiveScope.Value.ServiceProvider.GetRequiredService(); } return _captiveRedb; } } } private readonly object _captiveRedbLock = new(); private AsyncServiceScope? _captiveScope; private IRedbService? _captiveRedb; public IServiceProvider ServiceProvider => _sp; /// The route context of the stack, for tests that drive a route-side worker themselves. public redb.Route.Core.RouteContext Context => _ctx; /// /// Opens a fresh DI scope, resolves a per-scope (and therefore a /// fresh NpgsqlConnection) and runs the supplied against it. /// The scope (and its connection) is disposed when the action completes, even on exception. /// This is the safe pattern for any test-side database access in the production HTTP fixture /// — it avoids the captive-singleton race that otherwise serialises everything onto one /// connection and surfaces as NpgsqlOperationInProgressException. /// public async Task UseRedbAsync(Func action) { ArgumentNullException.ThrowIfNull(action); await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); await action(redb).ConfigureAwait(false); } /// /// Like but with a return value. /// public async Task UseRedbAsync(Func> action) { ArgumentNullException.ThrowIfNull(action); await using var scope = _sp.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); return await action(redb).ConfigureAwait(false); } /// /// Bearer token with identity:manage scope for management API calls. /// public string ManagementToken { get; private set; } = null!; /// /// Bearer token with scim scope for SCIM provisioning API calls. /// public string ScimToken { get; private set; } = null!; public async Task InitializeAsync() { Port = GetFreePort(); var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var cs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); // Real PostgreSQL + Pro with DeleteInsert services.AddRedbForTests(cs); services.AddSingleton(); // Identity options — production mode var identityOptions = new RedbIdentityOptions { TokenRetentionDays = 30, TokenThrottleMaxPerPeriod = 1000, TokenThrottlePeriod = TimeSpan.FromSeconds(1), Issuer = new Uri($"http://localhost:{Port}/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true, // Enable conditional features for E2E testing Features = new IdentityFeatureFlags { EnableDynamicRegistration = true, EnableDeviceCodeFlow = true, EnableScim = true, EnableScimBulk = true, EnablePushedAuthorization = true, }, DynamicRegistrationInitialAccessToken = DynamicRegAccessToken, DynamicRegistrationAllowedGrantTypes = ["authorization_code", "refresh_token", "client_credentials"], // Bump DCR throttle so a long-running test suite (~11 DCR tests in this // collection alone) does not stall on the per-IP window. DynamicRegistrationThrottleMaxPerPeriod = 1000, DynamicRegistrationThrottlePeriod = TimeSpan.FromSeconds(1), EnablePasswordFlow = true, // Scope-authorization gate (B0.1): user-bound token requests for // "identity:admin" must belong to group "identity-admins". // client_credentials flows are unaffected (no user identity). ScopeRequiredGroups = new(StringComparer.Ordinal) { [AdminGatedScope] = AdminGroupName }, // Z4: enable DPoP in soft mode — clients opt-in by sending the header. Dpop = new DpopOptions { Enabled = true, RequireForAccessTokens = false, }, // Disable the MFA OTP cleanup timer to avoid background interference in tests. MfaOtpCleanupInterval = System.Threading.Timeout.InfiniteTimeSpan, }; // N-3 (sub-step N3-7): enable self-service registration so FullStackAccountRegistrationTests // can exercise the public /api/v1/identity/account/register endpoint. The feature gate // defaults to OFF; flipping it on here is harmless to other tests in this collection // (none of them touch the register route or the AccountRegister direct-vm). identityOptions.Registration.Enabled = true; // B1 — enable the emergency-admin bootstrap endpoint with a known secret. // The endpoint is mounted unconditionally; the processor short-circuits on // the Enabled flag. Tests in BootstrapAdminTests clean the bootstrap_completed // sentinel + identity-web client between cases so each test sees pristine state. identityOptions.Bootstrap.Enabled = true; identityOptions.Bootstrap.Secret = BootstrapSecret; identityOptions.Bootstrap.WebClientId = BootstrapWebClientId; identityOptions.Bootstrap.AdminScope = BootstrapAdminScope; identityOptions.Bootstrap.AdminGroupName = BootstrapAdminGroup; // SeedWebClientHostedService.OnContextStarting seeds an OIDC client with the // default ClientId "identity-web", which is identical to BootstrapWebClientId. // The seed runs once at fixture startup; CleanupBootstrapStateAsync removes // the row before each test, but in practice the row keeps coming back via // a stale higher-level cache entry, so every "first call" test sees the // pre-seeded client and returns 409 (duplicate). Disabling the seed here lets // the bootstrap tests own the lifecycle of the canonical client end-to-end // — the only fixture in the suite that actually exercises that lifecycle. identityOptions.SeedWebClient.Enabled = false; // Webhook deliveries go through the outbox. The timer is off here: the webhook tests run the // delivery worker themselves (DeliverPendingAsync), so what a test asserts never races a pass. identityOptions.Delivery.PollInterval = System.Threading.Timeout.InfiniteTimeSpan; // The jwks_uri tests serve client keys from a loopback listener over http, and rotate them within a test: // the guard's private-target and https rules are relaxed here only, and one refresh may follow per second. identityOptions.ClientKeys.AllowPrivateNetworkTargets = true; identityOptions.ClientKeys.RequireHttps = false; identityOptions.ClientKeys.MinimumRefreshInterval = TimeSpan.FromSeconds(1); // The back-channel logout tests receive on a loopback listener over http. identityOptions.BackchannelLogout.AllowPrivateNetworkTargets = true; identityOptions.BackchannelLogout.RequireHttps = false; services.AddSingleton(Options.Create(identityOptions)); // H6/H7/H9: enable audit + PROPS persistence so e2e protocol tests can assert audit emission. services.AddSingleton(Options.Create(AuditOptions())); // HTTP transport options. Features instance is *shared* with the Core options // — single source of truth keeps Core (DI / direct-vm gating) and Http (route // mounting) in lockstep, mirroring the Identity:Features:* shared section in // production context.json. var transportOptions = new IdentityTransportOptions(); transportOptions.Http.PublicPort = Port; // Loopback only: a test listener on every interface makes the OS firewall ask about each new // test binary path. transportOptions.Http.Host = "localhost"; // Single-instance shared section (Issuer + Features) — replaces the // previous per-property mirror. Mirrors the architectural invariant // that Issuer and Features are bound from one Identity:* section in // context.json. transportOptions.Shared = identityOptions.Shared; services.AddSingleton(Options.Create(transportOptions)); // *** PRODUCTION bootstrap — real OpenIddict stores + pipeline *** services.AddRedbIdentityServer(identityOptions); // The password history store refuses, inside a route transaction, the calls that open a connection of // their own: a deployment promotes such a transaction to a distributed one, which stock PostgreSQL refuses. services.AddSingleton(); services.AddSingleton(sp => new InRouteTransactionHistoryStoreGuard(sp.GetRequiredService())); // N-4 (Session C): capture transactional e-mails in memory so tests can assert // delivery + extract reset tokens. Registered AFTER AddRedbIdentityServer because // Core leaves IEmailNotificationChannel unbound by default (production hosts pick // SMTP / SendGrid). We register the concrete type as a singleton and expose it via // the interface so the channel implementation and the test-side captured-message // reader share one instance. services.AddSingleton(sp => new InMemoryEmailNotificationChannel(sp.GetRequiredService())); services.AddSingleton( sp => sp.GetRequiredService()); // TODO: enable ValidateScopes=true here once the fixture's _sp.GetRequiredService<> // calls below + the captive `public IRedbService Redb` field are reworked to use a // dedicated init scope and a per-call scope helper. ASP.NET Core does this in // Development by default and it would surface captive-singleton bugs at resolve // time instead of letting them silently serialize concurrent requests onto a // single NpgsqlConnection (see DisableEntityCaching + per-exchange resolve fix). _sp = services.BuildServiceProvider(); // Initialize PostgreSQL schema. The init / schema-sync / seed phase runs strictly // serial here on a single dedicated DI scope (one connection from the pool) — no // concurrent HTTP traffic exists yet (HttpComponent is started below). await using (var initScope = _sp.CreateAsyncScope()) { var initRedb = initScope.ServiceProvider.GetRequiredService(); try { await initRedb.InitializeAsync(ensureCreated: true); } catch (Exception ex) { Console.Error.WriteLine($"InitializeAsync(ensureCreated:true) failed, falling back: {ex.GetType().Name}: {ex.Message}"); await initRedb.InitializeAsync(); } await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); // R1: AuditEventProps removed — identity_audit_log is now a flat // relational table created by IdentityAuditLogTableInitListener // (not via props scheme sync). // H5: ClaimMapper schemes — required by AttachClaimMapperClaims handler in the // OpenIddict ProcessSignInContext pipeline. Without these the resolver query // would throw at every token issuance. await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); await initRedb.SyncSchemeAsync(); await initRedb.InitializeTypeRegistryAsync(); } // Fix btree index overflow for large Payload values (4+ scope tokens) await IndexFixHelper.FixValueStringIndexAsync(cs); // Seed test data via OpenIddict managers (BCrypt-hashed secrets) await SeedTestClients(); await SeedTestUser(); await SeedAdminUserAndGroup(); // Create RouteContext with HTTP _ctx = new RouteContext(_sp, "production-http-e2e"); // The host trusts its own loopback peer as a reverse proxy, so a test can play the TLS // terminator: send X-Forwarded-Proto / X-Forwarded-For and the facade sees the client's // origin the way it would behind nginx. Requests without those headers are untouched. var hosting = new HttpHostingOptions(); hosting.TrustedProxies.Add("127.0.0.1").Add("::1"); _ctx.AddComponent(new HttpComponent { ServerManager = new SharedHttpServerManager(hosting) }); // Bearer auth processors live in Core's RouteBuilder so they get exposed as // `direct-vm://identity-auth-{management,scim}` consumers; the HTTP facade // calls them inline via .To(...). var validationScopes = _sp.GetRequiredService(); var managementAuth = new ManagementBearerAuthProcessor( validationScopes, // The same set InitRoute builds for a deployment: the master scope, self-service and every granular // admin scope; the scope table decides per path what a granular token reaches. new[] { identityOptions.ManagementScope, identityOptions.AccountScope }.Concat(IdentityScopes.GranularAdmin).ToArray(), anonymousPathPrefixes: new[] { "/api/v1/identity/password/", "/api/v1/identity/account/" }); IProcessor? scimAuth = identityOptions.Features.EnableScim ? new ManagementBearerAuthProcessor(validationScopes, identityOptions.ScimScope) : null; // A deployment names its redb instance (context.json RedbInstanceName), and only then do the mutating // routes run in a route transaction (WithRedbTx). Without the name this host ran every route without one, // so nothing here could show what happens inside it. identityOptions.RedbInstanceName = RouteRedbName; redb.Route.RedbCore.Extensions.RedbRouteExtensions.RegisterRedbService(_ctx, RouteRedbName, _sp.GetRequiredService()); _ctx.AddRoutes(new IdentityCoreRouteBuilder(_sp, Options.Create(identityOptions), Options.Create(AuditOptions()), managementAuth, scimAuth)); _ctx.AddRoutes(new AuditTargetCapture(AuditTargetMessages)); _ctx.AddRoutes(new HttpFacadeRouteBuilder( new SessionTicketService(_sp.GetRequiredService()), Options.Create(transportOptions), // Phase 9e: post_logout_redirect_uri validator routes through the // direct-vm broker registered by IdentityCoreRouteBuilder. Without this // the facade's validator delegate stays null → every logout falls back // to the "Signed Out" page, even for registered URIs. new redb.Identity.Http.Endpoints.BrokeredPostLogoutRedirectValidator(_ctx))); // identity_audit_log is a flat relational table created by // IdentityAuditLogTableInitListener (registered by Core/Module InitRoute // in tpkg deployments). The fixture builds its own RouteContext and // skips that path — register the listener directly so the table is // ensured on every provider. Without this, Postgres tests pass only // because earlier runs persisted the table; SQLite gets a fresh temp // file per call and sees "no such table: identity_audit_log". _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityAuditLogTableInitListener(_sp)); _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityDeliveryOutboxInitListener(_sp)); // The same goes for UX_users_email, the unique index that makes concurrent registrations of // one e-mail lose with 409: a deployment gets it from InitRoute.main, this context does not // call it. Without the listener the index existed only where an earlier run had left it, and // on a fresh database every concurrent registration of one address succeeded. _ctx.AddLifecycleListener(new redb.Identity.Core.Module.IdentityUniqueIndexesInitListener(_sp)); await _ctx.Start(); Producer = new ProducerTemplate(_ctx); Producer.Start(); Http = new HttpClient { BaseAddress = new Uri(BaseUrl) }; ManagementToken = await ObtainManagementTokenAsync(); ScimToken = await ObtainScimTokenAsync(); } public async Task DisposeAsync() { Http.Dispose(); Producer.Stop(); Producer.Dispose(); // Dispose the single captive scope (if Redb was ever accessed). Each scope owns an // NpgsqlConnection borrowed from the pool; without explicit disposal it would only // return to the pool when _sp itself is disposed, which can race with in-flight // commands and surface as NpgsqlOperationInProgressException during teardown. if (_captiveScope is { } captive) { try { await captive.DisposeAsync().ConfigureAwait(false); } catch (Exception ex) { Console.Error.WriteLine( $"[ProductionHttpFixture] captive-scope.DisposeAsync() threw: {ex.GetType().Name}: {ex.Message}"); } _captiveScope = null; _captiveRedb = null; } // Bound the route-context teardown to a short timeout so a misbehaving processor // (one that doesn't honour cancellation in its disposal path) cannot wedge the // entire test host. Without this, blame-collector trips after 3 minutes and the // run is aborted before later collections / dispose hooks complete. Best-effort: // if a route is genuinely stuck we leak it for the lifetime of the test process, // which is acceptable in a teardown path. try { using var ctsCtx = new CancellationTokenSource(TimeSpan.FromSeconds(15)); var disposeCtx = _ctx.DisposeAsync().AsTask(); var winner = await Task.WhenAny(disposeCtx, Task.Delay(Timeout.Infinite, ctsCtx.Token)); if (winner != disposeCtx) { Console.Error.WriteLine( "[ProductionHttpFixture] _ctx.DisposeAsync() did not complete within 15s; continuing teardown."); } else { await disposeCtx; } } catch (OperationCanceledException) { /* timeout — leak */ } catch (Exception ex) { Console.Error.WriteLine($"[ProductionHttpFixture] _ctx.DisposeAsync() threw: {ex.GetType().Name}: {ex.Message}"); } try { using var ctsSp = new CancellationTokenSource(TimeSpan.FromSeconds(10)); var disposeSp = _sp.DisposeAsync().AsTask(); var winner = await Task.WhenAny(disposeSp, Task.Delay(Timeout.Infinite, ctsSp.Token)); if (winner != disposeSp) { Console.Error.WriteLine( "[ProductionHttpFixture] _sp.DisposeAsync() did not complete within 10s; continuing teardown."); } else { await disposeSp; } } catch (OperationCanceledException) { /* timeout — leak */ } catch (Exception ex) { Console.Error.WriteLine($"[ProductionHttpFixture] _sp.DisposeAsync() threw: {ex.GetType().Name}: {ex.Message}"); } } private async Task SeedTestClients() { var manager = _sp.GetRequiredService(); foreach (var clientId in new[] { TestClientId, TestPublicClientId, TestMgmtClientId, TestConsentClientId }) { var existing = await manager.FindByClientIdAsync(clientId); if (existing is not null) await manager.DeleteAsync(existing); } // Confidential client — client_credentials + auth_code + refresh + introspect + revoke + password await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = TestClientId, ClientSecret = TestClientSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "E2E Confidential Client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.Endpoints.Introspection, OpenIddictConstants.Permissions.Endpoints.Revocation, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.GrantTypes.RefreshToken, OpenIddictConstants.Permissions.GrantTypes.Password, OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Email, OpenIddictConstants.Permissions.Scopes.Phone, OpenIddictConstants.Permissions.Prefixes.Scope + "openid", OpenIddictConstants.Permissions.Prefixes.Scope + "offline_access", OpenIddictConstants.Permissions.Prefixes.Scope + "groups", OpenIddictConstants.Permissions.Prefixes.Scope + "roles", OpenIddictConstants.Permissions.Prefixes.Scope + AdminGatedScope, OpenIddictConstants.Permissions.ResponseTypes.Code }, RedirectUris = { new Uri(TestRedirectUri) }, PostLogoutRedirectUris = { new Uri(TestRedirectUri) }, Requirements = { OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange } }); // Public PKCE client (+ device code flow) await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = TestPublicClientId, ClientType = OpenIddictConstants.ClientTypes.Public, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "E2E Public PKCE Client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.Endpoints.DeviceAuthorization, OpenIddictConstants.Permissions.Endpoints.PushedAuthorization, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.GrantTypes.RefreshToken, OpenIddictConstants.Permissions.GrantTypes.DeviceCode, OpenIddictConstants.Permissions.Prefixes.Scope + "openid", OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Email, OpenIddictConstants.Permissions.Prefixes.Scope + "offline_access", // W6-debt: allow self-service /me/* endpoints to be exercised end-to-end // through the same public PKCE client (auth code flow → token with sid). OpenIddictConstants.Permissions.Prefixes.Scope + "identity:account", OpenIddictConstants.Permissions.ResponseTypes.Code }, RedirectUris = { new Uri(TestRedirectUri) }, Requirements = { OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange } }); // Management client — client_credentials + identity:manage scope await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = TestMgmtClientId, ClientSecret = TestMgmtSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "E2E Management Client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Introspection, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.Prefixes.Scope + "identity:manage", OpenIddictConstants.Permissions.Prefixes.Scope + AdminGatedScope, OpenIddictConstants.Permissions.Prefixes.Scope + "scim" } }); // Explicit consent client — requires user consent page await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = TestConsentClientId, ClientType = OpenIddictConstants.ClientTypes.Public, ConsentType = OpenIddictConstants.ConsentTypes.Explicit, DisplayName = "E2E Explicit Consent App", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.Prefixes.Scope + "openid", OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Email, OpenIddictConstants.Permissions.ResponseTypes.Code }, RedirectUris = { new Uri(TestRedirectUri) }, Requirements = { OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange } }); } private async Task SeedTestUser() { // Try to find existing user in _users table var coreUser = await Redb.UserProvider.GetUserByLoginAsync(TestUsername); if (coreUser is null) { // Create user in _users table coreUser = await Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = TestUsername, Password = TestPassword, Name = TestUsername, Email = "e2e@example.com", Phone = "+1999888777", Enabled = true }); } // Ensure OIDC profile extension exists (linked via key = _users._id) var oidcObj = await Redb.Query() .WhereRedb(o => o.Key == coreUser.Id) .FirstOrDefaultAsync(); if (oidcObj is null) { oidcObj = new RedbObject(new UserProps()); oidcObj.name = TestUsername; oidcObj.key = coreUser.Id; oidcObj.value_guid = Guid.NewGuid(); } oidcObj.Props.EmailVerified = true; oidcObj.Props.GivenName = "E2E"; oidcObj.Props.FamilyName = "Tester"; oidcObj.Props.PhoneNumberVerified = true; await Redb.SaveAsync(oidcObj); } /// /// Seed admin user () and add to group /// . Used to exercise the /// RestrictScopeByGroupMembershipHandler via password grant. /// private async Task SeedAdminUserAndGroup() { // Admin user var adminUser = await Redb.UserProvider.GetUserByLoginAsync(TestAdminUsername); if (adminUser is null) { adminUser = await Redb.UserProvider.CreateUserAsync(new redb.Core.Models.Users.CreateUserRequest { Login = TestAdminUsername, Password = TestAdminPassword, Name = TestAdminUsername, Email = "e2e-admin@example.com", Phone = "+1999000111", Enabled = true }); } // OIDC props (required for token issuance — password flow loads them) var adminOidc = await Redb.Query() .WhereRedb(o => o.Key == adminUser.Id) .FirstOrDefaultAsync(); if (adminOidc is null) { adminOidc = new RedbObject(new UserProps()); adminOidc.name = TestAdminUsername; adminOidc.key = adminUser.Id; adminOidc.value_guid = Guid.NewGuid(); } adminOidc.Props.EmailVerified = true; adminOidc.Props.GivenName = "E2E"; adminOidc.Props.FamilyName = "Admin"; adminOidc.Props.PhoneNumberVerified = true; await Redb.SaveAsync(adminOidc); // Admin group — ensure exists, idempotent across fixture re-runs var groupService = new redb.Identity.Core.Services.GroupService(Redb); var existingGroup = await Redb.Query() .WhereRedb(o => o.Name == AdminGroupName) .FirstOrDefaultAsync(); long groupId; if (existingGroup is null) { var created = await groupService.CreateGroupAsync(AdminGroupName, "role", "Admin role group"); groupId = created.Id; } else { groupId = existingGroup.Id; } // Membership — silently skip if already present (re-runs) var alreadyMember = await Redb.Query() .WhereRedb(o => o.Key == adminUser.Id && o.ParentId == groupId) .FirstOrDefaultAsync(); if (alreadyMember is null) { await groupService.AddMemberAsync(groupId, adminUser.Id, role: "admin"); } } private async Task ObtainManagementTokenAsync() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = TestMgmtClientId, ["client_secret"] = TestMgmtSecret, ["scope"] = "identity:manage" }); var response = await Http.PostAsync("/connect/token", content); if (!response.IsSuccessStatusCode) { var error = await response.Content.ReadAsStringAsync(); throw new InvalidOperationException( $"Management token request failed ({response.StatusCode}): {error}"); } var json = await JsonSerializer.DeserializeAsync( await response.Content.ReadAsStreamAsync()); return json.GetProperty("access_token").GetString() ?? throw new InvalidOperationException("Missing access_token in response"); } private async Task ObtainScimTokenAsync() { var content = new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = TestMgmtClientId, ["client_secret"] = TestMgmtSecret, ["scope"] = "scim" }); var response = await Http.PostAsync("/connect/token", content); if (!response.IsSuccessStatusCode) { var error = await response.Content.ReadAsStringAsync(); throw new InvalidOperationException( $"SCIM token request failed ({response.StatusCode}): {error}"); } var json = await JsonSerializer.DeserializeAsync( await response.Content.ReadAsStreamAsync()); return json.GetProperty("access_token").GetString() ?? throw new InvalidOperationException("Missing access_token in response"); } private static int GetFreePort() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); int port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } } [CollectionDefinition("ProductionHttp")] public class ProductionHttpCollection : ICollectionFixture; /// The consumer behind . internal sealed class AuditTargetCapture( System.Collections.Concurrent.ConcurrentQueue<(Dictionary Headers, string Body)> sink) : RouteBuilder { protected override void Configure() { From(ProductionHttpFixture.AuditTargetUri) .RouteId("identity-test-audit-target") .Process(e => { var body = e.In.Body switch { byte[] bytes => System.Text.Encoding.UTF8.GetString(bytes), string text => text, null => string.Empty, var other => JsonSerializer.Serialize(other), }; sink.Enqueue((new Dictionary(e.In.Headers), body)); }); } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/PropsSigningKeyStoreFixture.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/Infrastructure/PropsSigningKeyStoreFixture.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using redb.Core; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Keys; using redb.Identity.Core.Models; using redb.Identity.Core.Routes; using redb.Identity.DataProtection; using redb.Route.Components; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Infrastructure; /// /// The production key path, end to end: OpenIddict fed from the redb-backed /// , no ephemeral keys. /// /// Every other fixture runs on ephemeral keys, which is the right default for tests that are about /// something else — but it means rotation and retirement never met a real token pipeline in the suite. /// This fixture is for exactly that: mint here, rotate and retire through the store, and ask the same /// server and validation stacks whether the token still holds. Access-token encryption is off so the /// token is a plain JWS and its kid can be read back, which turns "which key signed this" from an /// inference into an assertion. /// /// /// Own client, own context: nothing here is shared with , so the /// two never reseed each other's data. /// /// public sealed class PropsSigningKeyStoreFixture : IAsyncLifetime { public const string ClientId = "signing-keys-e2e-client"; public const string ClientSecret = "signing-keys-e2e-secret"; public const string Scope = "openid"; private ServiceProvider _sp = null!; private RouteContext _ctx = null!; public IServiceProvider ServiceProvider => _sp; public ISigningKeyStore Store => _sp.GetRequiredService(); public ProducerTemplate Producer { get; private set; } = null!; public async Task InitializeAsync() { var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var cs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenRetentionDays = 30, TokenThrottleMaxPerPeriod = 1000, TokenThrottlePeriod = TimeSpan.FromSeconds(1), Issuer = new Uri("https://identity.keys.test.local/"), // The point of this fixture: persistent keys from the store, nothing ephemeral to fall back on. UsePropsSigningKeyStore = true, AllowEphemeralKeys = false, // Plain JWS access tokens, so a test can read the kid that signed them. DisableAccessTokenEncryption = true, // Without ephemeral keys the key ring must be protected at rest, as in production. A fixed test // master key: the ring only ever holds this fixture's keys. DataProtection = new DataProtectionOptions { MasterKey = Convert.ToBase64String(Enumerable.Range(1, 32).Select(i => (byte)i).ToArray()), }, }; services.AddSingleton(Options.Create(identityOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); var redb = _sp.GetRequiredService(); try { await redb.InitializeAsync(ensureCreated: true); } catch { await redb.InitializeAsync(); } await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.SyncSchemeAsync(); await redb.InitializeTypeRegistryAsync(); // What SigningKeyInitListener does in the module: both kinds, before OpenIddict first reads its // options — the post-configure that fills the credentials runs on that first read. await Store.EnsureBootstrappedAsync("signing"); await Store.EnsureBootstrappedAsync("encryption"); await SeedClient(); _ctx = new RouteContext(_sp, "identity"); _ctx.AddRoutes(new IdentityCoreRouteBuilder(_sp, Options.Create(identityOptions))); await _ctx.Start(); Producer = new ProducerTemplate(_ctx); Producer.Start(); } public async Task DisposeAsync() { if (_ctx is not null) await _ctx.DisposeAsync(); if (_sp is not null) await _sp.DisposeAsync(); } /// Sends a request to a core route and returns the answer body. public Task Request(string endpointUri, object body) => Producer.RequestBody(endpointUri, body); private async Task SeedClient() { var manager = _sp.GetRequiredService(); var existing = await manager.FindByClientIdAsync(ClientId); if (existing is not null) await manager.DeleteAsync(existing); await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = ClientId, ClientSecret = ClientSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "Signing keys E2E client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Introspection, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.Prefixes.Scope + Scope, }, }); } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/SoapIdentityFixture.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/Infrastructure/SoapIdentityFixture.cs ---- using System.Net; using System.Net.Sockets; using System.Text; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Validation; using redb.Core; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Routes; using redb.Identity.Core.Routes.Processors; using redb.Identity.Soap; using redb.Route.Components; using redb.Route.Core; using redb.Route.Soap; using Xunit; namespace redb.Identity.Tests.Infrastructure; /// /// Boots redb.Identity.Core plus the WS-Trust facade in one process against the real PostgreSQL store, /// with the production OpenIddict pipeline and a real client registry — not degraded mode. The same /// reasoning as the gRPC fixture: a degraded stack skips client validation and keeps no token store, so it /// could neither refuse a wrong secret nor make a revoked token go inactive, and a test claiming either /// would be theatre. /// /// Requests are composed as raw SOAP envelopes and posted with an ordinary HttpClient rather than through /// a generated proxy. That is deliberate: the whole point of this facade is that someone else's generator /// can talk to it, so the wire has to be the thing under test. /// /// /// TLS is off here through AllowPlaintext — the documented escape hatch for a terminated /// connection. A self-signed certificate would test our own certificate handling, not the protocol, and /// the refusal itself is covered by SoapFacadeModuleTests. /// /// public class SoapIdentityFixture : IAsyncLifetime { /// /// Last word on the server options, for fixtures that need a stack tuned differently. The base /// settings are deliberately permissive so ordinary tests never trip a limiter by accident. /// protected virtual void Tune(RedbIdentityOptions options) { } public const string ClientId = "soap-e2e-client"; public const string ClientSecret = "soap-e2e-secret"; public const string GrantedScope = "identity:manage"; private ServiceProvider _sp = null!; private RouteContext _coreContext = null!; private RouteContext _ctx = null!; private HttpClient _http = null!; public int Port { get; private set; } public IRedbService Redb { get; private set; } = null!; private const string StsPath = "/sts"; public async Task InitializeAsync() { Port = GetFreePort(); var config = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); var cs = config.GetPostgresConnectionString() ?? throw new InvalidOperationException("ConnectionStrings:Postgres not found"); var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddRedbForTests(cs); services.AddSingleton(); var identityOptions = new RedbIdentityOptions { TokenRetentionDays = 30, TokenThrottleMaxPerPeriod = 1000, TokenThrottlePeriod = TimeSpan.FromSeconds(1), Issuer = new Uri($"http://localhost:{Port}/"), AllowEphemeralKeys = true, DisableAccessTokenEncryption = true, }; Tune(identityOptions); services.AddSingleton(Options.Create(identityOptions)); var transportOptions = new IdentitySoapTransportOptions { // One shared instance, the invariant every facade fixture keeps: issuer and feature flags come // from a single section rather than being mirrored property by property. Shared = identityOptions.Shared, }; transportOptions.Soap.Host = "127.0.0.1"; transportOptions.Soap.Port = Port; transportOptions.Soap.Path = StsPath; transportOptions.Soap.Ssl = false; transportOptions.Soap.AllowPlaintext = true; services.AddSingleton(Options.Create(transportOptions)); services.AddRedbIdentityServer(identityOptions); _sp = services.BuildServiceProvider(); Redb = _sp.GetRequiredService(); try { await Redb.InitializeAsync(ensureCreated: true); } catch { await Redb.InitializeAsync(); } await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.SyncSchemeAsync(); await Redb.InitializeTypeRegistryAsync(); await SeedClient(); // Two contexts, not one — the way Tsak actually runs them. Core owns "identity", the facade owns // "identity.soap", and they meet only over direct-vm through the shared registry in DI. // // This is not tidiness. Core registers a context-wide OnException().Handled() catch-all, // and inside one shared context it also swallows the facade's own faults: a refusal would come back // as an empty envelope instead of a soap:Fault, and a fixture built that way would prove the // opposite of what production does. _coreContext = new RouteContext(_sp, "identity"); redb.Route.Abstractions.IProcessor managementAuth = new ManagementBearerAuthProcessor( _sp.GetRequiredService(), new[] { identityOptions.ManagementScope, identityOptions.AccountScope }); _coreContext.AddRoutes(new IdentityCoreRouteBuilder(_sp, Options.Create(identityOptions), auditOptions: null, managementAuth: managementAuth, scimAuth: null)); await _coreContext.Start(); _ctx = new RouteContext(_sp, "identity.soap"); _ctx.AddComponent(new SoapComponent()); _ctx.AddRoutes(new SoapFacadeRouteBuilder(Options.Create(transportOptions))); await _ctx.Start(); _http = new HttpClient { BaseAddress = new Uri($"http://127.0.0.1:{Port}") }; } public async Task DisposeAsync() { _http?.Dispose(); if (_ctx is not null) await _ctx.DisposeAsync(); if (_coreContext is not null) await _coreContext.DisposeAsync(); if (_sp is not null) await _sp.DisposeAsync(); } /// /// Registers the confidential client the tests authenticate as. The manager hashes the secret, which /// is what makes «a wrong secret is refused» a real assertion rather than a formality. /// private async Task SeedClient() { var manager = _sp.GetRequiredService(); var existing = await manager.FindByClientIdAsync(ClientId); if (existing is not null) await manager.DeleteAsync(existing); await manager.CreateAsync(new OpenIddictApplicationDescriptor { ClientId = ClientId, ClientSecret = ClientSecret, ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Implicit, DisplayName = "SOAP E2E client", Permissions = { OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.Introspection, OpenIddictConstants.Permissions.Endpoints.Revocation, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.Prefixes.Scope + GrantedScope, }, }); } // ── the wire ───────────────────────────────────────────── /// /// Posts a WS-Trust request and returns the raw response envelope, whatever it is. Faults come back /// as envelopes too, so a test can read the fault code rather than only observing that something /// failed. /// public async Task PostAsync(string action, string rstBody, string? username = ClientId, string? password = ClientSecret) { var envelope = BuildEnvelope(rstBody, username, password); using var content = new StringContent(envelope, Encoding.UTF8, "text/xml"); content.Headers.Add("SOAPAction", $"\"{action}\""); using var response = await _http.PostAsync(StsPath, content); return await response.Content.ReadAsStringAsync(); } /// Fetches the published contract, the way a client developer's generator would. public async Task GetWsdlAsync() => await _http.GetAsync(StsPath + "?wsdl"); /// /// A SOAP 1.1 envelope with a WS-Security UsernameToken, which is how a WS-Trust caller presents its /// client credentials. /// private static string BuildEnvelope(string rstBody, string? username, string? password) { const string wsse = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; var security = username is null ? string.Empty : $""" {username} {password} """; return $""" {security} {rstBody} """; } private static int GetFreePort() { var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start(); var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); return port; } } /// /// The same stack with the per-IP limiter turned on. Core keys that limiter on /// redbHttp.RemoteAddress, a header a SOAP request has none of on its own: the listener puts it /// there because the facade asks for EmitHttpCompatHeaders. If that bridge ever breaks the /// limiter does not fail loudly — it silently stops protecting this port, and every other test in the /// suite still passes. This fixture exists so one of them would not. /// public sealed class SoapThrottledIdentityFixture : SoapIdentityFixture { /// Requests one IP may make per minute before Core answers 429. public const int PerIpPerMinute = 3; protected override void Tune(RedbIdentityOptions options) { options.RateLimit.Enabled = true; options.RateLimit.PerIpPerMinute = PerIpPerMinute; } } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/TestExchange.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/Infrastructure/TestExchange.cs ---- using redb.Route.Abstractions; namespace redb.Identity.Tests.Infrastructure; /// /// Minimal for unit tests. /// internal sealed class TestMessage : IMessage { public object? Body { get; set; } public string? ContentType { get; set; } public IDictionary Headers { get; } = new Dictionary(); public T? GetHeader(string key) => Headers.TryGetValue(key, out var v) && v is T t ? t : default; public IMessage Clone() { var clone = new TestMessage { Body = Body, ContentType = ContentType }; foreach (var h in Headers) clone.Headers[h.Key] = h.Value; return clone; } // Test double: the deep-copy distinction (see IMessage.Snapshot) is irrelevant here. public IMessage Snapshot() => Clone(); } /// /// Minimal for unit tests. /// internal sealed class TestExchange : IExchange { public IMessage In { get; set; } = new TestMessage(); public IMessage? Out { get; set; } public ExchangePattern Pattern { get; set; } = ExchangePattern.InOnly; public IDictionary Properties { get; } = new Dictionary(); public T? GetProperty(string key) => Properties.TryGetValue(key, out var v) && v is T t ? t : default; public Exception? Exception { get; set; } public bool ExceptionHandled { get; set; } public string? RouteId { get; set; } public string ExchangeId { get; } = Guid.NewGuid().ToString(); public bool IsStopped { get; private set; } public void Stop() => IsStopped = true; public IExchange Clone() => throw new NotSupportedException("Clone not needed in tests"); public IExchange Snapshot() => throw new NotSupportedException("Snapshot not needed in tests"); public ValueTask DisposeAsync() => default; } Path: redb-identity/tests/redb.Identity.Tests/Infrastructure/TestRedbSetup.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/Infrastructure/TestRedbSetup.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core.Extensions; using redb.Core.Models.Configuration; using redb.Core.Pro.Extensions; // Provider extensions. Pro variants are tier-agnostic — they dispatch on // AddRedb (Free) vs AddRedbPro (Pro). Do NOT also import the non-Pro // extensions; the resulting overload set would be ambiguous. using redb.Postgres.Pro.Extensions; using redb.MSSql.Pro.Extensions; using redb.SQLite.Pro.Extensions; using redb.SQLite.Data; namespace redb.Identity.Tests.Infrastructure; /// /// Test-only helper that wires redb to a (provider × tier) combination /// chosen via two environment variables. Default: SQLite Pro with the /// license bundled at redb.license in the test working dir. /// /// /// REDB_PROVIDER — picks storage. Values: sqlite /// (default), postgres, mssql. Case-insensitive. /// /// /// REDB_USE_PRO — picks tier. Default true (Pro); /// set to false for the free /// path. /// /// /// Per-provider connection strings come from environment overrides if /// set, otherwise from the local-dev defaults baked here. SQLite /// auto-creates a unique temp-file database per call so parallel test /// collections never collide. /// public static class TestRedbSetup { public enum Provider { Sqlite, Postgres, MsSql } private static readonly Lazy LicenseToken = new(LoadLicenseToken); private static int _sqliteExtensionResolved; private static int _sqliteScratchCleaned; public static Provider SelectedProvider => (Environment.GetEnvironmentVariable("REDB_PROVIDER")?.Trim().ToLowerInvariant()) switch { "postgres" or "pg" or "pgsql" => Provider.Postgres, "mssql" or "sqlserver" or "ms" => Provider.MsSql, _ => Provider.Sqlite, }; public static bool UsePro => !string.Equals( Environment.GetEnvironmentVariable("REDB_USE_PRO")?.Trim(), "false", StringComparison.OrdinalIgnoreCase); /// /// PVT prefilter, on by default so the suite exercises it. Set REDB_PVT_PREFILTER=false to /// take it out of the picture — worth doing when a failure needs to be attributed, since the /// prefilter is a superset that must never change a result. /// public static bool UsePvtPrefilter => !string.Equals( Environment.GetEnvironmentVariable("REDB_PVT_PREFILTER")?.Trim(), "false", StringComparison.OrdinalIgnoreCase); /// /// Add redb to . The /// is the historical local-dev default — used verbatim when REDB_PROVIDER=postgres /// and as a sentinel otherwise. SQLite / MSSQL pull their connection strings from /// env-var overrides or their respective defaults below. /// public static IServiceCollection AddRedbForTests( this IServiceCollection services, string postgresConnString, Action? configure = null) { if (SelectedProvider == Provider.Sqlite) EnsureSqliteNativeExtensionResolved(); if (UsePro) { return services.AddRedbPro(options => { ApplyProvider(options, postgresConnString); ApplyLicense(options); options.Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.ChangeTracking; c.EnablePropsCache = false; // PVT prefilter: narrows the object set before the pivot aggregate, so a selective // filter stops costing a full scheme scan. It is a superset and must never change a // result — which is exactly what running this suite with it on is worth proving. // Implemented by all three Pro providers, so it is not gated on the provider here. c.EnablePvtPrefilter = UsePvtPrefilter; configure?.Invoke(c); }); }); } return services.AddRedb(options => { ApplyProvider(options, postgresConnString); ApplyLicense(options); options.Configure(c => { c.PropsSaveStrategy = PropsSaveStrategy.DeleteInsert; c.EnablePropsCache = false; configure?.Invoke(c); }); }); } private static void ApplyProvider(RedbOptionsBuilder options, string postgresConnString) { switch (SelectedProvider) { case Provider.Postgres: options.UsePostgres(ResolvePostgresConnectionString(postgresConnString)); break; case Provider.MsSql: options.UseMsSql(ResolveMsSqlConnectionString()); break; default: options.UseSqlite(ResolveSqliteConnectionString()); break; } } private static void ApplyLicense(RedbOptionsBuilder options) { var token = LicenseToken.Value; if (!string.IsNullOrEmpty(token)) options.WithLicense(token); } // ── Per-provider connection-string resolution ──────────────────────── /// /// Resolves the Postgres connection string in this priority order: /// /// REDB_POSTGRES_CS env var when set and non-empty; /// the argument (typically /// config.GetConnectionString("Postgres") read from /// appsettings.json) when non-empty; /// the local-dev default below — Max Pool Size=100 to match /// MSSql/appsettings.json so the test-bench pool ceiling is uniform /// across providers and survives WithRedb-per-scope amplification. /// /// The hardcoded default makes the same Host/Port/credentials/database /// match the literal connection strings used by the Audit*IntegrationTests /// classes so a test that drops below appsettings.json (or one whose /// fixture doesn't load it) still lands on the same database. /// public static string ResolvePostgresConnectionString(string fallback) => Environment.GetEnvironmentVariable("REDB_POSTGRES_CS")?.Trim() is { Length: > 0 } cs ? cs : !string.IsNullOrEmpty(fallback) ? fallback : "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true;Maximum Pool Size=100;Include Error Detail=true"; /// /// The Postgres connection string of the run, for every place that needs it: the fixtures that /// hand it to and the tests that open their own connection. One /// resolution (: REDB_POSTGRES_CS, then /// appsettings.json, then the local default), so a test's own connection reaches the same /// database the server under test writes to, not whatever listens on the port named in the file. /// public static string GetPostgresConnectionString(this Microsoft.Extensions.Configuration.IConfiguration configuration) => ResolvePostgresConnectionString( Microsoft.Extensions.Configuration.ConfigurationExtensions.GetConnectionString(configuration, "Postgres") ?? string.Empty); public static string ResolveMsSqlConnectionString() => Environment.GetEnvironmentVariable("REDB_MSSQL_CS")?.Trim() is { Length: > 0 } cs ? cs // Max Pool Size=100 explicitly so the test-bench ceiling matches the PG // appsettings.json value; Microsoft.Data.SqlClient's default is also 100 // but stating it makes the limit explicit when comparing logs across // providers and matches the WithRedb-per-scope amplification headroom. : "Server=127.0.0.1,1433;Database=redb;User Id=sa;Password=1;TrustServerCertificate=true;Command Timeout=600;Max Pool Size=100;"; /// /// The SQLite database of this test process: one file per process under the temp dir, shared by every /// fixture of the process, never by another process. Override via REDB_SQLITE_CS for a pinned path /// or :memory:. Use when a single test needs to share storage /// across multiple redb instances (multi-replica probes). /// public static string ResolveSqliteConnectionString() { var pinned = Environment.GetEnvironmentVariable("REDB_SQLITE_CS")?.Trim(); if (!string.IsNullOrEmpty(pinned)) return pinned; var path = CreateSqliteScratchPath(); // Once per test process, before anyone opens it: remove the files of test processes that no longer // run (a killed run leaves its database with its -wal and -shm) and whatever an earlier process with // this process id left, and remove this process's files when it ends. Guarded with Interlocked so // that, of the fixtures resolving the path at once, only the first one sweeps. if (Interlocked.Exchange(ref _sqliteScratchCleaned, 1) == 0) { SweepSqliteScratchFiles(); AppDomain.CurrentDomain.ProcessExit += (_, _) => { Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); DeleteSqliteFiles(SqliteScratchPath); }; } return BuildSqliteConnectionString(path); } private const string SqliteScratchPrefix = "redb-test-identity-"; // Two test processes on one machine (two worktrees, or two sessions) must never share a database: a delivery // worker of one process would deliver the outbox rows of the other. private static readonly string SqliteScratchPath = Path.Combine(Path.GetTempPath(), $"{SqliteScratchPrefix}{Environment.ProcessId}.db"); /// /// The SQLite database file of this test process. Use the resulting path in /// twice (or more) when a test /// needs multiple redb instances pointing at the same physical DB. /// public static string CreateSqliteScratchPath() => SqliteScratchPath; private static void SweepSqliteScratchFiles() { foreach (var file in Directory.EnumerateFiles(Path.GetTempPath(), SqliteScratchPrefix + "*.db")) { var pid = Path.GetFileNameWithoutExtension(file)[SqliteScratchPrefix.Length..]; if (!int.TryParse(pid, out var id)) continue; if (id == Environment.ProcessId || !IsRunning(id)) DeleteSqliteFiles(file); } } private static bool IsRunning(int processId) { try { using var process = System.Diagnostics.Process.GetProcessById(processId); return !process.HasExited; } catch (ArgumentException) { return false; } catch (InvalidOperationException) { return false; } } private static void DeleteSqliteFiles(string path) { foreach (var f in new[] { path, path + "-wal", path + "-shm" }) { try { if (File.Exists(f)) File.Delete(f); } catch (IOException) { /* still held: the next start sweeps it */ } catch (UnauthorizedAccessException) { /* still held: the next start sweeps it */ } } } /// Compose a SQLite connection string from a file path with the /// per-test defaults (file-based, ReadWriteCreate, no shared cache — /// shared cache would break WAL's reader-during-writer guarantee). public static string BuildSqliteConnectionString(string filePath) => $"Data Source={filePath};Mode=ReadWriteCreate"; // ── SQLite native extension (Free path only; harmless on Pro) ──────── /// /// Free SQLite needs the native extension on every connection /// (get_object_json / pvt_build_*_sql live inside it). Pro doesn't, /// but setting the path is harmless. Best-effort: honour /// REDB_SQLITE_EXTENSION if set, else walk parents looking for /// redb.SQLite/native/build/redbsqlite.{dll,so,dylib}. Runs once per /// process via interlocked flag. /// private static void EnsureSqliteNativeExtensionResolved() { if (Interlocked.CompareExchange(ref _sqliteExtensionResolved, 1, 0) != 0) return; if (!string.IsNullOrEmpty(SqliteDataSource.NativeExtensionPath)) return; var fromEnv = Environment.GetEnvironmentVariable("REDB_SQLITE_EXTENSION")?.Trim(); if (!string.IsNullOrEmpty(fromEnv) && File.Exists(fromEnv)) { SqliteDataSource.NativeExtensionPath = fromEnv; return; } var suffix = OperatingSystem.IsWindows() ? ".dll" : OperatingSystem.IsMacOS() ? ".dylib" : ".so"; for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir != null; dir = dir.Parent) { // Public mirror layout first (redb.SQLite at the top level), then the development repository layout (redb.DB/src). var candidate = Path.Combine(dir.FullName, "redb.SQLite", "native", "build", "redbsqlite" + suffix); if (!File.Exists(candidate)) candidate = Path.Combine(dir.FullName, "redb.DB", "src", "redb.SQLite", "native", "build", "redbsqlite" + suffix); if (File.Exists(candidate)) { SqliteDataSource.NativeExtensionPath = candidate; return; } } } // ── License loading ────────────────────────────────────────────────── /// /// Read the Pro license JWT from redb.license next to the test /// assembly. The file is shipped in the test project and copied to the /// output dir by the csproj. Missing file → null, callers proceed with /// the free tier. /// private static string? LoadLicenseToken() { var path = Path.Combine(AppContext.BaseDirectory, "redb.license"); if (!File.Exists(path)) return null; try { var token = File.ReadAllText(path).Trim(); return string.IsNullOrEmpty(token) ? null : token; } catch { return null; } } } Path: redb-identity/tests/redb.Identity.Tests/Ldap/LdapAttributeMapperTests.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/Ldap/LdapAttributeMapperTests.cs ---- using AwesomeAssertions; using redb.Identity.Ldap; using redb.Route.Ldap; using Xunit; namespace redb.Identity.Tests.Ldap; /// /// Unit tests for and . /// public class LdapAttributeMapperTests { // ── Presets ── [Fact] public void OpenLdapPreset_SetsCorrectFilterAndAttributeMap() { var options = new LdapProviderOptions { UserBaseDn = "dc=test" }; options.ApplyPreset(LdapPreset.OpenLDAP); options.UserFilter.Should().Be("(uid={0})"); options.AttributeMap.Should().ContainKey("externalId").WhoseValue.Should().Be("uid"); options.AttributeMap.Should().ContainKey("displayName").WhoseValue.Should().Be("cn"); options.AttributeMap.Should().ContainKey("email").WhoseValue.Should().Be("mail"); options.AttributeMap.Should().ContainKey("phone").WhoseValue.Should().Be("telephoneNumber"); options.AttributeMap.Should().ContainKey("givenName").WhoseValue.Should().Be("givenName"); options.AttributeMap.Should().ContainKey("familyName").WhoseValue.Should().Be("sn"); } [Fact] public void ActiveDirectoryPreset_SetsCorrectFilterAndAttributeMap() { var options = new LdapProviderOptions { UserBaseDn = "dc=test" }; options.ApplyPreset(LdapPreset.ActiveDirectory); options.UserFilter.Should().Contain("sAMAccountName={0}"); options.UserFilter.Should().Contain("objectClass=user"); options.AttributeMap.Should().ContainKey("externalId").WhoseValue.Should().Be("sAMAccountName"); options.AttributeMap.Should().ContainKey("displayName").WhoseValue.Should().Be("displayName"); options.AttributeMap.Should().ContainKey("email").WhoseValue.Should().Be("mail"); } // ── Mapper: MapToResult ── [Fact] public void MapToResult_MapsAllFieldsFromLdapEntry() { var options = new LdapProviderOptions { UserBaseDn = "dc=test" }; options.ApplyPreset(LdapPreset.OpenLDAP); var mapper = new LdapAttributeMapper(options); var entry = new LdapEntry { Dn = "uid=alice,ou=users,dc=test", Attributes = { ["uid"] = "alice", ["cn"] = "Alice Wonderland", ["mail"] = "alice@example.com", ["telephoneNumber"] = "+1234567890", ["givenName"] = "Alice", ["sn"] = "Wonderland" } }; var result = mapper.MapToResult(entry); result.Succeeded.Should().BeTrue(); result.ExternalId.Should().Be("alice"); result.DisplayName.Should().Be("Alice Wonderland"); result.Email.Should().Be("alice@example.com"); result.Phone.Should().Be("+1234567890"); result.GivenName.Should().Be("Alice"); result.FamilyName.Should().Be("Wonderland"); } [Fact] public void MapToResult_MissingAttributes_AreNull() { var options = new LdapProviderOptions { UserBaseDn = "dc=test" }; options.ApplyPreset(LdapPreset.OpenLDAP); var mapper = new LdapAttributeMapper(options); var entry = new LdapEntry { Dn = "uid=bob,ou=users,dc=test", Attributes = { ["uid"] = "bob" } }; var result = mapper.MapToResult(entry); result.Succeeded.Should().BeTrue(); result.ExternalId.Should().Be("bob"); result.DisplayName.Should().BeNull(); result.Email.Should().BeNull(); result.Phone.Should().BeNull(); } [Fact] public void MapToResult_FallsBackToDn_WhenExternalIdNotMapped() { var options = new LdapProviderOptions { UserBaseDn = "dc=test", AttributeMap = new Dictionary { ["displayName"] = "cn" } }; var mapper = new LdapAttributeMapper(options); var entry = new LdapEntry { Dn = "uid=noid,ou=users,dc=test", Attributes = { ["cn"] = "No Id User" } }; var result = mapper.MapToResult(entry); result.ExternalId.Should().Be("uid=noid,ou=users,dc=test"); result.DisplayName.Should().Be("No Id User"); } [Fact] public void MapToResult_MapsAdditionalClaims() { var options = new LdapProviderOptions { UserBaseDn = "dc=test", AdditionalClaimsMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["department"] = "departmentNumber", ["title"] = "title" } }; options.ApplyPreset(LdapPreset.OpenLDAP); var mapper = new LdapAttributeMapper(options); var entry = new LdapEntry { Dn = "uid=alice,ou=users,dc=test", Attributes = { ["uid"] = "alice", ["departmentNumber"] = "Engineering", ["title"] = "Senior Developer" } }; var result = mapper.MapToResult(entry); result.AdditionalClaims.Should().NotBeNull(); result.AdditionalClaims.Should().ContainKey("department").WhoseValue.Should().Be("Engineering"); result.AdditionalClaims.Should().ContainKey("title").WhoseValue.Should().Be("Senior Developer"); } [Fact] public void MapToResult_EmptyAdditionalClaims_ReturnsNull() { var options = new LdapProviderOptions { UserBaseDn = "dc=test", AdditionalClaimsMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["department"] = "departmentNumber" } }; options.ApplyPreset(LdapPreset.OpenLDAP); var mapper = new LdapAttributeMapper(options); var entry = new LdapEntry { Dn = "uid=alice,ou=users,dc=test", Attributes = { ["uid"] = "alice" } }; var result = mapper.MapToResult(entry); result.AdditionalClaims.Should().BeNull(); } // ── Mapper: GetRequestedAttributes ── [Fact] public void GetRequestedAttributes_IncludesFieldAndClaimsAttributes() { var options = new LdapProviderOptions { UserBaseDn = "dc=test", AttributeMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["externalId"] = "uid", ["email"] = "mail" }, AdditionalClaimsMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["department"] = "departmentNumber" } }; var mapper = new LdapAttributeMapper(options); var attrs = mapper.GetRequestedAttributes(); attrs.Should().Contain("uid"); attrs.Should().Contain("mail"); attrs.Should().Contain("departmentNumber"); } [Fact] public void GetRequestedAttributes_DeduplicatesOverlapping() { var options = new LdapProviderOptions { UserBaseDn = "dc=test", AttributeMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["email"] = "mail" }, AdditionalClaimsMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["userEmail"] = "mail" } }; var mapper = new LdapAttributeMapper(options); var attrs = mapper.GetRequestedAttributes(); attrs.Should().ContainSingle(a => a.Equals("mail", StringComparison.OrdinalIgnoreCase)); } } Path: redb-identity/tests/redb.Identity.Tests/Ldap/LdapConnectionSettingsTests.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/Ldap/LdapConnectionSettingsTests.cs ---- using AwesomeAssertions; using redb.Identity.Ldap; using Xunit; namespace redb.Identity.Tests.Ldap; /// /// Unit tests for validation. /// public class LdapConnectionSettingsTests { // ── ValidateConnection ── [Fact] public void ValidateConnection_EmptyServer_Throws() { var settings = new LdapConnectionSettings { Server = "" }; var act = () => settings.ValidateConnection(); act.Should().Throw().WithMessage("*Server*required*"); } [Fact] public void ValidateConnection_WhitespaceServer_Throws() { var settings = new LdapConnectionSettings { Server = " " }; var act = () => settings.ValidateConnection(); act.Should().Throw().WithMessage("*Server*required*"); } [Theory] [InlineData(0)] [InlineData(-1)] [InlineData(70000)] public void ValidateConnection_PortOutOfRange_Throws(int port) { var settings = new LdapConnectionSettings { Port = port }; var act = () => settings.ValidateConnection(); act.Should().Throw().WithMessage("*Port*out of range*"); } [Fact] public void ValidateConnection_SslAndStartTls_Throws() { var settings = new LdapConnectionSettings { UseSsl = true, UseStartTls = true }; var act = () => settings.ValidateConnection(); act.Should().Throw().WithMessage("*mutually exclusive*"); } [Fact] public void ValidateConnection_BindDnWithoutPassword_Throws() { var settings = new LdapConnectionSettings { BindDn = "cn=admin,dc=test", BindPassword = null }; var act = () => settings.ValidateConnection(); act.Should().Throw().WithMessage("*BindDn*BindPassword*"); } [Fact] public void ValidateConnection_PasswordWithoutBindDn_Throws() { var settings = new LdapConnectionSettings { BindDn = null, BindPassword = "secret" }; var act = () => settings.ValidateConnection(); act.Should().Throw().WithMessage("*BindPassword*BindDn*"); } [Fact] public void ValidateConnection_ValidSettings_NoThrow() { var settings = new LdapConnectionSettings { Server = "ldap.test", Port = 636, UseSsl = true, BindDn = "cn=admin,dc=test", BindPassword = "secret" }; var act = () => settings.ValidateConnection(); act.Should().NotThrow(); } [Fact] public void ValidateConnection_DefaultSettings_NoThrow() { var settings = new LdapConnectionSettings(); var act = () => settings.ValidateConnection(); act.Should().NotThrow(); } // ── EffectivePort ── [Fact] public void EffectivePort_SslDefaultPort_Returns636() { var settings = new LdapConnectionSettings { UseSsl = true, Port = 389 }; settings.EffectivePort.Should().Be(636); } [Fact] public void EffectivePort_SslCustomPort_ReturnsCustom() { var settings = new LdapConnectionSettings { UseSsl = true, Port = 10636 }; settings.EffectivePort.Should().Be(10636); } [Fact] public void EffectivePort_NoSsl_ReturnsPlain() { var settings = new LdapConnectionSettings { Port = 389 }; settings.EffectivePort.Should().Be(389); } // ── Defaults ── [Fact] public void Defaults_AreReasonable() { var settings = new LdapConnectionSettings(); settings.Server.Should().Be("localhost"); settings.Port.Should().Be(389); settings.UseSsl.Should().BeFalse(); settings.UseStartTls.Should().BeFalse(); settings.SkipCertificateValidation.Should().BeFalse(); settings.BindDn.Should().BeNull(); settings.BindPassword.Should().BeNull(); settings.OperationTimeoutSeconds.Should().Be(10); settings.MaxConnections.Should().Be(5); } } Path: redb-identity/tests/redb.Identity.Tests/Ldap/LdapExternalUserProviderTests.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/Ldap/LdapExternalUserProviderTests.cs ---- using AwesomeAssertions; using redb.Identity.Ldap; using Xunit; namespace redb.Identity.Tests.Ldap; /// /// Unit tests for logic that doesn't require a live LDAP server. /// Tests LDAP filter escaping (RFC 4515) and constructor validation. /// public class LdapExternalUserProviderTests { // ── LDAP Filter Escaping (RFC 4515 §3) ── [Theory] [InlineData("alice", "alice")] [InlineData("bob.smith", "bob.smith")] [InlineData("user@domain.com", "user@domain.com")] public void EscapeLdapFilter_PlainValues_Unchanged(string input, string expected) { LdapExternalUserProvider.EscapeLdapFilter(input).Should().Be(expected); } [Theory] [InlineData("user*", "user\\2a")] [InlineData("(admin)", "\\28admin\\29")] [InlineData("dn\\path", "dn\\5cpath")] [InlineData("null\0char", "null\\00char")] [InlineData("a]l*i(c)e", "a]l\\2ai\\28c\\29e")] public void EscapeLdapFilter_SpecialChars_AreEscaped(string input, string expected) { LdapExternalUserProvider.EscapeLdapFilter(input).Should().Be(expected); } [Fact] public void EscapeLdapFilter_InjectionAttempt_IsNeutralized() { // Classic LDAP injection: username = "admin)(|(uid=*" var malicious = "admin)(|(uid=*"; var escaped = LdapExternalUserProvider.EscapeLdapFilter(malicious); escaped.Should().Be("admin\\29\\28|\\28uid=\\2a"); escaped.Should().NotContain(")("); escaped.Should().NotContain("*"); } [Theory] [InlineData("")] [InlineData(null)] public void EscapeLdapFilter_NullOrEmpty_ReturnsSame(string? input) { LdapExternalUserProvider.EscapeLdapFilter(input!).Should().Be(input); } // ── Constructor validation ── [Fact] public void Constructor_InvalidOptions_Throws() { var options = new LdapProviderOptions { UserBaseDn = "" }; // invalid var act = () => new LdapExternalUserProvider( options, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); act.Should().Throw().WithMessage("*UserBaseDn*"); } [Fact] public void ProviderName_ReturnsConfiguredName() { var options = new LdapProviderOptions { ProviderName = "ldap:corp", UserBaseDn = "dc=test", UserFilter = "(uid={0})" }; var provider = new LdapExternalUserProvider( options, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); provider.ProviderName.Should().Be("ldap:corp"); provider.Priority.Should().Be(100); } // ── Null/empty inputs ── [Fact] public async Task AuthenticateAsync_NullUsername_ReturnsNull() { var provider = CreateProvider(); var result = await provider.AuthenticateAsync(null!, "password"); result.Should().BeNull(); } [Fact] public async Task AuthenticateAsync_EmptyPassword_ReturnsNull() { var provider = CreateProvider(); var result = await provider.AuthenticateAsync("alice", ""); result.Should().BeNull(); } [Fact] public async Task AuthenticateAsync_WhitespaceUsername_ReturnsNull() { var provider = CreateProvider(); var result = await provider.AuthenticateAsync(" ", "password"); result.Should().BeNull(); } // ── Domain hint parsing ── [Theory] [InlineData("alice@corp.test", "alice", "corp.test")] [InlineData("bob@EXAMPLE.COM", "bob", "EXAMPLE.COM")] [InlineData("CORP\\alice", "alice", "CORP")] [InlineData("domain\\user", "user", "domain")] public void ParseDomainHint_WithHint_ExtractsCorrectly(string input, string expectedUser, string expectedDomain) { var (username, domain) = LdapExternalUserProvider.ParseDomainHint(input); username.Should().Be(expectedUser); domain.Should().Be(expectedDomain); } [Theory] [InlineData("alice")] [InlineData("bob.smith")] [InlineData("plain_user")] public void ParseDomainHint_WithoutHint_ReturnsNullDomain(string input) { var (username, domain) = LdapExternalUserProvider.ParseDomainHint(input); username.Should().Be(input); domain.Should().BeNull(); } [Theory] [InlineData("@domain")] // empty username part [InlineData("\\user")] // empty domain part [InlineData("user@")] // empty domain after @ [InlineData("domain\\")] // empty username after \ public void ParseDomainHint_EdgeCases_TreatsAsPlainOrPartial(string input) { var (username, domain) = LdapExternalUserProvider.ParseDomainHint(input); // Edge cases: at least one part is always present username.Should().NotBeNull(); } // ── UserAccountControlFlags ── [Fact] public void UacFlags_AccountDisable_HasCorrectValue() { ((int)UserAccountControlFlags.AccountDisable).Should().Be(0x0002); } [Fact] public void UacFlags_Lockout_HasCorrectValue() { ((int)UserAccountControlFlags.Lockout).Should().Be(0x0010); } [Fact] public void UacFlags_NormalAccount_HasCorrectValue() { ((int)UserAccountControlFlags.NormalAccount).Should().Be(0x0200); } [Fact] public void UacFlags_PasswordExpired_HasCorrectValue() { ((int)UserAccountControlFlags.PasswordExpired).Should().Be(0x800000); } [Fact] public void UacFlags_CombinedFlags_WorkCorrectly() { var combined = UserAccountControlFlags.NormalAccount | UserAccountControlFlags.AccountDisable; combined.HasFlag(UserAccountControlFlags.AccountDisable).Should().BeTrue(); combined.HasFlag(UserAccountControlFlags.NormalAccount).Should().BeTrue(); combined.HasFlag(UserAccountControlFlags.Lockout).Should().BeFalse(); } [Fact] public void UacFlags_DisabledAndNormal_ParsesFromInt() { // AD typical disabled user: NormalAccount(0x0200) + AccountDisable(0x0002) = 0x0202 var flags = (UserAccountControlFlags)0x0202; flags.HasFlag(UserAccountControlFlags.AccountDisable).Should().BeTrue(); flags.HasFlag(UserAccountControlFlags.NormalAccount).Should().BeTrue(); } [Fact] public void UacFlags_LockedOut_ParsesFromInt() { // NormalAccount(0x0200) + Lockout(0x0010) = 0x0210 var flags = (UserAccountControlFlags)0x0210; flags.HasFlag(UserAccountControlFlags.Lockout).Should().BeTrue(); flags.HasFlag(UserAccountControlFlags.AccountDisable).Should().BeFalse(); } [Fact] public async Task AuthenticateAsync_DomainMismatch_ReturnsNull() { var options = new LdapProviderOptions { UserBaseDn = "ou=users,dc=test", UserFilter = "(uid={0})", Server = "nonexistent.host", Domains = ["corp.test"] }; options.ApplyPreset(LdapPreset.OpenLDAP); var provider = new LdapExternalUserProvider( options, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); // Domain doesn't match configured domains → should return null (skip) var result = await provider.AuthenticateAsync("alice@other.test", "password"); result.Should().BeNull(); } [Fact] public async Task AuthenticateAsync_NoDomainHint_NoDomainConfig_Passes() { // When Domains is empty, bare usernames are accepted var provider = CreateProvider(); // This will attempt LDAP connection to nonexistent.host and throw, // NOT return null — proving domain routing didn't filter it out. var act = () => provider.AuthenticateAsync("alice", "password"); await act.Should().ThrowAsync(); } private static LdapExternalUserProvider CreateProvider() { var options = new LdapProviderOptions { UserBaseDn = "ou=users,dc=test", UserFilter = "(uid={0})", Server = "nonexistent.host", ConnectTimeoutSeconds = 1 // pre-flight probe fails fast on NXDOMAIN }; options.ApplyPreset(LdapPreset.OpenLDAP); return new LdapExternalUserProvider( options, Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); } } Path: redb-identity/tests/redb.Identity.Tests/Ldap/LdapGroupMapperTests.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/Ldap/LdapGroupMapperTests.cs ---- using AwesomeAssertions; using redb.Identity.Ldap; using redb.Route.Ldap; using Xunit; namespace redb.Identity.Tests.Ldap; /// /// Unit tests for logic. /// Tests CN extraction from DNs and option defaults. /// public class LdapGroupMapperTests { // ── ExtractCnFromDn ── [Theory] [InlineData("cn=developers,ou=groups,dc=example,dc=com", "developers")] [InlineData("CN=Admins,OU=Groups,DC=corp,DC=test", "Admins")] [InlineData("cn=single-group", "single-group")] [InlineData("cn=with spaces,ou=groups", "with spaces")] [InlineData("cn=Smith\\, John,ou=groups,dc=test", "Smith, John")] [InlineData("cn=Test\\+Group,ou=groups", "Test+Group")] [InlineData("cn=has\\\\backslash,ou=groups", "has\\backslash")] public void ExtractCnFromDn_ValidDn_ExtractsCn(string dn, string expected) { LdapGroupMapper.ExtractCnFromDn(dn).Should().Be(expected); } [Theory] [InlineData("ou=groups,dc=test")] // not a CN [InlineData("uid=alice,ou=users,dc=test")] // uid, not cn [InlineData("")] [InlineData(null)] [InlineData(" ")] public void ExtractCnFromDn_NotCn_ReturnsNull(string? dn) { LdapGroupMapper.ExtractCnFromDn(dn!).Should().BeNull(); } // ── Options defaults ── [Fact] public void GroupMapperOptions_Defaults() { var options = new LdapGroupMapperOptions(); options.GroupMemberAttribute.Should().Be("memberOf"); options.MemberRole.Should().Be("member"); options.AutoCreateGroups.Should().BeTrue(); options.SyncStrategy.Should().Be(LdapGroupSyncStrategy.Full); } // ── LdapEntry memberOf extraction ── [Fact] public void LdapEntry_GetStringArray_ExtractsMemberOf() { var entry = new LdapEntry { Dn = "uid=alice,ou=users,dc=test", Attributes = new Dictionary { ["memberOf"] = new[] { "cn=developers,ou=groups,dc=test", "cn=admins,ou=groups,dc=test" } } }; var groups = entry.GetStringArray("memberOf"); groups.Should().HaveCount(2); groups.Should().Contain("cn=developers,ou=groups,dc=test"); groups.Should().Contain("cn=admins,ou=groups,dc=test"); var names = groups!.Select(LdapGroupMapper.ExtractCnFromDn).ToArray(); names.Should().Equal("developers", "admins"); } [Fact] public void LdapEntry_NoMemberOf_ReturnsNull() { var entry = new LdapEntry { Dn = "uid=bob,ou=users,dc=test", Attributes = new Dictionary { ["uid"] = "bob" } }; entry.GetStringArray("memberOf").Should().BeNull(); } } Path: redb-identity/tests/redb.Identity.Tests/Ldap/LdapHealthCheckTests.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/Ldap/LdapHealthCheckTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Core.Services; using redb.Identity.Ldap; using Xunit; namespace redb.Identity.Tests.Ldap; /// /// Unit tests for . /// public class LdapHealthCheckTests { [Fact] public async Task NoProviders_ReturnsHealthy() { var check = new LdapHealthCheck( Array.Empty(), NullLogger.Instance); var result = await check.CheckHealthAsync(null!); result.Status.Should().Be(HealthStatus.Healthy); result.Description.Should().Contain("No LDAP providers"); } [Fact] public async Task NonLdapProviders_ReturnsHealthy() { // IExternalUserProvider that is NOT LdapExternalUserProvider → filtered out var nonLdapProvider = new FakeExternalUserProvider(); var check = new LdapHealthCheck( new IExternalUserProvider[] { nonLdapProvider }, NullLogger.Instance); var result = await check.CheckHealthAsync(null!); result.Status.Should().Be(HealthStatus.Healthy); result.Description.Should().Contain("No LDAP providers"); } [Fact] public async Task UnreachableServer_ReturnsUnhealthy() { var options = new LdapProviderOptions { ProviderName = "ldap:fail", UserBaseDn = "dc=test", UserFilter = "(uid={0})", Server = "192.0.2.1", // RFC 5737 TEST-NET — not routable Port = 19999, OperationTimeoutSeconds = 2, ConnectTimeoutSeconds = 1 // pre-flight probe must fail fast }; var provider = new LdapExternalUserProvider( options, NullLogger.Instance); var context = new HealthCheckContext { Registration = new HealthCheckRegistration( "ldap-test", _ => throw new NotImplementedException(), HealthStatus.Degraded, null) }; var check = new LdapHealthCheck( new IExternalUserProvider[] { provider }, NullLogger.Instance); var result = await check.CheckHealthAsync(context); result.Status.Should().NotBe(HealthStatus.Healthy); result.Data.Should().ContainKey("ldap:ldap:fail"); } private sealed class FakeExternalUserProvider : IExternalUserProvider { public string ProviderName => "fake"; public int Priority => 0; public Task AuthenticateAsync( string username, string password, CancellationToken ct = default) => Task.FromResult(null); } } Path: redb-identity/tests/redb.Identity.Tests/Ldap/LdapIntegrationTests.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/Ldap/LdapIntegrationTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Ldap; using Xunit; using Xunit.Abstractions; namespace redb.Identity.Tests.Ldap; /// /// Integration tests for against a live OpenLDAP server. /// Requires Docker container 'route-openldap' running on localhost:389. /// Seed data: alice/alice123, bob/bob123, charlie/charlie123, diana/diana123, eve/eve123 /// Domain: dc=redb,dc=test. Users OU: ou=users,dc=redb,dc=test. /// [Trait("Category", "Integration")] [Collection("LdapIntegration")] public class LdapIntegrationTests : IAsyncLifetime { private readonly ITestOutputHelper _out; private LdapExternalUserProvider _provider = null!; private bool _ldapAvailable; // ── OpenLDAP container settings ── private const string Server = "localhost"; private const int Port = 389; private const string BindDn = "cn=admin,dc=redb,dc=test"; private const string BindPassword = "admin"; private const string UserBaseDn = "ou=users,dc=redb,dc=test"; public LdapIntegrationTests(ITestOutputHelper output) { _out = output; } public async Task InitializeAsync() { var options = new LdapProviderOptions { Server = Server, Port = Port, BindDn = BindDn, BindPassword = BindPassword, UserBaseDn = UserBaseDn, ProviderName = "ldap:test" }; options.ApplyPreset(LdapPreset.OpenLDAP); _provider = new LdapExternalUserProvider( options, NullLogger.Instance); // Probe LDAP connectivity try { var probe = await _provider.AuthenticateAsync("alice", "alice123"); _ldapAvailable = probe is { Succeeded: true }; _out.WriteLine($"LDAP probe: available={_ldapAvailable}"); } catch (Exception ex) { _out.WriteLine($"LDAP not available: {ex.Message}"); _ldapAvailable = false; } } public Task DisposeAsync() => _provider.DisposeAsync().AsTask(); private void SkipIfNoLdap() { if (!_ldapAvailable) { _out.WriteLine("SKIP: OpenLDAP container not available on localhost:389"); Assert.Fail("OpenLDAP container not available on localhost:389. Start 'route-openldap' Docker container."); } } // ────────────────────────────────────────────────────────── // Successful authentication // ────────────────────────────────────────────────────────── [Fact] public async Task Auth_ValidCredentials_ReturnsSuccess() { SkipIfNoLdap(); var result = await _provider.AuthenticateAsync("alice", "alice123"); result.Should().NotBeNull(); result!.Succeeded.Should().BeTrue(); result.ExternalId.Should().Be("alice"); result.DisplayName.Should().Be("alice"); // cn=alice in seed data result.Email.Should().Be("alice@redb.test"); result.Phone.Should().Be("+7-495-001-0001"); // telephoneNumber of alice in seed data result.FamilyName.Should().Be("Wonderland"); // sn } [Fact] public async Task Auth_AnotherUser_ReturnsCorrectProfile() { SkipIfNoLdap(); var result = await _provider.AuthenticateAsync("bob", "bob123"); result.Should().NotBeNull(); result!.Succeeded.Should().BeTrue(); result.ExternalId.Should().Be("bob"); result.Email.Should().Be("bob@redb.test"); result.FamilyName.Should().Be("Builder"); result.Phone.Should().Be("+7-495-001-0002"); } // ────────────────────────────────────────────────────────── // Authentication failures // ────────────────────────────────────────────────────────── [Fact] public async Task Auth_WrongPassword_ReturnsFailed() { SkipIfNoLdap(); var result = await _provider.AuthenticateAsync("alice", "wrongpassword"); result.Should().NotBeNull(); result!.Succeeded.Should().BeFalse(); result.ErrorMessage.Should().NotBeNullOrWhiteSpace(); } [Fact] public async Task Auth_UnknownUser_ReturnsNull() { SkipIfNoLdap(); var result = await _provider.AuthenticateAsync("nonexistent_user_xyz", "password"); // null = provider doesn't handle this user result.Should().BeNull(); } // ────────────────────────────────────────────────────────── // Edge cases // ────────────────────────────────────────────────────────── [Fact] public async Task Auth_UserWithoutPhone_PhoneIsNull() { SkipIfNoLdap(); // charlie has no telephoneNumber in seed data var result = await _provider.AuthenticateAsync("charlie", "charlie123"); result.Should().NotBeNull(); result!.Succeeded.Should().BeTrue(); result.ExternalId.Should().Be("charlie"); result.Email.Should().Be("charlie@redb.test"); result.Phone.Should().BeNull(); } [Fact] public async Task Auth_AllSeedUsers_Authenticate() { SkipIfNoLdap(); var users = new[] { ("alice", "alice123"), ("bob", "bob123"), ("charlie", "charlie123"), ("diana", "diana123"), ("eve", "eve123") }; foreach (var (username, password) in users) { var result = await _provider.AuthenticateAsync(username, password); result.Should().NotBeNull($"user '{username}' should be found"); result!.Succeeded.Should().BeTrue($"user '{username}' should authenticate with correct password"); result.ExternalId.Should().Be(username); _out.WriteLine($" {username}: OK (email={result.Email}, sn={result.FamilyName})"); } } // ────────────────────────────────────────────────────────── // LDAP injection protection // ────────────────────────────────────────────────────────── [Fact] public async Task Auth_InjectionAttempt_DoesNotMatchAnyUser() { SkipIfNoLdap(); // Classic LDAP injection: try to match all users var result = await _provider.AuthenticateAsync("*)(uid=*", "anything"); result.Should().BeNull("injection attempt should not match any user"); } // ────────────────────────────────────────────────────────── // Attribute mapping with additional claims // ────────────────────────────────────────────────────────── [Fact] public async Task Auth_CustomAdditionalClaimsMap_MapsExtraAttributes() { SkipIfNoLdap(); var options = new LdapProviderOptions { Server = Server, Port = Port, BindDn = BindDn, BindPassword = BindPassword, UserBaseDn = UserBaseDn, AdditionalClaimsMap = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["surname"] = "sn", ["ldap_mail"] = "mail" } }; options.ApplyPreset(LdapPreset.OpenLDAP); await using var provider = new LdapExternalUserProvider( options, NullLogger.Instance); var result = await provider.AuthenticateAsync("alice", "alice123"); result.Should().NotBeNull(); result!.Succeeded.Should().BeTrue(); result.AdditionalClaims.Should().ContainKey("surname").WhoseValue.Should().Be("Wonderland"); result.AdditionalClaims.Should().ContainKey("ldap_mail").WhoseValue.Should().Be("alice@redb.test"); } } Path: redb-identity/tests/redb.Identity.Tests/Ldap/LdapProviderOptionsTests.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/Ldap/LdapProviderOptionsTests.cs ---- using AwesomeAssertions; using redb.Identity.Ldap; using Xunit; namespace redb.Identity.Tests.Ldap; /// /// Unit tests for validation and configuration. /// public class LdapProviderOptionsTests { [Fact] public void Validate_ThrowsOnEmptyUserBaseDn() { var options = new LdapProviderOptions { UserBaseDn = "" }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*UserBaseDn*"); } [Fact] public void Validate_ThrowsOnFilterWithoutPlaceholder() { var options = new LdapProviderOptions { UserBaseDn = "dc=test", UserFilter = "(uid=alice)" }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*{0}*"); } [Fact] public void Validate_ThrowsOnInvalidPort() { var options = new LdapProviderOptions { UserBaseDn = "dc=test", Port = 0 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*Port*"); } [Fact] public void Validate_PassesWithValidOptions() { var options = new LdapProviderOptions { UserBaseDn = "ou=users,dc=example,dc=com", UserFilter = "(uid={0})" }; var act = () => options.Validate(); act.Should().NotThrow(); } [Fact] public void EffectivePort_Returns636_WhenSslAndDefaultPort() { var options = new LdapProviderOptions { UseSsl = true, Port = 389 }; options.EffectivePort.Should().Be(636); } [Fact] public void EffectivePort_ReturnsCustomPort_WhenSslOnCustomPort() { var options = new LdapProviderOptions { UseSsl = true, Port = 10636 }; options.EffectivePort.Should().Be(10636); } [Fact] public void EffectivePort_ReturnsPlainPort_WhenNoSsl() { var options = new LdapProviderOptions { Port = 389 }; options.EffectivePort.Should().Be(389); } [Fact] public void Defaults_AreReasonable() { var options = new LdapProviderOptions(); options.ProviderName.Should().Be("ldap"); options.Priority.Should().Be(100); options.Server.Should().Be("localhost"); options.Port.Should().Be(389); options.UseSsl.Should().BeFalse(); options.UseStartTls.Should().BeFalse(); options.SearchScope.Should().Be(LdapSearchScopeOption.Subtree); options.UserFilter.Should().Be("(uid={0})"); options.MaxConnections.Should().Be(5); options.Domains.Should().BeEmpty(); } [Fact] public void ApplyPreset_OverwritesExistingMap() { var options = new LdapProviderOptions { UserBaseDn = "dc=test", AttributeMap = new Dictionary { ["custom"] = "field" } }; options.ApplyPreset(LdapPreset.ActiveDirectory); options.AttributeMap.Should().NotContainKey("custom"); options.AttributeMap.Should().ContainKey("externalId"); } // ── Validate delegation to ValidateConnection ── [Fact] public void Validate_EmptyServer_Throws() { var options = new LdapProviderOptions { Server = "", UserBaseDn = "dc=test", UserFilter = "(uid={0})" }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*Server*required*"); } [Fact] public void Validate_SslAndStartTls_Throws() { var options = new LdapProviderOptions { UseSsl = true, UseStartTls = true, UserBaseDn = "dc=test", UserFilter = "(uid={0})" }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*mutually exclusive*"); } // ── NormalizeAfterBind ── [Fact] public void NormalizeAfterBind_RestoresCaseInsensitiveComparer() { var options = new LdapProviderOptions(); // Simulate what IConfiguration.Bind() does: replace with case-sensitive dict options.AttributeMap = new Dictionary { ["ExternalId"] = "uid", ["DisplayName"] = "cn" }; options.AdditionalClaimsMap = new Dictionary { ["Department"] = "dept" }; options.AttributeMap.Comparer.Should().NotBe(StringComparer.OrdinalIgnoreCase); options.NormalizeAfterBind(); options.AttributeMap.Comparer.Should().Be(StringComparer.OrdinalIgnoreCase); options.AttributeMap["externalid"].Should().Be("uid"); options.AdditionalClaimsMap["department"].Should().Be("dept"); } [Fact] public void NormalizeAfterBind_AlreadyCaseInsensitive_NoOp() { var options = new LdapProviderOptions(); var originalMap = options.AttributeMap; options.NormalizeAfterBind(); options.AttributeMap.Should().BeSameAs(originalMap); } // ── CheckAccountStatus ── [Fact] public void CheckAccountStatus_DefaultFalse() { var options = new LdapProviderOptions(); options.CheckAccountStatus.Should().BeFalse(); } [Fact] public void ApplyPreset_AD_SetsCheckAccountStatusTrue() { var options = new LdapProviderOptions { UserBaseDn = "dc=test" }; options.ApplyPreset(LdapPreset.ActiveDirectory); options.CheckAccountStatus.Should().BeTrue(); options.UserFilter.Should().Contain("sAMAccountName"); } [Fact] public void ApplyPreset_OpenLDAP_DoesNotSetCheckAccountStatus() { var options = new LdapProviderOptions { UserBaseDn = "dc=test" }; options.ApplyPreset(LdapPreset.OpenLDAP); options.CheckAccountStatus.Should().BeFalse(); } } Path: redb-identity/tests/redb.Identity.Tests/Ldap/LdapProviderResilienceTests.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/Ldap/LdapProviderResilienceTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Core.Services; using redb.Identity.Ldap; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Ldap; /// /// Tests for LDAP provider resilience and provider chain ordering. /// These test the provider contract: exceptions are thrown (LoginService catches them), /// priority ordering, and domain-routed multi-provider scenarios. /// public class LdapProviderResilienceTests { // ── F: LDAP unavailable ── [Fact] public async Task AuthenticateAsync_UnreachableServer_ThrowsException() { // Provider with nonexistent host — should throw when LDAP call fails var options = new LdapProviderOptions { UserBaseDn = "ou=users,dc=test", UserFilter = "(uid={0})", Server = "192.0.2.1", // RFC 5737 TEST-NET — guaranteed unreachable Port = 389, OperationTimeoutSeconds = 2, ConnectTimeoutSeconds = 1 // pre-flight probe must fail fast }; options.ApplyPreset(LdapPreset.OpenLDAP); var provider = new LdapExternalUserProvider( options, NullLogger.Instance); // The provider should throw (not return null) — LoginService catches + skips var act = () => provider.AuthenticateAsync("alice", "password"); await act.Should().ThrowAsync(); } // ── G: Provider priority ordering ── [Fact] public void Providers_SortedByPriority_LowerFirst() { var providerA = new FakeExternalUserProvider { ProviderName = "A", Priority = 50 }; var providerB = new FakeExternalUserProvider { ProviderName = "B", Priority = 10 }; var providerC = new FakeExternalUserProvider { ProviderName = "C", Priority = 100 }; // Simulate what LoginService constructor does var sorted = new IExternalUserProvider[] { providerA, providerB, providerC } .OrderBy(p => p.Priority) .ToArray(); sorted[0].ProviderName.Should().Be("B"); sorted[1].ProviderName.Should().Be("A"); sorted[2].ProviderName.Should().Be("C"); } [Fact] public async Task ProviderChain_FirstMatchWins_OtherNotCalled() { var callLog = new List(); var provider1 = new FakeExternalUserProvider { ProviderName = "first", Priority = 10 }; provider1.UserHandlers["alice"] = pwd => { callLog.Add("first"); return pwd == "secret" ? ExternalAuthResult.Success("alice-ext", displayName: "Alice") : ExternalAuthResult.Failed("Bad password"); }; var provider2 = new FakeExternalUserProvider { ProviderName = "second", Priority = 20 }; provider2.UserHandlers["alice"] = pwd => { callLog.Add("second"); return ExternalAuthResult.Success("alice-2nd"); }; // Simulate the LoginService provider chain manually ExternalAuthResult? result = null; foreach (var p in new IExternalUserProvider[] { provider1, provider2 }.OrderBy(p => p.Priority)) { result = await p.AuthenticateAsync("alice", "secret"); if (result is not null) break; } result.Should().NotBeNull(); result!.Succeeded.Should().BeTrue(); result.ExternalId.Should().Be("alice-ext"); callLog.Should().Equal("first"); // second provider never called } [Fact] public async Task ProviderChain_FirstReturnsNull_SecondTried() { var callLog = new List(); var provider1 = new FakeExternalUserProvider { ProviderName = "skip", Priority = 10 }; // No handler for "bob" → returns null → skip var provider2 = new FakeExternalUserProvider { ProviderName = "catch", Priority = 20 }; provider2.UserHandlers["bob"] = pwd => { callLog.Add("catch"); return ExternalAuthResult.Success("bob-ext"); }; ExternalAuthResult? result = null; foreach (var p in new IExternalUserProvider[] { provider1, provider2 }.OrderBy(p => p.Priority)) { result = await p.AuthenticateAsync("bob", "password"); if (result is not null) break; } result.Should().NotBeNull(); result!.ExternalId.Should().Be("bob-ext"); callLog.Should().Equal("catch"); } [Fact] public async Task ProviderChain_FailedResult_StopsChain() { var provider1 = new FakeExternalUserProvider { ProviderName = "reject", Priority = 10 }; provider1.UserHandlers["alice"] = _ => ExternalAuthResult.Failed("Account locked"); var provider2 = new FakeExternalUserProvider { ProviderName = "fallback", Priority = 20 }; provider2.UserHandlers["alice"] = _ => ExternalAuthResult.Success("alice-fallback"); // Simulate LoginService chain: Failed means stop (don't try next) ExternalAuthResult? result = null; foreach (var p in new IExternalUserProvider[] { provider1, provider2 }.OrderBy(p => p.Priority)) { result = await p.AuthenticateAsync("alice", "password"); if (result is null) continue; break; // Both Success and Failed stop the chain } result.Should().NotBeNull(); result!.Succeeded.Should().BeFalse(); result.ErrorMessage.Should().Be("Account locked"); } // ── Domain routing with multiple providers ── [Fact] public async Task DomainRouting_MatchingDomain_AcceptsUser() { var options = new LdapProviderOptions { UserBaseDn = "ou=users,dc=corp", UserFilter = "(uid={0})", Server = "nonexistent.host", Domains = ["corp.test", "CORP"], ConnectTimeoutSeconds = 1 }; options.ApplyPreset(LdapPreset.OpenLDAP); var provider = new LdapExternalUserProvider( options, NullLogger.Instance); // UPN format: alice@corp.test → accepted (will throw connecting, which proves it wasn't filtered out) var act1 = () => provider.AuthenticateAsync("alice@corp.test", "password"); await act1.Should().ThrowAsync("matching domain should be accepted and attempt LDAP"); // NT format: CORP\alice → accepted var act2 = () => provider.AuthenticateAsync("CORP\\alice", "password"); await act2.Should().ThrowAsync("matching NT domain should be accepted"); } [Fact] public async Task DomainRouting_NonMatchingDomain_ReturnsNull() { var options = new LdapProviderOptions { UserBaseDn = "ou=users,dc=corp", UserFilter = "(uid={0})", Server = "nonexistent.host", Domains = ["corp.test"], ConnectTimeoutSeconds = 1 }; options.ApplyPreset(LdapPreset.OpenLDAP); var provider = new LdapExternalUserProvider( options, NullLogger.Instance); var result = await provider.AuthenticateAsync("alice@other.test", "password"); result.Should().BeNull("non-matching domain should skip to next provider"); var result2 = await provider.AuthenticateAsync("OTHER\\alice", "password"); result2.Should().BeNull("non-matching NT domain should skip"); } [Fact] public async Task DomainRouting_NoDomainHint_PassesThrough() { var options = new LdapProviderOptions { UserBaseDn = "ou=users,dc=corp", UserFilter = "(uid={0})", Server = "nonexistent.host", Domains = ["corp.test"], ConnectTimeoutSeconds = 1 }; options.ApplyPreset(LdapPreset.OpenLDAP); var provider = new LdapExternalUserProvider( options, NullLogger.Instance); // Bare username with no domain hint → pass through (attempt LDAP) var act = () => provider.AuthenticateAsync("alice", "password"); await act.Should().ThrowAsync("bare username should still be tried"); } [Fact] public void LdapProvider_Priority_IsConfigurable() { var options = new LdapProviderOptions { UserBaseDn = "dc=test", UserFilter = "(uid={0})", Priority = 42 }; var provider = new LdapExternalUserProvider( options, NullLogger.Instance); provider.Priority.Should().Be(42); } } Path: redb-identity/tests/redb.Identity.Tests/Ldap/LdapServiceExtensionsTests.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/Ldap/LdapServiceExtensionsTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Core.Services; using redb.Identity.Ldap; using Xunit; namespace redb.Identity.Tests.Ldap; /// /// Unit tests for DI registration. /// public class LdapServiceExtensionsTests { private static ServiceCollection BaseServices() { var sc = new ServiceCollection(); sc.AddSingleton(NullLoggerFactory.Instance); sc.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>)); return sc; } [Fact] public async Task AddRedbIdentityLdap_WithOptions_RegistersProvider() { var sc = BaseServices(); var options = new LdapProviderOptions { UserBaseDn = "dc=test", UserFilter = "(uid={0})", ProviderName = "ldap:test" }; sc.AddRedbIdentityLdap(options); await using var sp = sc.BuildServiceProvider(); var provider = sp.GetRequiredService(); provider.Should().BeOfType(); provider.ProviderName.Should().Be("ldap:test"); } [Fact] public void AddRedbIdentityLdap_WithOptions_RegistersOptionsAsSingleton() { var sc = BaseServices(); var options = new LdapProviderOptions { UserBaseDn = "dc=test", UserFilter = "(uid={0})", Priority = 42 }; sc.AddRedbIdentityLdap(options); using var sp = sc.BuildServiceProvider(); var resolved = sp.GetRequiredKeyedService("ldap"); resolved.Should().BeSameAs(options); resolved.Priority.Should().Be(42); } [Fact] public async Task AddRedbIdentityLdap_WithAction_ConfiguresAndRegisters() { var sc = BaseServices(); sc.AddRedbIdentityLdap(o => { o.UserBaseDn = "ou=people,dc=corp"; o.UserFilter = "(sAMAccountName={0})"; o.ProviderName = "ldap:corp"; o.Server = "ldap.corp.test"; }); await using var sp = sc.BuildServiceProvider(); var provider = sp.GetRequiredService(); provider.ProviderName.Should().Be("ldap:corp"); var options = sp.GetRequiredKeyedService("ldap:corp"); options.Server.Should().Be("ldap.corp.test"); } [Fact] public async Task AddRedbIdentityLdap_WithConfiguration_BindsSection() { var config = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { ["Server"] = "ldap.example.com", ["Port"] = "636", ["UseSsl"] = "true", ["UserBaseDn"] = "ou=users,dc=example,dc=com", ["UserFilter"] = "(uid={0})", ["BindDn"] = "cn=svc,dc=example,dc=com", ["BindPassword"] = "secret", ["ProviderName"] = "ldap:bound" }) .Build(); var sc = BaseServices(); sc.AddRedbIdentityLdap(config); await using var sp = sc.BuildServiceProvider(); var provider = sp.GetRequiredService(); provider.ProviderName.Should().Be("ldap:bound"); var options = sp.GetRequiredKeyedService("ldap:bound"); options.Server.Should().Be("ldap.example.com"); options.Port.Should().Be(636); options.UseSsl.Should().BeTrue(); options.BindDn.Should().Be("cn=svc,dc=example,dc=com"); } [Fact] public void AddRedbIdentityLdap_NullOptions_ThrowsArgumentNull() { var sc = BaseServices(); var act = () => sc.AddRedbIdentityLdap((LdapProviderOptions)null!); act.Should().Throw(); } [Fact] public void AddRedbIdentityLdap_InvalidOptions_ThrowsOnResolve() { var sc = BaseServices(); sc.AddRedbIdentityLdap(o => { o.UserBaseDn = ""; // invalid }); using var sp = sc.BuildServiceProvider(); // Provider constructor calls Validate() which throws var act = () => sp.GetRequiredService(); act.Should().Throw().WithMessage("*UserBaseDn*"); } // ── Multi-provider ── [Fact] public async Task MultiProvider_ResolvesAllProviders() { var sc = BaseServices(); sc.AddRedbIdentityLdap(new LdapProviderOptions { ProviderName = "ldap:corp", UserBaseDn = "dc=corp", UserFilter = "(uid={0})", Server = "corp.test" }); sc.AddRedbIdentityLdap(new LdapProviderOptions { ProviderName = "ldap:vendor", UserBaseDn = "dc=vendor", UserFilter = "(uid={0})", Server = "vendor.test" }); await using var sp = sc.BuildServiceProvider(); var providers = sp.GetServices().ToArray(); providers.Should().HaveCount(2); providers.Select(p => p.ProviderName).Should().BeEquivalentTo("ldap:corp", "ldap:vendor"); } [Fact] public void MultiProvider_KeyedOptionsAreSeparate() { var sc = BaseServices(); sc.AddRedbIdentityLdap(new LdapProviderOptions { ProviderName = "ldap:a", UserBaseDn = "dc=a", UserFilter = "(uid={0})", Server = "a.test", Priority = 10 }); sc.AddRedbIdentityLdap(new LdapProviderOptions { ProviderName = "ldap:b", UserBaseDn = "dc=b", UserFilter = "(uid={0})", Server = "b.test", Priority = 20 }); using var sp = sc.BuildServiceProvider(); var optA = sp.GetRequiredKeyedService("ldap:a"); var optB = sp.GetRequiredKeyedService("ldap:b"); optA.Server.Should().Be("a.test"); optA.Priority.Should().Be(10); optB.Server.Should().Be("b.test"); optB.Priority.Should().Be(20); } // ── Health check registration ── [Fact] public void AddRedbIdentityLdapCheck_RegistersHealthCheck() { var sc = BaseServices(); sc.AddHealthChecks() .AddRedbIdentityLdapCheck(); using var sp = sc.BuildServiceProvider(); var healthCheckService = sp.GetService(); healthCheckService.Should().NotBeNull(); } } Path: redb-identity/tests/redb.Identity.Tests/Ldap/LdapSyncTests.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/Ldap/LdapSyncTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Ldap; using Xunit; namespace redb.Identity.Tests.Ldap; /// /// Unit tests for , , /// and sync DI registration. /// public class LdapSyncTests { // ── LdapSyncOptions ── [Fact] public void SyncOptions_Defaults_AreReasonable() { var options = new LdapSyncOptions(); options.RouteId.Should().Be("ldap-sync"); options.Server.Should().Be("localhost"); options.Port.Should().Be(389); options.PollIntervalMs.Should().Be(60_000); options.ChangeTrackingMode.Should().Be("ModifyTimestamp"); options.InitialLoad.Should().BeTrue(); options.DetectDeletions.Should().BeTrue(); options.FullSyncInterval.Should().Be(10); options.ProviderName.Should().Be("ldap-sync"); options.SyncGroups.Should().BeFalse(); options.DisableDeletedUsers.Should().BeTrue(); options.UserFilter.Should().Be("(objectClass=inetOrgPerson)"); } [Fact] public void SyncOptions_Validate_ThrowsOnEmptyBaseDn() { var options = new LdapSyncOptions { UserBaseDn = "" }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*UserBaseDn*"); } [Fact] public void SyncOptions_Validate_ThrowsOnInvalidPollInterval() { var options = new LdapSyncOptions { UserBaseDn = "dc=test", PollIntervalMs = 0 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*PollIntervalMs*"); } [Fact] public void SyncOptions_Validate_ThrowsOnNegativePollInterval() { var options = new LdapSyncOptions { UserBaseDn = "dc=test", PollIntervalMs = -1000 }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*PollIntervalMs*"); } [Fact] public void SyncOptions_Validate_ThrowsOnInvalidChangeTrackingMode() { var options = new LdapSyncOptions { UserBaseDn = "dc=test", ChangeTrackingMode = "invalid_mode" }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*ChangeTrackingMode*"); } [Theory] [InlineData("ModifyTimestamp")] [InlineData("modifytimestamp")] [InlineData("Usn")] [InlineData("Persistent")] public void SyncOptions_Validate_AcceptsValidChangeTrackingModes(string mode) { var options = new LdapSyncOptions { UserBaseDn = "dc=test", ChangeTrackingMode = mode }; var act = () => options.Validate(); act.Should().NotThrow(); } [Fact] public void SyncOptions_Validate_ThrowsOnEmptyServer() { var options = new LdapSyncOptions { UserBaseDn = "dc=test", Server = "" }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*Server*required*"); } [Fact] public void SyncOptions_Validate_ThrowsOnSslAndStartTls() { var options = new LdapSyncOptions { UserBaseDn = "dc=test", UseSsl = true, UseStartTls = true }; var act = () => options.Validate(); act.Should().Throw().WithMessage("*mutually exclusive*"); } [Fact] public void SyncOptions_Validate_PassesWithValidBaseDn() { var options = new LdapSyncOptions { UserBaseDn = "ou=users,dc=test" }; var act = () => options.Validate(); act.Should().NotThrow(); } // ── LdapSyncRouteBuilder ── [Fact] public void SyncRouteBuilder_Constructor_ValidatesOptions() { var act = () => new LdapSyncRouteBuilder(null!); act.Should().Throw(); } [Fact] public void SyncRouteBuilder_Constructor_ValidatesBaseDn() { var options = new LdapSyncOptions { UserBaseDn = "" }; var act = () => new LdapSyncRouteBuilder(options); act.Should().Throw().WithMessage("*UserBaseDn*"); } [Fact] public void SyncRouteBuilder_Constructor_AcceptsValidOptions() { var options = new LdapSyncOptions { UserBaseDn = "ou=users,dc=test", Server = "ldap.test", PollIntervalMs = 30_000 }; var builder = new LdapSyncRouteBuilder(options); builder.Should().NotBeNull(); } // ── Sync DI registration ── [Fact] public void AddRedbIdentityLdapSync_RegistersHandler() { var sc = new ServiceCollection(); sc.AddSingleton(NullLoggerFactory.Instance); sc.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>)); sc.AddRedbIdentityLdapSync(o => { o.UserBaseDn = "ou=users,dc=test"; o.ProviderName = "ldap-sync:corp"; }); using var sp = sc.BuildServiceProvider(); var options = sp.GetRequiredService(); options.ProviderName.Should().Be("ldap-sync:corp"); // Handler requires IRedbService which isn't registered here, // but the registration itself should succeed var descriptor = sc.FirstOrDefault(d => d.ServiceType == typeof(LdapSyncHandler)); descriptor.Should().NotBeNull(); descriptor!.Lifetime.Should().Be(ServiceLifetime.Scoped); } [Fact] public void AddRedbIdentityLdapSync_WithGroups_RegistersGroupMapper() { var sc = new ServiceCollection(); sc.AddSingleton(NullLoggerFactory.Instance); sc.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>)); sc.AddRedbIdentityLdapSync(o => { o.UserBaseDn = "ou=users,dc=test"; o.SyncGroups = true; o.GroupMapperOptions.MemberRole = "viewer"; }); using var sp = sc.BuildServiceProvider(); var groupOptions = sp.GetRequiredService(); groupOptions.MemberRole.Should().Be("viewer"); var descriptor = sc.FirstOrDefault(d => d.ServiceType == typeof(LdapGroupMapper)); descriptor.Should().NotBeNull(); descriptor!.Lifetime.Should().Be(ServiceLifetime.Scoped); } [Fact] public void AddRedbIdentityLdapSync_WithoutGroups_NoGroupMapper() { var sc = new ServiceCollection(); sc.AddRedbIdentityLdapSync(o => { o.UserBaseDn = "ou=users,dc=test"; o.SyncGroups = false; }); var descriptor = sc.FirstOrDefault(d => d.ServiceType == typeof(LdapGroupMapper)); descriptor.Should().BeNull(); } } Path: redb-identity/tests/redb.Identity.Tests/Management/ApplicationManagementClientSecretE2ETests.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/Management/ApplicationManagementClientSecretE2ETests.cs ---- using AwesomeAssertions; using redb.Identity.Contracts.Applications; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Management; /// /// C12 regression: a confidential application created via the management API must be /// usable for client_credentials authentication via the token endpoint. /// /// Before the fix, /// hashed the secret with a custom PBKDF2 hasher and persisted the row directly via /// IRedbService.SaveAsync, bypassing OpenIddict. The token endpoint validates the secret /// with OpenIddict's BCrypt hasher — algorithms did not match, so the credentials were unusable. /// [Collection("ProductionBootstrap")] public class ApplicationManagementClientSecretE2ETests { private readonly ProductionBootstrapFixture _fx; public ApplicationManagementClientSecretE2ETests(ProductionBootstrapFixture fx) => _fx = fx; [Fact] public async Task CreatedClient_CanAuthenticate_ViaClientCredentials() { // 1. Create client through management API (the path users hit via REST). var clientId = $"c12-mgmt-{Guid.NewGuid():N}"; const string clientSecret = "Sup3rS3cret-!@#"; var createBody = new CreateApplicationRequest { ClientId = clientId, ClientSecret = clientSecret, ClientType = "confidential", DisplayName = "C12 management-api created", Permissions = [ "ept:token", "gt:client_credentials" ] }; var createExchange = await _fx.RequestWithHeaders( IdentityEndpoints.ManageApps, createBody, new Dictionary { ["operation"] = "create" }); var createOut = createExchange.HasOut ? createExchange.Out!.Body : createExchange.In.Body; createOut.Should().BeOfType( $"create should succeed; got {createOut?.GetType().Name}: {createOut}"); // 2. Use the *plain* secret to obtain an access_token. var tokenBody = new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = clientId, ["client_secret"] = clientSecret }; var tokenResult = await _fx.Request(IdentityEndpoints.Token, tokenBody); var tokenResponse = tokenResult.Should().BeOfType>().Subject; tokenResponse.Should().NotContainKey("error", because: $"client created via management API must authenticate; got {(tokenResponse.ContainsKey("error_description") ? tokenResponse["error_description"] : "n/a")}"); tokenResponse.Should().ContainKey("access_token"); tokenResponse["access_token"]!.ToString().Should().NotBeNullOrEmpty(); } [Fact] public async Task CreatedClient_WrongSecret_ReturnsInvalidClient() { var clientId = $"c12-mgmt-wrong-{Guid.NewGuid():N}"; const string clientSecret = "RealSecret-12345"; var createExchange = await _fx.RequestWithHeaders( IdentityEndpoints.ManageApps, new CreateApplicationRequest { ClientId = clientId, ClientSecret = clientSecret, ClientType = "confidential", DisplayName = "C12 wrong-secret negative", Permissions = ["ept:token", "gt:client_credentials"] }, new Dictionary { ["operation"] = "create" }); (createExchange.HasOut ? createExchange.Out!.Body : createExchange.In.Body) .Should().BeOfType(); var tokenResult = await _fx.Request(IdentityEndpoints.Token, new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = clientId, ["client_secret"] = "wrong-secret" }); var response = tokenResult.Should().BeOfType>().Subject; response.Should().ContainKey("error"); response["error"]!.ToString().Should().Be("invalid_client"); } } Path: redb-identity/tests/redb.Identity.Tests/Management/ApplicationManagementTests.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/Management/ApplicationManagementTests.cs ---- using AwesomeAssertions; using NSubstitute; using OpenIddict.Abstractions; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Applications; using redb.Identity.Contracts.Common; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Management; public class ApplicationManagementTests { private readonly IRedbService _redb = Substitute.For(); private readonly IOpenIddictApplicationManager _appManager = Substitute.For(); private readonly ApplicationManagementProcessor _processor; public ApplicationManagementTests() { var context = MockRouteContext.CreateWithServices(_redb, (typeof(IOpenIddictApplicationManager), _appManager)); _processor = new ApplicationManagementProcessor(context); } private static TestExchange CreateExchange(string operation, object? body = null) { var exchange = new TestExchange(); exchange.In.Headers["operation"] = operation; if (body != null) exchange.In.Body = body; return exchange; } // ── Create ── [Fact] public async Task Create_ValidInput_ReturnsApplicationResponse() { // 1st FindByClientIdAsync (duplicate check) -> null; // 2nd FindByClientIdAsync (read-back after CreateAsync) -> created entity. var created = MockRedbQuery.CreateObject(42, "My App", new ApplicationProps { ClientId = "my-app", ClientType = "confidential" }); _appManager.FindByClientIdAsync("my-app", Arg.Any()) .Returns(default(object), created); _appManager.CreateAsync(Arg.Any(), Arg.Any()) .Returns(created); var exchange = CreateExchange("create", new CreateApplicationRequest { ClientId = "my-app", ClientSecret = "secret", DisplayName = "My App", ClientType = "confidential" }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.ClientId.Should().Be("my-app"); resp.DisplayName.Should().Be("My App"); resp.ClientType.Should().Be("confidential"); exchange.Properties["identity-event-type"].Should().Be("ClientRegistered"); // Verify CreateAsync was called with the descriptor that carries the *plain* secret — // OpenIddict hashes it internally via its own (BCrypt) mechanism. await _appManager.Received(1).CreateAsync( Arg.Is(d => d.ClientId == "my-app" && d.ClientSecret == "secret"), Arg.Any()); } [Theory] [InlineData("https://127.0.0.1/bc-logout")] // loopback [InlineData("https://169.254.169.254/bc-logout")] // link-local [InlineData("http://203.0.113.10/bc-logout")] // plain http while https is required public async Task Create_And_Update_Refuse_A_BackchannelLogoutUri_The_Guard_Refuses(string uri) { var create = CreateExchange("create", new CreateApplicationRequest { ClientId = "bcl-app", ClientSecret = "secret", ClientType = "confidential", BackchannelLogoutUri = uri, }); await _processor.Process(create); create.Out!.Body.Should().BeOfType().Subject.Error.Should().Be("validation_error"); await _appManager.DidNotReceive().CreateAsync(Arg.Any(), Arg.Any()); var app = MockRedbQuery.CreateObject(9, "Bcl app", new ApplicationProps { ClientId = "bcl-app-2", ClientType = "confidential" }); _redb.LoadAsync(9).Returns(app); var update = CreateExchange("update", new UpdateApplicationRequest { Id = "9", BackchannelLogoutUri = uri }); await _processor.Process(update); update.Out!.Body.Should().BeOfType().Subject.Error.Should().Be("validation_error"); app.Props.BackchannelLogoutUri.Should().BeNull(); } [Fact] public async Task Create_MissingClientId_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateApplicationRequest { ClientId = "" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } [Fact] public async Task Create_InvalidClientType_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateApplicationRequest { ClientId = "app1", ClientType = "invalid_type" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } [Fact] public async Task Create_InvalidRedirectUri_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateApplicationRequest { ClientId = "app1", RedirectUris = new[] { "not-a-uri" } }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } [Fact] public async Task Create_DuplicateClientId_ReturnsDuplicateError() { var existing = MockRedbQuery.CreateObject(1, "existing", new ApplicationProps { ClientId = "dup-app" }); _appManager.FindByClientIdAsync("dup-app", Arg.Any()) .Returns(existing); var exchange = CreateExchange("create", new CreateApplicationRequest { ClientId = "dup-app" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("duplicate"); await _appManager.DidNotReceive().CreateAsync( Arg.Any(), Arg.Any()); } // ── Read ── [Fact] public async Task Read_ById_ReturnsApplication() { var app = MockRedbQuery.CreateObject(10, "Test App", new ApplicationProps { ClientId = "test-read" }); _redb.LoadAsync(10).Returns(app); var exchange = CreateExchange("read", new Dictionary { ["id"] = 10L }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.ClientId.Should().Be("test-read"); resp.Id.Should().Be("10"); } [Fact] public async Task Read_ByClientId_ReturnsApplication() { var app = MockRedbQuery.CreateObject(10, "Test App", new ApplicationProps { ClientId = "by-cid" }); // V4-UNIQUE: read-by-clientId is a GetByUniqueAsync probe now. _redb.GetByUniqueAsync( Arg.Any>>(), "by-cid", Arg.Any()) .Returns(app); var exchange = CreateExchange("read", new Dictionary { ["clientId"] = "by-cid" }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.ClientId.Should().Be("by-cid"); } [Fact] public async Task Read_NotFound_ReturnsNotFoundError() { _redb.LoadAsync(999).Returns((RedbObject?)null); var exchange = CreateExchange("read", new Dictionary { ["id"] = 999L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("not_found"); } // ── Update ── [Fact] public async Task Update_ValidInput_ReturnsUpdatedApplication() { var app = MockRedbQuery.CreateObject(5, "Old Name", new ApplicationProps { ClientId = "upd-app", ClientType = "confidential" }); _redb.LoadAsync(5).Returns(app); _redb.SaveAsync(Arg.Any>()).Returns(5L); var exchange = CreateExchange("update", new UpdateApplicationRequest { Id = "5", DisplayName = "New Name", ClientType = "public" }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.DisplayName.Should().Be("New Name"); resp.ClientType.Should().Be("public"); exchange.Properties["identity-event-type"].Should().Be("ClientUpdated"); } [Fact] public async Task Update_RequestUris_AreStored_Echoed_AndCleared() { var app = MockRedbQuery.CreateObject(6, "Jar app", new ApplicationProps { ClientId = "jar-app", ClientType = "confidential" }); _redb.LoadAsync(6).Returns(app); _redb.SaveAsync(Arg.Any>()).Returns(6L); var set = CreateExchange("update", new UpdateApplicationRequest { Id = "6", RequestUris = ["https://app.example.com/ro.jwt#hash", "https://app.example.com/ro.jwt#hash", "https://app.example.com/ro2.jwt"], }); await _processor.Process(set); set.Out!.Body.Should().BeOfType().Subject.RequestUris .Should().Equal("https://app.example.com/ro.jwt#hash", "https://app.example.com/ro2.jwt"); var leave = CreateExchange("update", new UpdateApplicationRequest { Id = "6", DisplayName = "Renamed" }); await _processor.Process(leave); app.Props.RequestUris.Should().HaveCount(2, "null leaves the list alone"); var clear = CreateExchange("update", new UpdateApplicationRequest { Id = "6", RequestUris = [] }); await _processor.Process(clear); app.Props.RequestUris.Should().BeNull("an empty array clears the list"); } [Theory] [InlineData("not a uri")] [InlineData("ftp://app.example.com/ro.jwt")] [InlineData("https://user:pw@app.example.com/ro.jwt")] public async Task Update_InvalidRequestUri_IsRefused(string requestUri) { var app = MockRedbQuery.CreateObject(8, "Jar app", new ApplicationProps { ClientId = "jar-app-2", ClientType = "confidential" }); _redb.LoadAsync(8).Returns(app); var exchange = CreateExchange("update", new UpdateApplicationRequest { Id = "8", RequestUris = [requestUri] }); await _processor.Process(exchange); exchange.Out!.Body.Should().BeOfType().Subject.Error.Should().Be("validation_error"); app.Props.RequestUris.Should().BeNull(); await _redb.DidNotReceive().SaveAsync(Arg.Any>()); } [Fact] public async Task Update_NotFound_ReturnsNotFoundError() { _redb.LoadAsync(999).Returns((RedbObject?)null); var exchange = CreateExchange("update", new UpdateApplicationRequest { Id = "999" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("not_found"); } // ── Delete ── [Fact] public async Task Delete_ValidId_ReturnsSuccess() { // The delete looks the record up first; it exists and is of this resource. _redb.LoadAsync(7).Returns(new RedbObject(new ApplicationProps()) { id = 7 }); _redb.DeleteAsync(7).Returns(true); var exchange = CreateExchange("delete", new Dictionary { ["id"] = 7L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Success.Should().BeTrue(); exchange.Properties["identity-event-type"].Should().Be("ClientDeleted"); } [Fact] public async Task Delete_MissingId_ReturnsValidationError() { var exchange = CreateExchange("delete", new Dictionary { ["id"] = 0L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } // ── List ── [Fact] public async Task List_ReturnsPaginatedResults() { var items = Enumerable.Range(1, 5) .Select(i => MockRedbQuery.CreateObject(i, $"App{i}", new ApplicationProps { ClientId = $"app-{i}" })) .ToList(); MockRedbQuery.Setup(_redb, items); var exchange = CreateExchange("list", new ListRequest { Offset = 0, Count = 3 }); await _processor.Process(exchange); var result = exchange.Out!.Body.Should().BeOfType>().Subject; result.Total.Should().Be(5); result.Items.Should().HaveCount(3); } // ── Unknown operation ── [Fact] public async Task UnknownOperation_ReturnsInvalidOperation() { var exchange = CreateExchange("kaboom"); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("invalid_operation"); } // ── Missing operation header ── [Fact] public async Task MissingOperationHeader_Throws() { var exchange = new TestExchange(); await Assert.ThrowsAsync(() => _processor.Process(exchange)); } // ── Input Validation ── [Fact] public async Task Create_InvalidConsentType_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateApplicationRequest { ClientId = "app1", ConsentType = "bogus" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("ConsentType"); } [Fact] public async Task Create_InvalidApplicationType_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateApplicationRequest { ClientId = "app1", ApplicationType = "bogus" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("ApplicationType"); } [Fact] public async Task Create_InvalidPostLogoutRedirectUri_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateApplicationRequest { ClientId = "app1", PostLogoutRedirectUris = new[] { "not-a-uri" } }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("post-logout redirect URI"); } [Fact] public async Task Create_DisplayNameTooLong_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateApplicationRequest { ClientId = "app1", DisplayName = new string('a', 257) }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("DisplayName"); } [Fact] public async Task Create_ClientIdWithInvalidChars_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateApplicationRequest { ClientId = "app with spaces!" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("invalid characters"); } } Path: redb-identity/tests/redb.Identity.Tests/Management/OneTimeSecretsTests.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/Management/OneTimeSecretsTests.cs ---- using System.Reflection; using System.Text.Json.Serialization; using System.Text.RegularExpressions; using AwesomeAssertions; using redb.Identity.Contracts.Applications; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Mfa; using redb.Identity.Contracts.Registration; using redb.Identity.Contracts.Scim; using redb.Identity.Contracts.Webhooks; using redb.Identity.Core.Routes.Processors; using Xunit; namespace redb.Identity.Tests.Management; /// /// The declaration that keeps one-time secrets out of the idempotency cache: the /// marker on result members, and , which reads it. /// public class OneTimeSecretsTests { public static TheoryData SecretBearing() => new() { { "webhook created", new WebhookSubscriptionResponse { Id = 1, Url = "http://x", HmacSecret = "s" } }, { "webhook secret rotated", new WebhookSecretRotatedResponse { HmacSecret = "s" } }, { "application secret rotated", new ApplicationResponse { ClientId = "c", NewSecret = "s" } }, { "client registered", new DynamicRegistrationResponse { ClientId = "c", ClientSecret = "s" } }, { "client registered, public", new DynamicRegistrationResponse { ClientId = "c", RegistrationAccessToken = "t" } }, { "mfa setup", new MfaSetupResponse { Method = "totp", SecretBase32 = "ABC" } }, { "mfa setup, otp method", new MfaSetupResponse { Method = "email", SetupToken = "t" } }, { "mfa confirmed", new MfaConfirmedResponse { RecoveryCodes = new[] { "r1" } } }, { "recovery codes", new MfaRecoveryCodesResponse { RecoveryCodes = new[] { "r1" } } }, { "scim user with password", new ScimUser { UserName = "u", Password = "p" } }, { "in a page", new PagedResult { Items = new List { new() { Url = "http://x", HmacSecret = "s" } } } }, }; public static TheoryData SecretFree() => new() { { "nothing", null }, { "webhook read back", new WebhookSubscriptionResponse { Id = 1, Url = "http://x", HmacSecret = null, HasHmacSecret = true } }, { "webhook with an empty secret", new WebhookSubscriptionResponse { Url = "http://x", HmacSecret = "" } }, { "application read back", new ApplicationResponse { ClientId = "c" } }, { "recovery codes, none", new MfaRecoveryCodesResponse { RecoveryCodes = Array.Empty() } }, { "scim user", new ScimUser { UserName = "u" } }, { "a page of webhooks", new PagedResult { Items = new List { new() { Url = "http://x" } } } }, { "success", new SuccessResponse() }, { "a dictionary", new Dictionary { ["hmacSecret"] = "s" } }, { "a string", "s" }, }; [Theory, MemberData(nameof(SecretBearing))] public void A_set_marked_member_is_found(string @case, object result) => OneTimeSecrets.Carries(result).Should().BeTrue(@case); [Theory, MemberData(nameof(SecretFree))] public void An_answer_without_a_set_marked_member_is_kept(string @case, object? result) => OneTimeSecrets.Carries(result).Should().BeFalse(@case); // Member names that look like a credential or a one-time value. A Contracts result member whose name matches // must carry [OneTimeSecret] or be listed below with the reason it is not one. private static readonly Regex SecretLooking = new( "secret|token|password|passcode|recovery|otp|qr|private_?key|api_?key|(^|_)code(s)?$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); private static readonly Dictionary NotSecrets = new() { // Flags that say whether a secret exists; the secret itself is never in these answers. ["WebhookSubscriptionResponse.HasHmacSecret"] = "flag", ["FederationProviderResponse.HasSecret"] = "flag", ["SecretWithheldReplayResponse.SecretWithheld"] = "flag of the replay answer itself", // Kinds, methods, settings and addresses. ["IntrospectionResponse.TokenType"] = "token type name (RFC 7662)", ["TokenResponse.TokenType"] = "token type name (Bearer)", ["DynamicRegistrationResponse.TokenEndpointAuthMethod"] = "authentication method name", ["DynamicRegistrationResponse.ClientSecretExpiresAt"] = "expiry time of the secret", ["DynamicRegistrationResponse.PasswordResetUris"] = "redirect addresses", ["ApplicationResponse.PasswordResetUris"] = "redirect addresses", ["OAuth2EndpointOverrides.TokenEndpoint"] = "endpoint address", ["ScimServiceProviderConfig.ChangePassword"] = "SCIM capability flag", ["ClaimDefinitionResponse.EmitOnIdToken"] = "claim placement flag", ["ClaimDefinitionResponse.EmitOnAccessToken"] = "claim placement flag", ["ApplicationResponse.AccessTokenLifetimeSeconds"] = "lifetime setting", ["ApplicationResponse.RefreshTokenLifetimeSeconds"] = "lifetime setting", ["ApplicationResponse.IdentityTokenLifetimeSeconds"] = "lifetime setting", ["ApplicationResponse.IdTokenAudiences"] = "audience names", ["ApplicationResponse.AccessTokenAudiences"] = "audience names", // Counts. ["TokenPrunePreview.WouldPruneTokens"] = "count", ["TokenPruneResult.PrunedTokens"] = "count", ["MfaOtpPruneResult.PrunedMfaOtp"] = "count", ["MfaStatusResponse.RecoveryCodesRemaining"] = "count", // Optimistic concurrency stamps, sent back on update; they grant nothing. ["ScopeResponse.ConcurrencyToken"] = "concurrency stamp", ["ApplicationResponse.ConcurrencyToken"] = "concurrency stamp", // Configuration bound from settings, never an answer of a route. ["FederationProviderConfig.ClientSecret"] = "configuration, not a result", }; [Fact] public void Every_secret_looking_result_member_is_marked_or_explained() { var contracts = typeof(OneTimeSecretAttribute).Assembly; var unmarked = new List(); foreach (var type in contracts.GetExportedTypes()) { if (!type.IsClass || type.IsAbstract || typeof(Attribute).IsAssignableFrom(type)) continue; // Requests are what callers send; they are not answers and never reach the cache. if (type.Name.EndsWith("Request", StringComparison.Ordinal)) continue; foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var json = property.GetCustomAttribute()?.Name ?? property.Name; if (!SecretLooking.IsMatch(property.Name) && !SecretLooking.IsMatch(json)) continue; if (property.IsDefined(typeof(OneTimeSecretAttribute), inherit: true)) continue; var name = $"{type.Name}.{property.Name}"; if (!NotSecrets.ContainsKey(name)) unmarked.Add(name); } } string.Join(", ", unmarked).Should().BeEmpty( "a result member that looks like a secret is marked [OneTimeSecret], so the idempotency cache never keeps it, " + "or it is listed in NotSecrets with the reason it is not one"); } } Path: redb-identity/tests/redb.Identity.Tests/Management/ResultContractsJsonTests.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/Management/ResultContractsJsonTests.cs ---- using System.Text.Encodings.Web; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Sessions; using redb.Identity.Contracts.Tokens; using Xunit; namespace redb.Identity.Tests.Management; /// /// The result types of the management and cleanup routes write the JSON those routes wrote when their bodies /// were anonymous objects, under every option set a controller dispatcher serializes with: the HTTP dispatcher /// names members camelCase, the gRPC one writes names as declared, so the names are pinned on the types and an /// absent optional member stays absent. The wire tests (ManagementResultWireTests, GrpcManagementResultWireTests) /// prove the routes a caller reaches; these cover every type, including the session cleanup that only a timer runs. /// public class ResultContractsJsonTests { // The option sets of redb.Route.Controllers: HttpControllerDispatcher's default and GrpcControllerDispatcher's. private static readonly JsonSerializerOptions HttpDispatcher = new() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; private static readonly JsonSerializerOptions GrpcDispatcher = new() { PropertyNameCaseInsensitive = true }; public static TheoryData OptionSets => new() { "http", "grpc", "default" }; private static string Write(object value, string options) => options switch { "http" => JsonSerializer.Serialize(value, HttpDispatcher), "grpc" => JsonSerializer.Serialize(value, GrpcDispatcher), _ => JsonSerializer.Serialize(value), }; [Theory, MemberData(nameof(OptionSets))] public void The_error_document(string options) => Write(new ErrorResponse { Error = "invalid_operation", ErrorDescription = "Unknown operation: nuke" }, options) .Should().Be("""{"error":"invalid_operation","error_description":"Unknown operation: nuke"}"""); [Theory, MemberData(nameof(OptionSets))] public void Success_alone(string options) => Write(new SuccessResponse(), options).Should().Be("""{"success":true}"""); [Theory, MemberData(nameof(OptionSets))] public void Success_with_the_sessions_revoked(string options) => Write(new SuccessResponse { SessionsRevoked = 2 }, options).Should().Be("""{"success":true,"sessionsRevoked":2}"""); [Theory, MemberData(nameof(OptionSets))] public void Success_with_the_consents_revoked(string options) => Write(new SuccessResponse { Revoked = 1 }, options).Should().Be("""{"success":true,"revoked":1}"""); [Theory, MemberData(nameof(OptionSets))] public void The_revoked_count(string options) => Write(new RevokedCountResponse { RevokedCount = 3 }, options).Should().Be("""{"revokedCount":3}"""); [Theory, MemberData(nameof(OptionSets))] public void The_token_prune(string options) => Write(new TokenPruneResult { PrunedTokens = 5, PrunedAuthorizations = 2 }, options) .Should().Be("""{"prunedTokens":5,"prunedAuthorizations":2}"""); [Theory, MemberData(nameof(OptionSets))] public void The_token_prune_preview(string options) => Write(new TokenPrunePreview { WouldPruneTokens = 5, WouldPruneAuthorizations = 2, Threshold = new DateTimeOffset(2026, 11, 10, 8, 30, 0, TimeSpan.Zero), }, options).Should().Be( """{"dryRun":true,"wouldPruneTokens":5,"wouldPruneAuthorizations":2,"threshold":"2026-11-10T08:30:00+00:00"}"""); [Theory, MemberData(nameof(OptionSets))] public void The_session_prune(string options) => Write(new SessionPruneResult { PrunedSessions = 4, ExpiredActiveSessions = 1 }, options) .Should().Be("""{"prunedSessions":4,"expiredActiveSessions":1}"""); } Path: redb-identity/tests/redb.Identity.Tests/Management/ResultContractsParityTests.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/Management/ResultContractsParityTests.cs ---- using System.Text.Encodings.Web; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Contracts.ClaimMappers; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Consents; using redb.Identity.Contracts.Federation; using redb.Identity.Contracts.Groups; using redb.Identity.Contracts.Mfa; using redb.Identity.Contracts.Sessions; using redb.Identity.Contracts.SigningKeys; using redb.Identity.Contracts.Tokens; using redb.Identity.Contracts.Users; using redb.Identity.Contracts.Validation; using redb.Identity.Contracts.Webhooks; using Xunit; namespace redb.Identity.Tests.Management; /// /// Each result type next to the anonymous object or dictionary its route answered with before, as that route built it, /// written under every option set the answer can be serialized with: the HTTP and gRPC controller dispatchers, /// the serializer defaults, and the ASP.NET Core web defaults the Web host answers with. The bytes must be equal. /// This covers the routes no wire test reaches: the self-service ones a user token calls, the cleanup routes a /// timer runs, the signing key retirement that would change the keys of the test host, and the rare branches. /// public class ResultContractsParityTests { private static readonly JsonSerializerOptions HttpDispatcher = new() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; private static readonly JsonSerializerOptions GrpcDispatcher = new() { PropertyNameCaseInsensitive = true }; private static readonly JsonSerializerOptions WebDefaults = new(JsonSerializerDefaults.Web); private static readonly JsonSerializerOptions Defaults = new(); private static readonly DateTimeOffset Created = new(2026, 11, 17, 10, 0, 0, TimeSpan.Zero); private static readonly DateTimeOffset Modified = new(2026, 11, 17, 11, 30, 0, TimeSpan.FromHours(1)); private static readonly JsonElement WebAuthnOptions = JsonSerializer.SerializeToElement(new Dictionary { ["rp"] = new Dictionary { ["id"] = "localhost", ["name"] = "redb" }, ["challenge"] = "AAECAw", ["pubKeyCredParams"] = new[] { new Dictionary { ["type"] = "public-key", ["alg"] = -7 } }, }); private static readonly Dictionary Cases = new() { ["group"] = ( new { id = 7L, name = (string?)"g", parentId = (long?)null, groupType = (string?)null, description = (string?)"d", createdAt = Created, modifiedAt = Modified }, new GroupResponse { Id = 7, Name = "g", ParentId = null, GroupType = null, Description = "d", CreatedAt = Created, ModifiedAt = Modified }), ["group with members"] = ( new { id = 7L, name = (string?)"g", parentId = (long?)3, groupType = (string?)"team", description = (string?)null, createdAt = Created, modifiedAt = Modified, memberCount = 2 }, new GroupResponse { Id = 7, Name = "g", ParentId = 3, GroupType = "team", Description = null, CreatedAt = Created, ModifiedAt = Modified, MemberCount = 2 }), ["group tree"] = ( new { id = 1L, name = (string?)"root", parentId = (long?)null, groupType = (string?)null, description = (string?)null, level = 0, children = new List { new { id = 2L, name = (string?)"leaf", parentId = (long?)1, groupType = (string?)null, description = (string?)null, level = 1, children = new List() } }, }, new GroupTreeNodeResponse { Id = 1, Name = "root", Level = 0, Children = { new GroupTreeNodeResponse { Id = 2, Name = "leaf", ParentId = 1, Level = 1 } }, }), ["group changed"] = (new { success = true, groupId = 5L }, new GroupChangedResponse { GroupId = 5 }), ["group moved"] = (new { success = true, groupId = 5L, newParentGroupId = 9L }, new GroupMovedResponse { GroupId = 5, NewParentGroupId = 9 }), ["member added"] = ( new { success = true, membershipId = 11L, groupId = 5L, userId = 6L, role = "member" }, new GroupMemberAddedResponse { MembershipId = 11, GroupId = 5, UserId = 6, Role = "member" }), ["member changed"] = (new { success = true, groupId = 5L, userId = 6L, role = "owner" }, new GroupMemberChangedResponse { GroupId = 5, UserId = 6, Role = "owner" }), ["member removed"] = (new { success = true, groupId = 5L, userId = 6L }, new GroupMemberRemovedResponse { GroupId = 5, UserId = 6 }), ["membership check"] = (new { isMember = false, groupId = 5L, userId = 6L }, new GroupMembershipCheckResponse { IsMember = false, GroupId = 5, UserId = 6 }), ["claim scope deleted"] = (new { success = true, cascadedAssignments = 2, cascadedMappers = 1 }, new ClaimScopeDeletedResponse { CascadedAssignments = 2, CascadedMappers = 1 }), ["signing key retired"] = (new { success = true, kid = "k-1" }, new SigningKeyRetiredResponse { Kid = "k-1" }), ["webhook secret rotated"] = (new { success = true, hmacSecret = "s3cr3t+/=" }, new WebhookSecretRotatedResponse { HmacSecret = "s3cr3t+/=" }), ["webhook deliveries"] = ( new { items = new[] { new { id = 3L, deliveryId = (string?)"0f0e", eventId = (string?)null, kind = "webhook", destination = "12", eventType = "UserCreated", status = "failed", attempts = 2, lastError = (string?)"HttpRequestException: & \"quoted\"", createdAt = (string?)"2026-11-17 10:00:00", nextAttemptAt = (string?)null, finishedAt = (string?)"2026-11-17 10:05:00", }, }.ToList(), offset = 0, count = 25, }, new WebhookDeliveryPage { Items = new List(), Offset = 0, Count = 25, }), ["impersonation started"] = (new { targetUserId = 42L, targetLogin = (string?)"alice" }, new ImpersonationStartedResponse { TargetUserId = 42, TargetLogin = "alice" }), ["impersonation stopped"] = (new { stopped = true }, new ImpersonationStoppedResponse()), ["my consent granted"] = ( new { id = 9L, userId = 6L, clientId = (string?)"spa", applicationId = 4L, scopes = new[] { "openid", "profile" } }, new MyConsentGrantedResponse { Id = 9, UserId = 6, ClientId = "spa", ApplicationId = 4, Scopes = new[] { "openid", "profile" } }), ["my consent revoked"] = (new { revoked = 1 }, new MyConsentRevokedResponse { Revoked = 1 }), ["federated identity unlinked"] = (new { unlinked = true, providerId = "github" }, new FederatedIdentityUnlinkedResponse { ProviderId = "github" }), ["mfa otp prune"] = (new { prunedMfaOtp = 3 }, new MfaOtpPruneResult { PrunedMfaOtp = 3 }), ["revoked sids prune"] = (new { prunedRevokedSids = 4 }, new RevokedSidsPruneResult { PrunedRevokedSids = 4 }), ["webauthn challenges prune"] = (new { prunedWebAuthnChallenges = 5 }, new WebAuthnChallengePruneResult { PrunedWebAuthnChallenges = 5 }), ["success already absent"] = (new { success = true, alreadyAbsent = true }, new SuccessResponse { AlreadyAbsent = true }), ["success sessions revoked"] = (new { success = true, sessionsRevoked = 0 }, new SuccessResponse { SessionsRevoked = 0 }), ["error without description"] = (new { error = "access_denied", error_description = (string?)null }, new ErrorResponse { Error = "access_denied", ErrorDescription = null }), ["validation error"] = ( new { error = "validation_error", error_description = "name is required.", validation_errors = new[] { "name is required.", "kind is required." } }, new ValidationErrorResponse { ErrorDescription = "name is required.", ValidationErrors = new[] { "name is required.", "kind is required." } }), ["validation error without body"] = ( new { error = "validation_error", error_description = "Request body is required.", validation_errors = Array.Empty() }, new ValidationErrorResponse { ErrorDescription = "Request body is required.", ValidationErrors = Array.Empty() }), ["inactive introspection"] = (new { active = false }, new IntrospectionResponse { Active = false }), ["session page"] = ( new Dictionary { ["items"] = new List { new() { SessionId = 4, UserId = 6, ClientId = "spa", CreatedAt = Created } }, ["total"] = 1, ["offset"] = 0, ["count"] = 25 }, new SessionPage { Items = new List { new() { SessionId = 4, UserId = 6, ClientId = "spa", CreatedAt = Created } }, Total = 1, Offset = 0, Count = 25 }), ["session revoke preview"] = ( new Dictionary { ["success"] = true, ["dryRun"] = true, ["wouldRevoke"] = 2, ["sampleSessionIds"] = new List { 4, 5 } }, new SessionRevokePreview { WouldRevoke = 2, SampleSessionIds = new List { 4, 5 } }), ["sessions revoked"] = (new Dictionary { ["success"] = true, ["revoked"] = 3 }, new SuccessResponse { Revoked = 3 }), ["sessions logged out"] = (new Dictionary { ["success"] = true, ["sessionsRevoked"] = 3 }, new SuccessResponse { SessionsRevoked = 3 }), ["mfa status"] = ( new Dictionary { ["enabled"] = true, ["methods"] = new[] { "totp" }, ["recovery_codes_remaining"] = 8 }, new MfaStatusResponse { Enabled = true, Methods = new[] { "totp" }, RecoveryCodesRemaining = 8 }), ["mfa setup totp"] = ( new Dictionary { ["method"] = "totp", ["secret_base32"] = "JBSWY3DP", ["qr_uri"] = "otpauth://totp/redb:bob?secret=JBSWY3DP&issuer=redb", ["setup_token"] = "CfDJ8+/=" }, new MfaSetupResponse { Method = "totp", SecretBase32 = "JBSWY3DP", QrUri = "otpauth://totp/redb:bob?secret=JBSWY3DP&issuer=redb", SetupToken = "CfDJ8+/=" }), ["mfa setup email"] = ( new Dictionary { ["method"] = "email", ["secret_base32"] = null, ["qr_uri"] = null, ["setup_token"] = "t", ["masked_email"] = "b***@example.test" }, new MfaSetupResponse { Method = "email", SetupToken = "t", Extra = new Dictionary { ["masked_email"] = "b***@example.test" } }), ["mfa confirmed"] = ( new Dictionary { ["confirmed"] = true, ["recovery_codes"] = new[] { "a1", "b2" } }, new MfaConfirmedResponse { RecoveryCodes = new[] { "a1", "b2" } }), ["mfa disabled"] = (new Dictionary { ["disabled"] = true }, new MfaDisabledResponse()), ["mfa recovery codes"] = ( new Dictionary { ["recovery_codes"] = new[] { "a1" } }, new MfaRecoveryCodesResponse { RecoveryCodes = new[] { "a1" } }), ["mfa error"] = ( new Dictionary { ["error"] = "invalid_code", ["error_description"] = "Invalid verification code" }, new ErrorResponse { Error = "invalid_code", ErrorDescription = "Invalid verification code" }), ["mfa setup email with state"] = ( new Dictionary { ["method"] = "email", ["secret_base32"] = null, ["qr_uri"] = null, ["setup_token"] = "t", ["masked_email"] = "b***@example.test", ["mfa_state"] = "CfDJ8+/=" }, new MfaSetupResponse { Method = "email", SetupToken = "t", Extra = new Dictionary { ["masked_email"] = "b***@example.test", ["mfa_state"] = "CfDJ8+/=" } }), ["webauthn status"] = ( new Dictionary { ["enabled"] = true, ["credentials_count"] = 2 }, new WebAuthnStatusResponse { Enabled = true, CredentialsCount = 2 }), ["webauthn registration options"] = ( new Dictionary { ["options"] = WebAuthnOptions, ["setup_token"] = "CfDJ8+/=" }, new WebAuthnRegistrationOptionsResponse { Options = WebAuthnOptions, SetupToken = "CfDJ8+/=" }), ["webauthn registered"] = ( new Dictionary { ["registered"] = true, ["credential_key"] = "k1", ["recovery_codes"] = new[] { "a1" } }, new WebAuthnRegisteredResponse { CredentialKey = "k1", RecoveryCodes = new[] { "a1" } }), ["webauthn registered, no codes"] = ( new Dictionary { ["registered"] = true, ["credential_key"] = "k1", ["recovery_codes"] = Array.Empty() }, new WebAuthnRegisteredResponse { CredentialKey = "k1", RecoveryCodes = Array.Empty() }), ["webauthn credentials"] = ( new Dictionary { ["credentials"] = new List> { new() { ["key"] = "k1", ["display_name"] = "Laptop", ["aaguid"] = null, ["registered_at"] = Created, ["last_used_at"] = (DateTimeOffset?)Modified, ["user_verified"] = true, ["backup_eligible"] = false, ["backup_state"] = false, }, new() { ["key"] = "k2", ["display_name"] = null, ["aaguid"] = "08987058-cadc-4b81-b6e1-30de50dcbe96", ["registered_at"] = Created, ["last_used_at"] = (DateTimeOffset?)null, ["user_verified"] = false, ["backup_eligible"] = true, ["backup_state"] = true, }, }, }, new WebAuthnCredentialList { Credentials = new List { new() { Key = "k1", DisplayName = "Laptop", RegisteredAt = Created, LastUsedAt = Modified, UserVerified = true, BackupEligible = false, BackupState = false }, new() { Key = "k2", Aaguid = "08987058-cadc-4b81-b6e1-30de50dcbe96", RegisteredAt = Created, UserVerified = false, BackupEligible = true, BackupState = true }, }, }), ["webauthn renamed"] = (new Dictionary { ["renamed"] = true }, new WebAuthnRenamedResponse()), ["webauthn deleted"] = (new Dictionary { ["deleted"] = true }, new WebAuthnDeletedResponse()), }; static ResultContractsParityTests() { // The delivery item is built here so it mirrors the anonymous one member for member. ((WebhookDeliveryPage)Cases["webhook deliveries"].Now).Items.Add(new WebhookDeliveryItem { Id = 3, DeliveryId = "0f0e", EventId = null, Kind = "webhook", Destination = "12", EventType = "UserCreated", Status = "failed", Attempts = 2, LastError = "HttpRequestException: & \"quoted\"", CreatedAt = "2026-11-17 10:00:00", NextAttemptAt = null, FinishedAt = "2026-11-17 10:05:00", }); } public static TheoryData All() { var data = new TheoryData(); foreach (var name in Cases.Keys) foreach (var options in new[] { "http", "grpc", "web", "default" }) data.Add(name, options); return data; } [Theory, MemberData(nameof(All))] public void The_type_writes_the_bytes_of_the_anonymous_answer_it_replaced(string @case, string options) { var json = options switch { "http" => HttpDispatcher, "grpc" => GrpcDispatcher, "web" => WebDefaults, _ => Defaults, }; var (before, now) = Cases[@case]; JsonSerializer.Serialize(now, json).Should().Be(JsonSerializer.Serialize(before, json)); } } Path: redb-identity/tests/redb.Identity.Tests/Management/ScopeManagementTests.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/Management/ScopeManagementTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Scopes; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; namespace redb.Identity.Tests.Management; public class ScopeManagementTests { private readonly IRedbService _redb = Substitute.For(); private readonly ScopeManagementProcessor _processor; public ScopeManagementTests() { var context = MockRouteContext.Create(_redb); _processor = new ScopeManagementProcessor(context); } private static TestExchange CreateExchange(string operation, object? body = null) { var exchange = new TestExchange(); exchange.In.Headers["operation"] = operation; if (body != null) exchange.In.Body = body; return exchange; } // ── Create ── [Fact] public async Task Create_ValidInput_ReturnsScopeResponse() { MockRedbQuery.Setup(_redb, new List>()); _redb.SaveAsync(Arg.Any>()) .Returns(ci => { ci.Arg>().Id = 1; return 1L; }); var exchange = CreateExchange("create", new CreateScopeRequest { Name = "api", DisplayName = "API Access", Description = "Access to API resources", Resources = new[] { "resource-server-1" } }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.Name.Should().Be("api"); resp.DisplayName.Should().Be("API Access"); resp.Description.Should().Be("Access to API resources"); exchange.Properties["identity-event-type"].Should().Be("ScopeCreated"); } [Fact] public async Task Create_MissingName_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateScopeRequest { Name = "" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } [Fact] public async Task Create_DuplicateName_ReturnsDuplicateError() { var existing = MockRedbQuery.CreateObject(1, "api", new ScopeProps { ScopeName = "api" }); // V4-UNIQUE: the duplicate pre-check is a GetByUniqueAsync probe now. _redb.GetByUniqueAsync( Arg.Any>>(), "api", Arg.Any()) .Returns(existing); var exchange = CreateExchange("create", new CreateScopeRequest { Name = "api" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("duplicate"); } // ── Read ── [Fact] public async Task Read_ById_ReturnsScope() { var scope = MockRedbQuery.CreateObject(10, "Profile", new ScopeProps { ScopeName = "profile", Description = "Profile data" }); _redb.LoadAsync(10).Returns(scope); var exchange = CreateExchange("read", new Dictionary { ["id"] = 10L }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.Name.Should().Be("profile"); resp.Id.Should().Be("10"); } [Fact] public async Task Read_ByName_ReturnsScope() { var scope = MockRedbQuery.CreateObject(10, "Profile", new ScopeProps { ScopeName = "profile" }); // V4-UNIQUE: read-by-name is a GetByUniqueAsync probe now. _redb.GetByUniqueAsync( Arg.Any>>(), "profile", Arg.Any()) .Returns(scope); var exchange = CreateExchange("read", new Dictionary { ["name"] = "profile" }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.Name.Should().Be("profile"); } [Fact] public async Task Read_NotFound_ReturnsNotFoundError() { _redb.LoadAsync(999).Returns((RedbObject?)null); var exchange = CreateExchange("read", new Dictionary { ["id"] = 999L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("not_found"); } // ── Update ── [Fact] public async Task Update_ValidInput_ReturnsUpdatedScope() { var scope = MockRedbQuery.CreateObject(5, "Old", new ScopeProps { ScopeName = "api", Description = "old" }); _redb.LoadAsync(5).Returns(scope); _redb.SaveAsync(Arg.Any>()).Returns(5L); var exchange = CreateExchange("update", new UpdateScopeRequest { Id = "5", DisplayName = "New Display", Description = "new desc", Resources = new[] { "rs1" } }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.DisplayName.Should().Be("New Display"); resp.Description.Should().Be("new desc"); exchange.Properties["identity-event-type"].Should().Be("ScopeUpdated"); } // ── Delete ── [Fact] public async Task Delete_ValidId_ReturnsSuccess() { // The delete looks the record up first; it exists and is of this resource. _redb.LoadAsync(3).Returns(new RedbObject(new ScopeProps()) { id = 3 }); _redb.DeleteAsync(3).Returns(true); var exchange = CreateExchange("delete", new Dictionary { ["id"] = 3L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Success.Should().BeTrue(); exchange.Properties["identity-event-type"].Should().Be("ScopeDeleted"); } // ── List ── [Fact] public async Task List_ReturnsPaginatedResults() { var items = new List> { MockRedbQuery.CreateObject(1, "openid", new ScopeProps { ScopeName = "openid" }), MockRedbQuery.CreateObject(2, "profile", new ScopeProps { ScopeName = "profile" }), MockRedbQuery.CreateObject(3, "api", new ScopeProps { ScopeName = "api" }) }; MockRedbQuery.Setup(_redb, items); var exchange = CreateExchange("list", new ListRequest { Offset = 1, Count = 2 }); await _processor.Process(exchange); var result = exchange.Out!.Body.Should().BeOfType>().Subject; result.Total.Should().Be(3); result.Items.Should().HaveCount(2); } // ── Input Validation ── [Fact] public async Task Create_InvalidNameChars_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateScopeRequest { Name = "scope with spaces!" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("invalid characters"); } [Fact] public async Task Create_DisplayNameTooLong_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateScopeRequest { Name = "api", DisplayName = new string('a', 257) }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("DisplayName"); } [Fact] public async Task Create_DescriptionTooLong_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateScopeRequest { Name = "api", Description = new string('a', 1025) }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("Description"); } } Path: redb-identity/tests/redb.Identity.Tests/Management/TokenManagementTests.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/Management/TokenManagementTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Tokens; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; using static OpenIddict.Abstractions.OpenIddictConstants; namespace redb.Identity.Tests.Management; public class TokenManagementTests { private readonly IRedbService _redb = Substitute.For(); private readonly TokenManagementProcessor _processor; public TokenManagementTests() { var context = MockRouteContext.Create(_redb); _processor = new TokenManagementProcessor(context); } private static TestExchange CreateExchange(string operation, object? body = null) { var exchange = new TestExchange(); exchange.In.Headers["operation"] = operation; if (body != null) exchange.In.Body = body; return exchange; } // ── List ── [Fact] public async Task List_NoFilters_ReturnsAllTokens() { var items = new List> { MockRedbQuery.CreateObject(1, "token1", new TokenProps { ApplicationObjectId = 10, Status = Statuses.Valid, Type = "access_token" }), MockRedbQuery.CreateObject(2, "token2", new TokenProps { ApplicationObjectId = 10, Status = Statuses.Revoked, Type = "refresh_token" }) }; MockRedbQuery.Setup(_redb, items); var exchange = CreateExchange("list"); await _processor.Process(exchange); var result = exchange.Out!.Body.Should().BeOfType>().Subject; result.Total.Should().Be(2); result.Items.Should().HaveCount(2); } [Fact] public async Task List_FilterByStatus_ReturnsFiltered() { var items = new List> { MockRedbQuery.CreateObject(1, "t1", new TokenProps { Status = Statuses.Valid, Type = "access_token" }), MockRedbQuery.CreateObject(2, "t2", new TokenProps { Status = Statuses.Revoked, Type = "access_token" }), MockRedbQuery.CreateObject(3, "t3", new TokenProps { Status = Statuses.Valid, Type = "refresh_token" }) }; MockRedbQuery.Setup(_redb, items); var exchange = CreateExchange("list", new Dictionary { ["status"] = Statuses.Valid }); await _processor.Process(exchange); var result = exchange.Out!.Body.Should().BeOfType>().Subject; result.Total.Should().Be(2); result.Items.Should().OnlyContain(t => t.Status == Statuses.Valid); } // ── Revoke ── [Fact] public async Task Revoke_ValidToken_SetsRevokedStatus() { var token = MockRedbQuery.CreateObject(42, "tok", new TokenProps { Status = Statuses.Valid, Type = "access_token" }); _redb.LoadAsync(42).Returns(token); _redb.SaveAsync(Arg.Any>()).Returns(42L); var exchange = CreateExchange("revoke", new Dictionary { ["tokenId"] = 42L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Success.Should().BeTrue(); token.Props.Status.Should().Be(Statuses.Revoked); exchange.Properties["identity-event-type"].Should().Be("TokenRevoked"); } [Fact] public async Task Revoke_UserToken_EventNamesTheUser() { // The token's subject column is the public sub; the event carries the user's internal id, // the key of their UserProps, as TokensRevokedByUser does. var subject = Guid.NewGuid(); var token = MockRedbQuery.CreateObject(43, "tok", new TokenProps { Status = Statuses.Valid, Type = "access_token" }); token.value_guid = subject; _redb.LoadAsync(43).Returns(token); _redb.SaveAsync(Arg.Any>()).Returns(43L); var user = MockRedbQuery.CreateObject(900, "user", new UserProps()); user.value_guid = subject; user.key = 7; MockRedbQuery.Setup(_redb, new List> { user }); var exchange = CreateExchange("revoke", new Dictionary { ["tokenId"] = 43L }); await _processor.Process(exchange); exchange.Properties["identity-event-type"].Should().Be("TokenRevoked"); var data = exchange.Properties["identity-event-data"]!; data.GetType().GetProperty("UserId")!.GetValue(data).Should().Be(7L); } [Fact] public async Task Revoke_MissingTokenId_ReturnsValidationError() { var exchange = CreateExchange("revoke", new Dictionary { ["tokenId"] = 0L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } [Fact] public async Task Revoke_TokenNotFound_ReturnsNotFoundError() { _redb.LoadAsync(999).Returns((RedbObject?)null); var exchange = CreateExchange("revoke", new Dictionary { ["tokenId"] = 999L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("not_found"); } // ── Revoke by user ── [Fact] public async Task RevokeByUser_RevokesAllValidTokens() { // The processor first reads UserProps to resolve the public sub (value_guid), // then queries TokenProps by ValueGuid. Both queryables must be seeded. var userGuid = Guid.NewGuid(); var userObj = MockRedbQuery.CreateObject(100, "u100", new UserProps()); userObj.Key = 100; userObj.value_guid = userGuid; MockRedbQuery.Setup(_redb, new List> { userObj }); var items = new List> { MockRedbQuery.CreateObject(1, "t1", new TokenProps { Status = Statuses.Valid, Type = "access_token" }), MockRedbQuery.CreateObject(2, "t2", new TokenProps { Status = Statuses.Valid, Type = "refresh_token" }) }; // TokenProps subject linkage moved from Key→value_guid; mirror that on the seed. foreach (var t in items) t.value_guid = userGuid; MockRedbQuery.Setup(_redb, items); _redb.SaveAsync(Arg.Any>()).Returns(ci => ci.Arg>().Id); var exchange = CreateExchange("revoke-by-user", new Dictionary { ["userId"] = 100L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.RevokedCount.Should().Be(2); items.Should().OnlyContain(t => t.Props.Status == Statuses.Revoked); exchange.Properties["identity-event-type"].Should().Be("TokensRevokedByUser"); } [Fact] public async Task RevokeByUser_MissingUserId_ReturnsValidationError() { var exchange = CreateExchange("revoke-by-user", new Dictionary { ["userId"] = 0L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } // ── Unknown operation ── [Fact] public async Task UnknownOperation_ReturnsInvalidOperation() { var exchange = CreateExchange("destroy"); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("invalid_operation"); } } Path: redb-identity/tests/redb.Identity.Tests/Management/UserManagementTests.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/Management/UserManagementTests.cs ---- using AwesomeAssertions; using NSubstitute; using NSubstitute.ExceptionExtensions; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Providers; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Users; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; using CoreCreateUserRequest = redb.Core.Models.Users.CreateUserRequest; using CoreUpdateUserRequest = redb.Core.Models.Users.UpdateUserRequest; namespace redb.Identity.Tests.Management; public class UserManagementTests { private readonly IRedbService _redb = Substitute.For(); private readonly IUserProvider _userProvider = Substitute.For(); private readonly UserManagementProcessor _processor; public UserManagementTests() { _redb.UserProvider.Returns(_userProvider); var context = MockRouteContext.Create(_redb); _processor = new UserManagementProcessor(context); } private static TestExchange CreateExchange(string operation, object? body = null) { var exchange = new TestExchange(); exchange.In.Headers["operation"] = operation; if (body != null) exchange.In.Body = body; return exchange; } private static IRedbUser MockUser(long id, string login, bool enabled = true, string? email = null, string? phone = null, string? name = null) { var user = Substitute.For(); user.Id.Returns(id); user.Login.Returns(login); user.Name.Returns(name ?? login); user.Enabled.Returns(enabled); user.Email.Returns(email); user.Phone.Returns(phone); user.DateRegister.Returns(DateTimeOffset.UtcNow); return user; } // ── Create ── [Fact] public async Task Create_ValidInput_ReturnsUserResponse() { var coreUser = MockUser(1, "admin", name: "Administrator"); _userProvider.CreateUserAsync(Arg.Any(), Arg.Any()) .Returns(coreUser); _redb.SaveAsync(Arg.Any>()).Returns(100L); var exchange = CreateExchange("create", new CreateUserRequest { Login = "admin", Password = "P@ssw0rd!", DisplayName = "Administrator" }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.Login.Should().Be("admin"); resp.Status.Should().Be("active"); exchange.Properties["identity-event-type"].Should().Be("UserCreated"); } [Fact] public async Task Create_CoreHandlesPasswordHash() { var coreUser = MockUser(11, "user1"); _userProvider.CreateUserAsync(Arg.Any(), Arg.Any()) .Returns(coreUser); _redb.SaveAsync(Arg.Any>()).Returns(100L); var exchange = CreateExchange("create", new CreateUserRequest { Login = "user1", Password = "secret123" }); await _processor.Process(exchange); // Password is delegated to Core's UserProvider — not stored in UserProps await _userProvider.Received(1).CreateUserAsync( Arg.Is(r => r.Login == "user1" && r.Password == "secret123"), Arg.Any()); } [Fact] public async Task Create_MissingLogin_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateUserRequest { Login = "", Password = "pass1234" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } [Fact] public async Task Create_MissingPassword_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateUserRequest { Login = "user1", Password = "" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } [Fact] public async Task Create_DuplicateLogin_ReturnsDuplicateError() { _userProvider.CreateUserAsync(Arg.Any(), Arg.Any()) .Throws(new InvalidOperationException("Login 'admin' is already taken")); var exchange = CreateExchange("create", new CreateUserRequest { Login = "admin", Password = "pass1234" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("duplicate"); } // ── Read ── [Fact] public async Task Read_ById_ReturnsUser() { var coreUser = MockUser(10, "admin", email: "admin@test.com"); _userProvider.GetUserByIdAsync(10).Returns(coreUser); MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("read", new Dictionary { ["id"] = 10L }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.Login.Should().Be("admin"); resp.Id.Should().Be(10); } [Fact] public async Task Read_ByLogin_ReturnsUser() { var coreUser = MockUser(10, "admin"); _userProvider.GetUserByLoginAsync("admin").Returns(coreUser); MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("read", new Dictionary { ["login"] = "admin" }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.Login.Should().Be("admin"); } [Fact] public async Task Read_NotFound_ReturnsNotFoundError() { _userProvider.GetUserByIdAsync(999).Returns((IRedbUser?)null); var exchange = CreateExchange("read", new Dictionary { ["id"] = 999L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("not_found"); } // ── Update ── [Fact] public async Task Update_ValidInput_ReturnsUpdatedUser() { var coreUser = MockUser(5, "user1"); _userProvider.GetUserByIdAsync(5).Returns(coreUser); var updatedUser = MockUser(5, "user1", enabled: false, name: "New Name"); _userProvider.UpdateUserAsync(coreUser, Arg.Any(), Arg.Any()) .Returns(updatedUser); MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("update", new UpdateUserRequest { Id = 5, DisplayName = "New Name", Status = "blocked" }); await _processor.Process(exchange); var resp = exchange.Out!.Body.Should().BeOfType().Subject; resp.DisplayName.Should().Be("New Name"); resp.Status.Should().Be("blocked"); exchange.Properties["identity-event-type"].Should().Be("UserUpdated"); } [Fact] public async Task Update_InvalidStatus_ReturnsValidationError() { var coreUser = MockUser(5, "user1"); _userProvider.GetUserByIdAsync(5).Returns(coreUser); var exchange = CreateExchange("update", new UpdateUserRequest { Id = 5, Status = "deleted" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } // ── Delete ── [Fact] public async Task Delete_ValidId_ReturnsSuccess() { var coreUser = MockUser(7, "user7"); _userProvider.GetUserByIdAsync(7).Returns(coreUser); _userProvider.DeleteUserAsync(coreUser, Arg.Any()).Returns(true); MockRedbQuery.Setup(_redb, new List>()); // Delete now cascades through SessionService.LogoutAsync (sessions + authorizations // revoke) before soft-deleting the user row — mock both query types so the cascade // doesn't NRE on an unconfigured Query() call. Empty lists model the // "user has no active sessions / authorizations to revoke" path. MockRedbQuery.Setup(_redb, new List>()); MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("delete", new Dictionary { ["id"] = 7L }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Success.Should().BeTrue(); exchange.Properties["identity-event-type"].Should().Be("UserDeleted"); } // ── List ── [Fact] public async Task List_ReturnsPaginatedResults() { var users = Enumerable.Range(1, 4) .Select(i => MockUser(i, $"user{i}")) .ToList(); _userProvider.GetUsersAsync(Arg.Any()).Returns(users); _userProvider.GetUserCountAsync().Returns(4); MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("list", new ListRequest { Offset = 0, Count = 2 }); await _processor.Process(exchange); var result = exchange.Out!.Body.Should().BeOfType>().Subject; result.Total.Should().Be(4); result.Items.Should().HaveCount(4); } // ── Search ── [Fact] public async Task Search_ByQuery_ReturnsMatchedUsers() { var users = new List { MockUser(1, "admin"), MockUser(2, "admin2") }; _userProvider.GetUsersAsync(Arg.Any()).Returns(users); MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("search", new Dictionary { ["query"] = "admin" }); await _processor.Process(exchange); // Search now returns the standard PagedResult envelope shared with /users list. var page = exchange.Out!.Body.Should().BeAssignableTo>().Subject; page.Items.Should().HaveCount(2); page.Items.Should().OnlyContain(r => r.Login!.Contains("admin")); } [Fact] public async Task Search_EmptyQuery_ReturnsValidationError() { var exchange = CreateExchange("search", new Dictionary { ["query"] = "" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } // ── Change Password ── [Fact] public async Task ChangePassword_ValidOldPassword_Succeeds() { var coreUser = MockUser(5, "user1"); _userProvider.GetUserByIdAsync(5).Returns(coreUser); _userProvider.ChangePasswordAsync(coreUser, "oldpass1", "newpass1", Arg.Any()) .Returns(true); // C7: ChangePassword now triggers SessionService.LogoutAsync — stub the relevant // queries so the in-memory mock returns empty lists rather than throwing NRE. MockRedbQuery.Setup(_redb, new List>()); MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("change-password", new ChangePasswordRequest { Id = 5, OldPassword = "oldpass1", NewPassword = "newpass1" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Success.Should().BeTrue(); exchange.Properties["identity-event-type"].Should().Be("PasswordChanged"); } [Fact] public async Task ChangePassword_RevokesAllUserSessions() { // C7: every session that was authenticated with the OLD password must be // invalidated when the password changes. Build two active sessions for the // user, change the password, and assert both ended up "revoked". var coreUser = MockUser(7, "user-c7"); _userProvider.GetUserByIdAsync(7).Returns(coreUser); _userProvider.ChangePasswordAsync(coreUser, "old-pwd-c7", "new-pwd-c7", Arg.Any()) .Returns(true); var session1 = MockRedbQuery.CreateObject( 701, "session-701", new SessionProps { Status = "active" }); session1.key = 7; var session2 = MockRedbQuery.CreateObject( 702, "session-702", new SessionProps { Status = "active" }); session2.key = 7; MockRedbQuery.Setup(_redb, new List> { session1, session2 }); MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("change-password", new ChangePasswordRequest { Id = 7, OldPassword = "old-pwd-c7", NewPassword = "new-pwd-c7" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Success.Should().BeTrue(); session1.Props.Status.Should().Be("revoked"); session2.Props.Status.Should().Be("revoked"); // The audit event should report how many sessions were revoked. var data = exchange.Properties["identity-event-data"]!; var revoked = (int)data.GetType().GetProperty("SessionsRevoked")!.GetValue(data)!; revoked.Should().Be(2); } [Fact] public async Task ChangePassword_WrongOldPassword_ReturnsError() { var coreUser = MockUser(5, "user1"); _userProvider.GetUserByIdAsync(5).Returns(coreUser); _userProvider.ChangePasswordAsync(coreUser, "wrongpwd", "newpass1", Arg.Any()) .Returns(false); var exchange = CreateExchange("change-password", new ChangePasswordRequest { Id = 5, OldPassword = "wrongpwd", NewPassword = "newpass1" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("invalid_password"); } [Fact] public async Task ChangePassword_UserNotFound_ReturnsNotFound() { _userProvider.GetUserByIdAsync(999).Returns((IRedbUser?)null); var exchange = CreateExchange("change-password", new ChangePasswordRequest { Id = 999, OldPassword = "old12345", NewPassword = "new12345" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("not_found"); } // ── Input Validation ── [Fact] public async Task Create_PasswordTooShort_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateUserRequest { Login = "user1", Password = "short" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("at least"); } [Fact] public async Task Create_InvalidLoginChars_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateUserRequest { Login = "user@name!", Password = "P@ssw0rd!" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("invalid characters"); } [Fact] public async Task Create_InvalidEmail_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateUserRequest { Login = "user1", Password = "P@ssw0rd!", Email = "not-an-email" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("email"); } [Fact] public async Task Create_InvalidPhoneNumber_ReturnsValidationError() { var exchange = CreateExchange("create", new CreateUserRequest { Login = "user1", Password = "P@ssw0rd!", PhoneNumber = "123-456" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("E.164"); } [Fact] public async Task ChangePassword_PasswordTooShort_ReturnsValidationError() { var exchange = CreateExchange("change-password", new ChangePasswordRequest { Id = 5, OldPassword = "oldpass1", NewPassword = "short" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("at least"); } [Fact] public async Task ChangePassword_SameAsOld_ReturnsValidationError() { var exchange = CreateExchange("change-password", new ChangePasswordRequest { Id = 5, OldPassword = "P@ssw0rd!", NewPassword = "P@ssw0rd!" }); await _processor.Process(exchange); var body = exchange.Out!.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); body.ErrorDescription.Should().Contain("differ"); } } Path: redb-identity/tests/redb.Identity.Tests/Module/DiContainerHealthTests.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/Module/DiContainerHealthTests.cs ---- using System; using AwesomeAssertions; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Core.Models.Configuration; using redb.Core.Extensions; using redb.Core.Pro.Extensions; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Postgres.Pro.Extensions; using redb.Route.Components; using redb.Route.Core; using Xunit;using redb.Identity.Tests.Infrastructure; namespace redb.Identity.Tests.Module; /// /// E7 — DI lifetimes audit. Locks the contract that the production Identity /// bootstrap () is /// free of captive dependencies — /// instantiates one of every registered service through a probe scope and throws /// if any Singleton's constructor pulls a Scoped /// service. Without this guard a captive-dep regression slips in silently and /// only manifests as request-pipeline state corruption under load. /// public class DiContainerHealthTests { [Fact] public void AddRedbIdentityServer_HasNoCaptiveDependencies() { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); // Same connection-string lookup as ProductionBootstrapFixture. Falls back to a // dummy DSN if Postgres is unreachable — ValidateOnBuild does NOT open the // connection, so the actual DSN doesn't matter for DI graph validation. var config = new ConfigurationBuilder().AddInMemoryCollection().Build(); var cs = "Host=localhost;Port=1;Database=fake;Username=fake;Password=fake"; services.AddRedbForTests(cs); services.AddSingleton(); var options = new RedbIdentityOptions { Issuer = new Uri("https://identity.test.local/"), AllowEphemeralKeys = true, }; services.AddSingleton(Options.Create(options)); services.AddRedbIdentityServer(options); // The act: BuildServiceProvider with ValidateOnBuild=true. Throws AggregateException // listing every service whose ctor cannot be satisfied — captive deps, missing // registrations, ambiguous overloads. var act = () => services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true, ValidateOnBuild = true, }); act.Should().NotThrow("AddRedbIdentityServer must be free of captive dependencies"); } } Path: redb-identity/tests/redb.Identity.Tests/Module/GracefulShutdownTests.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/Module/GracefulShutdownTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using redb.Route.Abstractions; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Module; /// /// F2 — graceful shutdown contract for the Identity route context. /// public class GracefulShutdownTests { [Fact] public async Task ContextStop_InvokesStoppingThenStopped_OnAllListeners() { var sp = new ServiceCollection().BuildServiceProvider(); await using var ctx = new RouteContext(sp, "graceful-shutdown-test"); var listener = Substitute.For(); ctx.AddLifecycleListener(listener); await ctx.Start(); ctx.IsStarted.Should().BeTrue(); await ctx.Stop(); Received.InOrder(() => { listener.OnContextStopping(ctx, Arg.Any()); listener.OnContextStopped(ctx, Arg.Any()); }); } [Fact] public async Task ContextStop_PropagatesProvidedCancellationToken() { var sp = new ServiceCollection().BuildServiceProvider(); await using var ctx = new RouteContext(sp, "graceful-shutdown-ct-test"); CancellationToken capturedStopping = default; CancellationToken capturedStopped = default; var listener = Substitute.For(); listener.OnContextStopping(Arg.Any(), Arg.Do(t => capturedStopping = t)) .Returns(Task.CompletedTask); listener.OnContextStopped(Arg.Any(), Arg.Do(t => capturedStopped = t)) .Returns(Task.CompletedTask); ctx.AddLifecycleListener(listener); await ctx.Start(); using var cts = new CancellationTokenSource(); await ctx.Stop(cts.Token); capturedStopping.Should().Be(cts.Token); capturedStopped.Should().Be(cts.Token); } [Fact] public async Task ContextStop_WhenListenerThrows_StillStops() { var sp = new ServiceCollection().BuildServiceProvider(); await using var ctx = new RouteContext(sp, "graceful-shutdown-throw-test"); var crashing = Substitute.For(); crashing.OnContextStopping(Arg.Any(), Arg.Any()) .Returns(_ => throw new InvalidOperationException("boom")); ctx.AddLifecycleListener(crashing); await ctx.Start(); try { await ctx.Stop(); } catch (InvalidOperationException) { } ctx.IsStarted.Should().BeFalse(); } } Path: redb-identity/tests/redb.Identity.Tests/Module/IdentityModuleConfigBinderTests.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/Module/IdentityModuleConfigBinderTests.cs ---- using System.Net; using AwesomeAssertions; using NSubstitute; using redb.Identity.Contracts.Configuration; using redb.Identity.Core.Configuration; using redb.Identity.Core.Module; using redb.Route.Abstractions; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Module; /// /// Verifies that correctly hydrates /// from the nested IDictionary<string, object?> /// structure that Tsak deposits on the route context via SetProperty. /// public sealed class IdentityModuleConfigBinderTests { private static IRouteContext MakeContext(IDictionary? identitySection) { var sp = Substitute.For(); var ctx = new RouteContext(sp, "_test"); if (identitySection is not null) ctx.SetProperty(IdentityModuleConfigBinder.SectionName, identitySection); return ctx; } [Fact] public void Bind_ReturnsDefaults_WhenNoIdentitySection() { var opts = IdentityModuleConfigBinder.Bind(MakeContext(null)); opts.Should().NotBeNull(); opts.Issuer.Should().Be(new Uri("https://localhost/")); opts.RateLimit.Enabled.Should().BeFalse(); } [Fact] public void Bind_HydratesScalarsAndTimespans() { var section = new Dictionary { ["RedbInstanceName"] = "identity-pg", ["Issuer"] = "https://identity.example.com/", ["AllowEphemeralKeys"] = "true", ["AccessTokenLifetime"] = "00:30:00", ["RecoveryCodePbkdf2Iterations"] = "750000", ["Features"] = new Dictionary { ["EnableDeviceCodeFlow"] = "true", }, }; var opts = IdentityModuleConfigBinder.Bind(MakeContext(section)); opts.RedbInstanceName.Should().Be("identity-pg"); opts.Issuer.Should().Be(new Uri("https://identity.example.com/")); opts.AllowEphemeralKeys.Should().BeTrue(); opts.AccessTokenLifetime.Should().Be(TimeSpan.FromMinutes(30)); opts.RecoveryCodePbkdf2Iterations.Should().Be(750_000); opts.Features.EnableDeviceCodeFlow.Should().BeTrue(); } [Fact] public void Bind_HydratesNestedRateLimitOptions() { var section = new Dictionary { ["RateLimit"] = new Dictionary { ["Enabled"] = "true", ["PerIpPerMinute"] = "120", ["PerIpUsernameFailures"] = "3", ["PerIpUsernameWindow"] = "00:30:00", ["Backend"] = "redis", ["RedisConnectionString"] = "localhost:6379", ["RedisKeyPrefix"] = "myapp:rl:" } }; var opts = IdentityModuleConfigBinder.Bind(MakeContext(section)); opts.RateLimit.Enabled.Should().BeTrue(); opts.RateLimit.PerIpPerMinute.Should().Be(120); opts.RateLimit.PerIpUsernameFailures.Should().Be(3); opts.RateLimit.PerIpUsernameWindow.Should().Be(TimeSpan.FromMinutes(30)); opts.RateLimit.Backend.Should().Be("redis"); opts.RateLimit.RedisConnectionString.Should().Be("localhost:6379"); opts.RateLimit.RedisKeyPrefix.Should().Be("myapp:rl:"); } [Fact] public void Bind_HydratesStringArrays() { var section = new Dictionary { ["DynamicRegistrationAllowedScopes"] = new List { "openid", "profile", "custom_scope" } }; var opts = IdentityModuleConfigBinder.Bind(MakeContext(section)); opts.DynamicRegistrationAllowedScopes.Should().Equal("openid", "profile", "custom_scope"); } [Fact] public void Bind_HydratesFederationProvidersList() { var section = new Dictionary { ["Features"] = new Dictionary { ["EnableFederation"] = "true", }, ["FederationProviders"] = new List { new Dictionary { ["ProviderId"] = "google", ["DisplayName"] = "Google", ["Authority"] = "https://accounts.google.com", ["ClientId"] = "client-1", ["ClientSecret"] = "secret-1", ["Priority"] = "10" } } }; var opts = IdentityModuleConfigBinder.Bind(MakeContext(section)); opts.Features.EnableFederation.Should().BeTrue(); opts.FederationProviders.Should().HaveCount(1); opts.FederationProviders[0].ProviderId.Should().Be("google"); opts.FederationProviders[0].Authority.Should().Be("https://accounts.google.com"); opts.FederationProviders[0].Priority.Should().Be(10); } [Fact] public void Bind_ManuallyParsesIpAddressesAndNetworks() { var section = new Dictionary { ["ReverseProxies"] = new Dictionary { ["TrustForwardedFor"] = "true", ["KnownProxies"] = new List { "10.0.0.1", "203.0.113.7" }, ["KnownNetworks"] = new List { "10.0.0.0/8", "192.168.0.0/16" } } }; var opts = IdentityModuleConfigBinder.Bind(MakeContext(section)); opts.ReverseProxies.TrustForwardedFor.Should().BeTrue(); opts.ReverseProxies.KnownProxies.Should().HaveCount(2); opts.ReverseProxies.KnownProxies.Should().Contain(IPAddress.Parse("10.0.0.1")); opts.ReverseProxies.KnownNetworks.Should().HaveCount(2); opts.ReverseProxies.KnownNetworks[0].BaseAddress.Should().Be(IPAddress.Parse("10.0.0.0")); opts.ReverseProxies.KnownNetworks[0].PrefixLength.Should().Be(8); } // Identity:Audit in a Tsak worker: the module used to hand the route builder no audit options at // all, so configured targets were ignored and events reached only the relational sink. [Fact] public void BindAudit_ReturnsDefaults_WhenNoAuditSection() { var audit = IdentityModuleConfigBinder.BindAudit(MakeContext(new Dictionary { ["Issuer"] = "https://id.example/" })); audit.Enabled.Should().BeTrue(); audit.Filter.Should().Be("*"); audit.Targets.Should().BeEmpty(); } [Fact] public void BindAudit_HydratesTargetsAndSwitches() { var section = new Dictionary { ["Audit"] = new Dictionary { ["Filter"] = "TokenRevoked,UserDeleted", ["PersistToProps"] = "false", ["Targets"] = new List { new Dictionary { ["Name"] = "app", ["Enabled"] = "true", ["Uri"] = "direct-vm://app-identity-events" }, new Dictionary { ["Name"] = "log", ["Enabled"] = "false", ["Uri"] = "log:identity-audit" }, }, }, }; var audit = IdentityModuleConfigBinder.BindAudit(MakeContext(section)); audit.Filter.Should().Be("TokenRevoked,UserDeleted"); audit.PersistToProps.Should().BeFalse(); audit.Targets.Should().HaveCount(2); audit.Targets[0].Name.Should().Be("app"); audit.Targets[0].Enabled.Should().BeTrue(); audit.Targets[0].Uri.Should().Be("direct-vm://app-identity-events"); audit.Targets[1].Enabled.Should().BeFalse(); } [Fact] public void BindAudit_ReadsTargetsGivenAsIndexedKeys() { // An environment override (Identity__Audit__Targets__0__Uri) arrives as a dictionary keyed "0". var section = new Dictionary { ["Audit"] = new Dictionary { ["Targets"] = new Dictionary { ["0"] = new Dictionary { ["Name"] = "app", ["Enabled"] = "true", ["Uri"] = "direct-vm://app-identity-events" }, }, }, }; var audit = IdentityModuleConfigBinder.BindAudit(MakeContext(section)); audit.Targets.Should().ContainSingle() .Which.Uri.Should().Be("direct-vm://app-identity-events"); } } Path: redb-identity/tests/redb.Identity.Tests/Module/IdentityModuleHostTests.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/Module/IdentityModuleHostTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection.Repositories; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using NSubstitute; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Module; using redb.Identity.Core.Services; using redb.Route.Core; using redb.Route.RedbCore.Extensions; using Xunit; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Module; /// /// Smoke tests for — verifies that the child /// built for the .tpkg path resolves all the services that /// the existing IdentityCoreRouteBuilder depends on, without requiring the host /// to pre-register Identity in the root container. /// public sealed class IdentityModuleHostTests { private static (RouteContext Ctx, IRedbService Redb) MakeContext() { var rootServices = new ServiceCollection(); rootServices.AddSingleton(NullLoggerFactory.Instance); rootServices.AddLogging(); var rootSp = rootServices.BuildServiceProvider(); var ctx = new RouteContext(rootSp, "_test", NullLoggerFactory.Instance); var redb = Substitute.For(); // The production bridge resolves IRedbService through an IServiceScopeFactory // looked up at "redb-factory:{name}" (so each child-scope request becomes a // host-side scope and the underlying IRedbService is Scoped). Build a tiny // host SP that registers the substitute as Scoped so per-scope resolutions // still return the same reference under our control. var hostServices = new ServiceCollection(); hostServices.AddScoped(_ => redb); // HostRedbScope now also resolves ISqlDialect from the host scope so the // child container can bridge dialect-aware services without re-registration. hostServices.AddScoped(_ => Substitute.For()); var hostSp = hostServices.BuildServiceProvider(); ctx.AddToRegistry("redb-factory:identity-pg", hostSp.GetRequiredService()); return (ctx, redb); } [Fact] public void Build_WithEphemeralKeys_ResolvesIdentityOptionsAndCoreServices() { var (ctx, _) = MakeContext(); var opts = new RedbIdentityOptions { RedbInstanceName = "identity-pg", AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; using var childSp = IdentityModuleHost.Build(ctx, opts); childSp.GetRequiredService>().Value.AllowEphemeralKeys .Should().BeTrue(); childSp.GetService().Should().NotBeNull(); childSp.GetService().Should().NotBeNull(); childSp.GetService().Should().NotBeNull("PersistKeysToRedb must register IXmlRepository"); childSp.GetService().Should().NotBeNull(); childSp.GetService>() .Should().NotBeNull("AddRedbIdentityServer must wire up OpenIddict server options"); } [Fact] public void Build_WithRateLimitMemoryBackend_ResolvesInMemoryStore() { var (ctx, _) = MakeContext(); var opts = new RedbIdentityOptions { AllowEphemeralKeys = true, DisableAccessTokenEncryption = true, RateLimit = new RateLimitOptions { Enabled = true, Backend = "memory" } }; using var childSp = IdentityModuleHost.Build(ctx, opts); var store = childSp.GetService(); store.Should().NotBeNull(); store.Should().BeOfType(); } [Fact] public void Build_BridgesIRedbServiceFromRouteContextRegistry() { var (ctx, expected) = MakeContext(); var opts = new RedbIdentityOptions { RedbInstanceName = "identity-pg", AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; using var childSp = IdentityModuleHost.Build(ctx, opts); // IRedbService is Scoped inside the child container (per-exchange lifestyle), // so we must open a scope to resolve it — exactly what redb.Route does per HTTP // exchange via IExchange.ServiceProvider. using var scope = childSp.CreateScope(); var bridged = scope.ServiceProvider.GetRequiredService(); ReferenceEquals(bridged, expected).Should().BeTrue( "the child container must reuse the IRedbService registered in the route context registry"); } [Fact] public async Task ChildHostDisposeListener_DisposesChildSpOnContextStopped() { var (ctx, _) = MakeContext(); var opts = new RedbIdentityOptions { AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; var childSp = IdentityModuleHost.Build(ctx, opts); var listener = new ChildHostDisposeListener(childSp); await listener.OnContextStopped(ctx, default); Action act = () => childSp.GetRequiredService>(); act.Should().Throw(); } // ── The transaction-enlistment contract ─────────────────────────────────────────────────── // // These two are the proof that `WithRedbTx` on the token route is meaningful again, and they // are deliberately written at the layer where the bug actually lived: the .tpkg child // container. A test built on a single-SP host would pass with OR without the fix — in that // topology the OpenIddict handler already runs on the exchange's own scope — and would prove // nothing while looking like proof. // // The host factory below hands out a DISTINCT IRedbService per scope, exactly like production // (each scope = its own DB connection). That is what makes "same reference" a real assertion // rather than an artefact of the fixture. /// /// Route context whose named redb factory yields a FRESH per scope — /// one connection per scope, as in production. Reference equality therefore means "the same /// connection", which is the whole question here. /// private static RouteContext MakeContextWithDistinctRedbPerScope() { var rootServices = new ServiceCollection(); rootServices.AddSingleton(NullLoggerFactory.Instance); rootServices.AddLogging(); var rootSp = rootServices.BuildServiceProvider(); var ctx = new RouteContext(rootSp, "_test_tx", NullLoggerFactory.Instance); var hostServices = new ServiceCollection(); hostServices.AddScoped(_ => Substitute.For()); hostServices.AddScoped(_ => Substitute.For()); var hostSp = hostServices.BuildServiceProvider(); ctx.AddToRegistry("redb-factory:identity-pg", hostSp.GetRequiredService()); return ctx; } private static RedbIdentityOptions TxOptions() => new() { RedbInstanceName = "identity-pg", AllowEphemeralKeys = true, DisableAccessTokenEncryption = true }; [Fact] public void ChildScope_BoundToExchange_ResolvesTheExchangeRedbService() { var ctx = MakeContextWithDistinctRedbPerScope(); using var childSp = IdentityModuleHost.Build(ctx, TxOptions()); var exchange = new Exchange(); // The instance the route-level ambient transaction (.Transacted()) enlists. redb.Route // caches its scope on the exchange, so every later ask for the same name returns this one. var transactionService = ctx.GetRedbService("identity-pg", exchange); // What an OpenIddict store gets: a child-container scope, told which exchange it serves. using var scope = childSp.CreateScope(); scope.ServiceProvider.GetRequiredService().Exchange = exchange; var storeService = scope.ServiceProvider.GetRequiredService(); ReferenceEquals(storeService, transactionService).Should().BeTrue( "the OpenIddict stores must write on the SAME IRedbService — and therefore the same DB " + "connection — that the route transaction was opened on. When they did not, the wrap " + "covered a connection nobody was writing on (no atomicity at all), and the stores' own " + "connection then deadlocked against the row locks the transaction held while the " + "transaction awaited them. That is why WithRedbTx had to be stripped from the token " + "route; this assertion is what lets it come back."); } [Fact] public void ChildScope_WithoutExchange_GetsItsOwnRedbService() { var ctx = MakeContextWithDistinctRedbPerScope(); using var childSp = IdentityModuleHost.Build(ctx, TxOptions()); // Out-of-route callers — cleanup timers, hosted services, schema init — have no exchange and // therefore no ambient transaction to join. They must get their own scope: taking somebody // else's connection would be worse than the bug we just fixed. using var scopeA = childSp.CreateScope(); using var scopeB = childSp.CreateScope(); var a = scopeA.ServiceProvider.GetRequiredService(); var b = scopeB.ServiceProvider.GetRequiredService(); ReferenceEquals(a, b).Should().BeFalse( "with no exchange there is no transaction to enlist in, so each scope must keep its own " + "connection — otherwise concurrent background work would serialise onto one connection " + "(the captive-singleton trap this bridge exists to avoid)"); } } Path: redb-identity/tests/redb.Identity.Tests/OAuth/ScopeAndResponseTypeTests.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/OAuth/ScopeAndResponseTypeTests.cs ---- using System.Net; using System.Text.Json; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.OAuth; /// /// G8 — supplemental OAuth/OIDC validation tests beyond what is covered by /// PkceEnforcementTests and RedirectUriValidationTests. /// /// OIDC §3.2.2.1: response_type=id_token requires the openid /// scope; without it the request is malformed. /// RFC 6749 §3.3: scope values are space-delimited; comma-separated scopes /// are NOT a valid scope list — they yield a single bogus scope token. /// /// [Collection("ProductionHttp")] public sealed class ScopeAndResponseTypeTests { private readonly ProductionHttpFixture _fx; public ScopeAndResponseTypeTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task IdTokenResponseType_WithoutOpenidScope_IsRejected() { // OpenID Connect Core §3.2.2.1: when response_type contains id_token, scope // MUST contain "openid" — otherwise the server cannot determine the subject // for the implicit ID token. var (_, challenge) = GeneratePkce(); var resp = await PostAuthorizeAsync(new Dictionary { ["response_type"] = "id_token", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "profile", // intentionally missing "openid" ["nonce"] = "n-" + Guid.NewGuid().ToString("N"), ["code_challenge"] = challenge, ["code_challenge_method"] = "S256", }); await AssertOAuthErrorAsync(resp, "id_token response_type without 'openid' scope must be rejected (OIDC §3.2.2.1)"); } [Fact] public async Task CommaDelimitedScopes_AreNotParsedAsMultipleScopes() { // RFC 6749 §3.3: scope = scope-token *( SP scope-token ). Comma is NOT a // valid delimiter — "openid,profile" is a single (and unregistered) scope // token, so the server must either reject as invalid_scope or treat it as // an unknown scope. It MUST NOT silently grant both "openid" AND "profile". var (_, challenge) = GeneratePkce(); var resp = await PostAuthorizeAsync(new Dictionary { ["response_type"] = "code", ["client_id"] = ProductionHttpFixture.TestPublicClientId, ["redirect_uri"] = ProductionHttpFixture.TestRedirectUri, ["scope"] = "openid,profile", // RFC violation — must NOT be split on comma ["code_challenge"] = challenge, ["code_challenge_method"] = "S256", }); // Acceptable outcomes per RFC 6749 §4.1.2.1: // (a) error=invalid_scope (server recognised the bogus token and refused); // (b) success but the resulting authorization MUST NOT include a "profile" // scope grant — comma split would be a security regression. if (resp.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found) { var location = resp.Headers.Location?.ToString() ?? ""; // If redirected back with a code, the only granted scope can be "openid,profile" // as a single token (which is unregistered), or nothing — never the split set. location.Should().NotContain("scope=openid+profile", "comma-delimited scope must NOT be silently split into space-delimited grant"); location.Should().NotContain("scope=openid%20profile", "comma-delimited scope must NOT be silently split into space-delimited grant"); } else { // Direct error response — must be invalid_scope or invalid_request, never 200. resp.IsSuccessStatusCode.Should().BeFalse( "comma-delimited scope must be rejected as malformed"); } } // ─────────────── helpers ─────────────── private async Task PostAuthorizeAsync(IDictionary form) { var cookieJar = new CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookieJar, UseCookies = true, }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); return await client.PostAsync("/connect/authorize", new FormUrlEncodedContent(form)); } private static async Task AssertOAuthErrorAsync(HttpResponseMessage resp, string because) { if (resp.StatusCode is HttpStatusCode.Redirect or HttpStatusCode.Found) { var location = resp.Headers.Location?.ToString() ?? ""; location.Should().MatchRegex(@"error=(invalid_request|invalid_scope|unsupported_response_type)", because); return; } resp.IsSuccessStatusCode.Should().BeFalse(because + $". Got {resp.StatusCode}"); var body = await resp.Content.ReadAsStringAsync(); if (body.Length > 0 && body.TrimStart().StartsWith('{')) { var json = JsonDocument.Parse(body).RootElement; if (json.TryGetProperty("error", out var err)) { err.GetString().Should().BeOneOf( "invalid_request", "invalid_scope", "unsupported_response_type"); } } } private static (string verifier, string challenge) GeneratePkce() { var bytes = new byte[32]; System.Security.Cryptography.RandomNumberGenerator.Fill(bytes); var verifier = Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_'); var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.ASCII.GetBytes(verifier)); var challenge = Convert.ToBase64String(hash).TrimEnd('=').Replace('+', '-').Replace('/', '_'); return (verifier, challenge); } } Path: redb-identity/tests/redb.Identity.Tests/OpenIddict/Adapter/AdapterIntegrationTests.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/OpenIddict/Adapter/AdapterIntegrationTests.cs ---- using System.Security.Claims; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Identity.Core.OpenIddict; using redb.Identity.Tests.Infrastructure; using Xunit; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Tests.Adapter; /// /// Integration tests proving the full adapter pipeline works end-to-end: /// IExchange → Extract handlers → OpenIddict pipeline → Apply handlers → IExchange.Out /// public class AdapterIntegrationTests { private static ServiceProvider BuildServiceProvider() { var services = new ServiceCollection(); services.AddLogging(b => b.SetMinimumLevel(LogLevel.Warning)); services.AddOpenIddict() .AddServer(options => { options.EnableDegradedMode(); options.SetIssuer(new Uri("https://identity.test.local/")); options.SetTokenEndpointUris("/connect/token"); options.AllowClientCredentialsFlow(); options.AddEphemeralEncryptionKey(); options.AddEphemeralSigningKey(); options.DisableAccessTokenEncryption(); // Register our redb.Route adapter options.UseRedbRoute(); // Degraded mode requires a custom validation handler options.AddEventHandler(builder => builder .UseInlineHandler(context => default) .SetOrder(int.MaxValue - 100_000) .Build()); // Custom handler: provide ClaimsPrincipal for client_credentials options.AddEventHandler(builder => builder .UseInlineHandler(context => { if (!context.Request.IsClientCredentialsGrantType()) return default; var identity = new ClaimsIdentity( authenticationType: "OpenIddict.Server", nameType: Claims.Name, roleType: Claims.Role); identity.SetClaim(Claims.Subject, context.Request.ClientId!); context.Principal = new ClaimsPrincipal(identity); return default; }) .SetOrder(OpenIddictServerHandlers.Exchange.AttachPrincipal .Descriptor.Order + 100) .Build()); }); return services.BuildServiceProvider(); } [Fact] public async Task ClientCredentials_ViaExchange_ProducesAccessToken() { await using var sp = BuildServiceProvider(); using var scope = sp.CreateScope(); var handler = scope.ServiceProvider.GetRequiredService(); // Simulate IExchange from direct-vm://identity-token var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "test-client", ["client_secret"] = "test-secret" }; await handler.ProcessAsync(exchange, OpenIddictServerEndpointType.Token); // Verify response written to exchange exchange.Out.Should().NotBeNull("Apply handler should write the response"); exchange.Out!.ContentType.Should().Be("application/json"); var body = exchange.Out.Body.Should().BeOfType>().Subject; body.Should().ContainKey("access_token"); body["access_token"].Should().NotBeNull(); body["access_token"]!.ToString().Should().NotBeEmpty("JWT access token should be generated"); body["token_type"].Should().Be("Bearer"); body["expires_in"].Should().NotBeNull(); } [Fact] public async Task ClientCredentials_ViaBasicAuth_ProducesAccessToken() { await using var sp = BuildServiceProvider(); using var scope = sp.CreateScope(); var handler = scope.ServiceProvider.GetRequiredService(); var credentials = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes("basic-client:basic-secret")); var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["grant_type"] = "client_credentials" }; exchange.In.Headers["Authorization"] = $"Basic {credentials}"; await handler.ProcessAsync(exchange, OpenIddictServerEndpointType.Token); exchange.Out.Should().NotBeNull(); var body = exchange.Out!.Body.Should().BeOfType>().Subject; body.Should().ContainKey("access_token"); body["token_type"].Should().Be("Bearer"); } [Fact] public async Task InvalidGrantType_ReturnsError() { await using var sp = BuildServiceProvider(); using var scope = sp.CreateScope(); var handler = scope.ServiceProvider.GetRequiredService(); var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["grant_type"] = "password", // not allowed ["client_id"] = "test-client", ["client_secret"] = "test-secret" }; await handler.ProcessAsync(exchange, OpenIddictServerEndpointType.Token); exchange.Out.Should().NotBeNull(); var body = exchange.Out!.Body.Should().BeOfType>().Subject; body.Should().ContainKey("error"); body["error"].Should().Be("unsupported_grant_type"); } } Path: redb-identity/tests/redb.Identity.Tests/OpenIddict/Adapter/ApplyHandlerTests.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/OpenIddict/Adapter/ApplyHandlerTests.cs ---- using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Options; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Identity.Core.Configuration; using redb.Identity.Core.OpenIddict; using redb.Identity.Core.OpenIddict.Handlers; using redb.Identity.Tests.Infrastructure; using redb.Route.Abstractions; using Xunit; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Tests.Adapter; public class ApplyHandlerTests { private static (OpenIddictServerTransaction transaction, TestExchange exchange) CreateTransactionWithExchange() { var exchange = new TestExchange(); var transaction = new OpenIddictServerTransaction(); transaction.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = exchange; return (transaction, exchange); } [Fact] public async Task ApplyTokenResponse_SuccessResponse_WritesToExchangeOut() { var (transaction, exchange) = CreateTransactionWithExchange(); transaction.Response = new OpenIddictResponse(); transaction.Response.AccessToken = "eyJ-test-token"; transaction.Response.TokenType = "Bearer"; transaction.Response.ExpiresIn = 3600; var context = new ApplyTokenResponseContext(transaction); await new ApplyTokenResponseHandler().HandleAsync(context); exchange.Out.Should().NotBeNull(); exchange.Out!.ContentType.Should().Be("application/json"); exchange.Pattern.Should().Be(ExchangePattern.InOut); context.IsRequestHandled.Should().BeTrue(); var body = exchange.Out.Body.Should().BeOfType>().Subject; body["access_token"].Should().Be("eyJ-test-token"); body["token_type"].Should().Be("Bearer"); body["expires_in"].Should().Be(3600L); } [Fact] public async Task ApplyTokenResponse_ErrorResponse_WritesErrorToExchangeOut() { var (transaction, exchange) = CreateTransactionWithExchange(); transaction.Response = new OpenIddictResponse { Error = "invalid_client", ErrorDescription = "Unknown client" }; var context = new ApplyTokenResponseContext(transaction); await new ApplyTokenResponseHandler().HandleAsync(context); exchange.Out.Should().NotBeNull(); context.IsRequestHandled.Should().BeTrue(); var body = exchange.Out!.Body.Should().BeOfType>().Subject; body["error"].Should().Be("invalid_client"); body["error_description"].Should().Be("Unknown client"); } [Fact] public async Task ApplyTokenResponse_NoExchange_Skips() { var transaction = new OpenIddictServerTransaction(); transaction.Response = new OpenIddictResponse(); var context = new ApplyTokenResponseContext(transaction); await new ApplyTokenResponseHandler().HandleAsync(context); context.IsRequestHandled.Should().BeFalse(); } [Fact] public async Task ApplyAuthorizationResponse_WritesToExchangeOut() { var (transaction, exchange) = CreateTransactionWithExchange(); transaction.Response = new OpenIddictResponse(); transaction.Response.Code = "auth-code-123"; var context = new ApplyAuthorizationResponseContext(transaction); await new ApplyAuthorizationResponseHandler().HandleAsync(context); exchange.Out.Should().NotBeNull(); context.IsRequestHandled.Should().BeTrue(); var body = exchange.Out!.Body.Should().BeOfType>().Subject; body["code"].Should().Be("auth-code-123"); } [Fact] public async Task ApplyIntrospectionResponse_WritesToExchangeOut() { var (transaction, exchange) = CreateTransactionWithExchange(); transaction.Response = new OpenIddictResponse(); transaction.Response.SetParameter("active", new OpenIddictParameter(true)); var context = new ApplyIntrospectionResponseContext(transaction); await new ApplyIntrospectionResponseHandler().HandleAsync(context); exchange.Out.Should().NotBeNull(); context.IsRequestHandled.Should().BeTrue(); } [Fact] public async Task ApplyRevocationResponse_WritesToExchangeOut() { var (transaction, exchange) = CreateTransactionWithExchange(); transaction.Response = new OpenIddictResponse(); var context = new ApplyRevocationResponseContext(transaction); await new ApplyRevocationResponseHandler().HandleAsync(context); exchange.Out.Should().NotBeNull(); context.IsRequestHandled.Should().BeTrue(); } [Fact] public async Task ApplyDiscoveryResponse_WritesToExchangeOut() { var (transaction, exchange) = CreateTransactionWithExchange(); transaction.Response = new OpenIddictResponse(); transaction.Response.SetParameter("issuer", new OpenIddictParameter("https://identity.local/")); var context = new ApplyConfigurationResponseContext(transaction); await new ApplyDiscoveryResponseHandler(Options.Create(new RedbIdentityOptions())).HandleAsync(context); exchange.Out.Should().NotBeNull(); context.IsRequestHandled.Should().BeTrue(); var body = exchange.Out!.Body.Should().BeOfType>().Subject; body["issuer"].Should().Be("https://identity.local/"); } [Theory] [InlineData(false, true, true, true)] // JAR off: nothing about request_uri is published [InlineData(true, true, true, true)] [InlineData(true, true, false, false)] [InlineData(true, false, true, null)] // request_uri off: the flag is not published public async Task ApplyDiscoveryResponse_PublishesRequireRequestUriRegistration( bool enableJar, bool enableRequestUri, bool requireRegistration, bool? expected) { var (transaction, exchange) = CreateTransactionWithExchange(); transaction.Response = new OpenIddictResponse(); transaction.Response.SetParameter("issuer", new OpenIddictParameter("https://identity.local/")); var options = new RedbIdentityOptions(); options.Features.EnableJar = enableJar; options.Jar.EnableRequestUri = enableRequestUri; options.Jar.RequireRequestUriRegistration = requireRegistration; await new ApplyDiscoveryResponseHandler(Options.Create(options)).HandleAsync(new ApplyConfigurationResponseContext(transaction)); var body = exchange.Out!.Body.Should().BeOfType>().Subject; if (!enableJar || expected is null) body.Should().NotContainKey("require_request_uri_registration"); else body["require_request_uri_registration"]!.ToString()!.ToLowerInvariant().Should().Be(expected.Value ? "true" : "false"); } [Fact] public async Task ApplyUserinfoResponse_WritesToExchangeOut() { var (transaction, exchange) = CreateTransactionWithExchange(); transaction.Response = new OpenIddictResponse(); transaction.Response.SetParameter("sub", new OpenIddictParameter("user-123")); var context = new ApplyUserInfoResponseContext(transaction); await new ApplyUserinfoResponseHandler().HandleAsync(context); exchange.Out.Should().NotBeNull(); context.IsRequestHandled.Should().BeTrue(); var body = exchange.Out!.Body.Should().BeOfType>().Subject; body["sub"].Should().Be("user-123"); } [Fact] public async Task ApplyTokenResponse_PreservesExistingOut() { var (transaction, exchange) = CreateTransactionWithExchange(); transaction.Response = new OpenIddictResponse { AccessToken = "tok" }; // Pre-create Out message exchange.Out = new TestMessage(); var context = new ApplyTokenResponseContext(transaction); await new ApplyTokenResponseHandler().HandleAsync(context); // Should reuse existing Out, not create a new one exchange.Out.Should().NotBeNull(); var body = exchange.Out!.Body.Should().BeOfType>().Subject; body["access_token"].Should().Be("tok"); } [Fact] public async Task ApplyTokenResponse_NormalizesJsonElementValues() { var (transaction, exchange) = CreateTransactionWithExchange(); transaction.Response = new OpenIddictResponse(); // SetParameter with JsonElement values (as OpenIddict may produce internally) transaction.Response.SetParameter("string_val", new OpenIddictParameter(JsonSerializer.Deserialize("\"hello\""))); transaction.Response.SetParameter("number_val", new OpenIddictParameter(JsonSerializer.Deserialize("42"))); transaction.Response.SetParameter("bool_val", new OpenIddictParameter(JsonSerializer.Deserialize("true"))); var context = new ApplyTokenResponseContext(transaction); await new ApplyTokenResponseHandler().HandleAsync(context); var body = exchange.Out!.Body.Should().BeOfType>().Subject; // JsonElement should be unwrapped to native types, not left as JsonElement body["string_val"].Should().BeOfType().And.Be("hello"); body["number_val"].Should().NotBeOfType("numbers should be unwrapped"); Convert.ToInt64(body["number_val"]).Should().Be(42L); body["bool_val"].Should().BeOfType().And.Be(true); } } Path: redb-identity/tests/redb.Identity.Tests/OpenIddict/Adapter/ExtractClientCredentialsTests.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/OpenIddict/Adapter/ExtractClientCredentialsTests.cs ---- using AwesomeAssertions; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Identity.Core.OpenIddict; using redb.Identity.Core.OpenIddict.Handlers; using redb.Identity.Tests.Infrastructure; using Xunit; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Tests.Adapter; public class ExtractClientCredentialsTests { private static (ExtractTokenRequestContext context, TestExchange exchange) SetupToken( Dictionary? body = null, string? authorizationHeader = null) { var exchange = new TestExchange(); if (body != null) exchange.In.Body = body; if (authorizationHeader != null) exchange.In.Headers["Authorization"] = authorizationHeader; var transaction = new OpenIddictServerTransaction(); transaction.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = exchange; var context = new ExtractTokenRequestContext(transaction); // Pre-populate request (as if ExtractTokenRequestHandler already ran) context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); return (context, exchange); } [Fact] public async Task BasicAuth_ExtractsClientIdAndSecret() { var credentials = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes("my-client:my-secret")); var (context, _) = SetupToken(authorizationHeader: $"Basic {credentials}"); await new ExtractClientCredentialsHandler().HandleAsync(context); context.Request!.ClientId.Should().Be("my-client"); context.Request.ClientSecret.Should().Be("my-secret"); } [Fact] public async Task BasicAuth_UrlEncodedCredentials_DecodesCorrectly() { // client_id contains special chars: "app%23test" → decoded "app#test" var credentials = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes("app%23test:s%26cret")); var (context, _) = SetupToken(authorizationHeader: $"Basic {credentials}"); await new ExtractClientCredentialsHandler().HandleAsync(context); context.Request!.ClientId.Should().Be("app#test"); context.Request.ClientSecret.Should().Be("s&cret"); } [Fact] public async Task BasicAuth_OverridesBodyCredentials() { var body = new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "body-client", ["client_secret"] = "body-secret" }; var credentials = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes("header-client:header-secret")); var (context, _) = SetupToken(body, $"Basic {credentials}"); await new ExtractClientCredentialsHandler().HandleAsync(context); // Basic auth should override body-based credentials (RFC 6749 §2.3.1) context.Request!.ClientId.Should().Be("header-client"); context.Request.ClientSecret.Should().Be("header-secret"); } [Fact] public async Task NoAuthorizationHeader_LeavesRequestUnchanged() { var body = new Dictionary { ["client_id"] = "body-only", ["client_secret"] = "body-secret" }; var (context, _) = SetupToken(body); await new ExtractClientCredentialsHandler().HandleAsync(context); context.Request!.ClientId.Should().Be("body-only"); context.Request.ClientSecret.Should().Be("body-secret"); } [Fact] public async Task BearerToken_NotBasic_LeavesRequestUnchanged() { var (context, _) = SetupToken(authorizationHeader: "Bearer eyJhbGciOiJSUzI1NiJ9"); await new ExtractClientCredentialsHandler().HandleAsync(context); // Bearer tokens are not client credentials context.Request!.ClientId.Should().BeNull(); context.Request.ClientSecret.Should().BeNull(); } [Fact] public async Task InvalidBase64_RejectsWithInvalidClient() { var (context, _) = SetupToken(authorizationHeader: "Basic !!!not-base64!!!"); await new ExtractClientCredentialsHandler().HandleAsync(context); // The client attempted header authentication: a failed one, not a missing client_id (RFC 6749 5.2). context.IsRejected.Should().BeTrue(); context.Error.Should().Be(OpenIddictConstants.Errors.InvalidClient); context.Request!.ClientId.Should().BeNull(); } [Fact] public async Task BasicAuth_NoColon_RejectsWithInvalidClient() { var credentials = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes("no-colon-here")); var (context, _) = SetupToken(authorizationHeader: $"Basic {credentials}"); await new ExtractClientCredentialsHandler().HandleAsync(context); context.IsRejected.Should().BeTrue(); context.Error.Should().Be(OpenIddictConstants.Errors.InvalidClient); context.Request!.ClientId.Should().BeNull(); } [Fact] public async Task NoExchangeInTransaction_Skips() { var transaction = new OpenIddictServerTransaction(); transaction.Request = new OpenIddictRequest { ClientId = "keep-me" }; var context = new ExtractTokenRequestContext(transaction); context.Request = transaction.Request; await new ExtractClientCredentialsHandler().HandleAsync(context); // Should not modify anything context.Request!.ClientId.Should().Be("keep-me"); } // ── Introspection endpoint ── [Fact] public async Task Introspection_BasicAuth_ExtractsCredentials() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["token"] = "some-token" }; var creds = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes("intro-client:intro-secret")); exchange.In.Headers["Authorization"] = $"Basic {creds}"; var transaction = new OpenIddictServerTransaction(); transaction.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = exchange; var context = new ExtractIntrospectionRequestContext(transaction); context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); await new ExtractIntrospectionClientCredentialsHandler().HandleAsync(context); context.Request!.ClientId.Should().Be("intro-client"); context.Request.ClientSecret.Should().Be("intro-secret"); } [Fact] public async Task Introspection_NoBasicAuth_LeavesUnchanged() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["token"] = "some-token", ["client_id"] = "body-client" }; var transaction = new OpenIddictServerTransaction(); transaction.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = exchange; var context = new ExtractIntrospectionRequestContext(transaction); context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); await new ExtractIntrospectionClientCredentialsHandler().HandleAsync(context); context.Request!.ClientId.Should().Be("body-client"); } // ── Revocation endpoint ── [Fact] public async Task Revocation_BasicAuth_ExtractsCredentials() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["token"] = "revoke-me" }; var creds = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes("revoke-client:revoke-secret")); exchange.In.Headers["Authorization"] = $"Basic {creds}"; var transaction = new OpenIddictServerTransaction(); transaction.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = exchange; var context = new ExtractRevocationRequestContext(transaction); context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); await new ExtractRevocationClientCredentialsHandler().HandleAsync(context); context.Request!.ClientId.Should().Be("revoke-client"); context.Request.ClientSecret.Should().Be("revoke-secret"); } [Fact] public async Task Revocation_NoBasicAuth_LeavesUnchanged() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["token"] = "revoke-me", ["client_id"] = "body-client" }; var transaction = new OpenIddictServerTransaction(); transaction.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = exchange; var context = new ExtractRevocationRequestContext(transaction); context.Request = RedbRouteOpenIddictServerHelpers.CreateRequestFromExchange(exchange); await new ExtractRevocationClientCredentialsHandler().HandleAsync(context); context.Request!.ClientId.Should().Be("body-client"); } } Path: redb-identity/tests/redb.Identity.Tests/OpenIddict/Adapter/ExtractHandlerTests.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/OpenIddict/Adapter/ExtractHandlerTests.cs ---- using AwesomeAssertions; using OpenIddict.Abstractions; using OpenIddict.Server; using redb.Identity.Core.OpenIddict; using redb.Identity.Core.OpenIddict.Handlers; using redb.Identity.Tests.Infrastructure; using Xunit; using static OpenIddict.Abstractions.OpenIddictConstants; using static OpenIddict.Server.OpenIddictServerEvents; namespace redb.Identity.Tests.Adapter; public class ExtractHandlerTests { private static OpenIddictServerTransaction CreateTransaction(TestExchange exchange) { var transaction = new OpenIddictServerTransaction(); transaction.Properties[RedbRouteOpenIddictServerHelpers.ExchangePropertyKey] = exchange; return transaction; } [Fact] public async Task ExtractToken_DictionaryStringString_PopulatesRequest() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "my-app", ["client_secret"] = "my-secret", ["scope"] = "api" }; var context = new ExtractTokenRequestContext(CreateTransaction(exchange)); var handler = new ExtractTokenRequestHandler(); await handler.HandleAsync(context); context.Request.Should().NotBeNull(); context.Request!.GrantType.Should().Be(GrantTypes.ClientCredentials); context.Request.ClientId.Should().Be("my-app"); context.Request.ClientSecret.Should().Be("my-secret"); context.Request.Scope.Should().Be("api"); } [Fact] public async Task ExtractToken_DictionaryStringObject_PopulatesRequest() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["grant_type"] = "authorization_code", ["code"] = "abc123", ["redirect_uri"] = "https://example.com/cb" }; var context = new ExtractTokenRequestContext(CreateTransaction(exchange)); await new ExtractTokenRequestHandler().HandleAsync(context); context.Request.Should().NotBeNull(); context.Request!.GrantType.Should().Be(GrantTypes.AuthorizationCode); context.Request.Code.Should().Be("abc123"); context.Request.RedirectUri.Should().Be("https://example.com/cb"); } [Fact] public async Task ExtractToken_FormUrlEncodedString_PopulatesRequest() { var exchange = new TestExchange(); exchange.In.Body = "grant_type=client_credentials&client_id=url-app&client_secret=s%26cret"; var context = new ExtractTokenRequestContext(CreateTransaction(exchange)); await new ExtractTokenRequestHandler().HandleAsync(context); context.Request.Should().NotBeNull(); context.Request!.GrantType.Should().Be(GrantTypes.ClientCredentials); context.Request.ClientId.Should().Be("url-app"); context.Request.ClientSecret.Should().Be("s&cret"); // decoded } [Fact] public async Task ExtractToken_OpenIddictRequest_UsedDirectly() { var original = new OpenIddictRequest { GrantType = GrantTypes.ClientCredentials, ClientId = "direct-client" }; var exchange = new TestExchange(); exchange.In.Body = original; var context = new ExtractTokenRequestContext(CreateTransaction(exchange)); await new ExtractTokenRequestHandler().HandleAsync(context); context.Request.Should().BeSameAs(original); } [Fact] public async Task ExtractToken_NullBody_CreatesEmptyRequest() { var exchange = new TestExchange(); exchange.In.Body = null; var context = new ExtractTokenRequestContext(CreateTransaction(exchange)); await new ExtractTokenRequestHandler().HandleAsync(context); context.Request.Should().NotBeNull(); context.Request!.GrantType.Should().BeNull(); } [Fact] public async Task ExtractToken_NoExchangeInTransaction_Skips() { var transaction = new OpenIddictServerTransaction(); // No exchange stored → handler should skip var context = new ExtractTokenRequestContext(transaction); await new ExtractTokenRequestHandler().HandleAsync(context); context.Request.Should().BeNull(); } [Fact] public async Task ExtractAuthorization_PopulatesRequest() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["response_type"] = "code", ["client_id"] = "auth-client", ["redirect_uri"] = "https://example.com/cb", ["scope"] = "openid profile" }; var context = new ExtractAuthorizationRequestContext(CreateTransaction(exchange)); await new ExtractAuthorizationRequestHandler().HandleAsync(context); context.Request.Should().NotBeNull(); context.Request!.ResponseType.Should().Be("code"); context.Request.ClientId.Should().Be("auth-client"); } [Fact] public async Task ExtractIntrospection_PopulatesRequest() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["token"] = "my-token", ["token_type_hint"] = "access_token" }; var context = new ExtractIntrospectionRequestContext(CreateTransaction(exchange)); await new ExtractIntrospectionRequestHandler().HandleAsync(context); context.Request.Should().NotBeNull(); context.Request!.Token.Should().Be("my-token"); context.Request.TokenTypeHint.Should().Be("access_token"); } [Fact] public async Task ExtractRevocation_PopulatesRequest() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["token"] = "revoke-token" }; var context = new ExtractRevocationRequestContext(CreateTransaction(exchange)); await new ExtractRevocationRequestHandler().HandleAsync(context); context.Request.Should().NotBeNull(); context.Request!.Token.Should().Be("revoke-token"); } [Fact] public async Task ExtractUserinfo_BearerToken_SetsAccessToken() { var exchange = new TestExchange(); exchange.In.Body = null; exchange.In.Headers["Authorization"] = "Bearer eyJhbGciOiJSUzI1NiJ9"; var context = new ExtractUserInfoRequestContext(CreateTransaction(exchange)); await new ExtractUserinfoRequestHandler().HandleAsync(context); context.Request.Should().NotBeNull(); context.Request!.AccessToken.Should().Be("eyJhbGciOiJSUzI1NiJ9"); } } Path: redb-identity/tests/redb.Identity.Tests/Pipeline/AppManagementPipelineTests.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/Pipeline/AppManagementPipelineTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Core.Models.Entities; using redb.Identity.Contracts.Applications; using redb.Identity.Contracts.Common; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Pipeline; /// /// Application management through the full route pipeline. /// Validates: route wiring → processor → WireTap → event dispatch. /// [Collection("IdentityRoute")] public class AppManagementPipelineTests { private readonly IdentityRouteFixture _fixture; public AppManagementPipelineTests(IdentityRouteFixture fixture) => _fixture = fixture; [Fact] public async Task CreateApp_ThroughPipeline_ReturnsApplicationResponse() { MockRedbQuery.Setup(_fixture.Redb, new List>()); _fixture.Redb.SaveAsync(Arg.Any>()) .Returns(ci => { ci.Arg>().Id = 100; return 100L; }); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, new CreateApplicationRequest { ClientId = "pipeline-app", ClientSecret = "secret", ClientType = "confidential", DisplayName = "Pipeline App" }, new Dictionary { ["operation"] = "create" }); exchange.Exception.Should().BeNull(); var resp = exchange.In.Body.Should().BeOfType().Subject; resp.ClientId.Should().Be("pipeline-app"); resp.DisplayName.Should().Be("Pipeline App"); } [Fact] public async Task CreateApp_MissingClientId_ReturnsError() { var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, new CreateApplicationRequest { ClientId = "" }, new Dictionary { ["operation"] = "create" }); exchange.Exception.Should().BeNull(); var body = exchange.In.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } [Fact] public async Task ReadApp_ById_ReturnsApplication() { var app = MockRedbQuery.CreateObject(42, "Test", new ApplicationProps { ClientId = "read-pipeline" }); _fixture.Redb.LoadAsync(42).Returns(app); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, new Dictionary { ["id"] = 42L }, new Dictionary { ["operation"] = "read" }); exchange.Exception.Should().BeNull(); var resp = exchange.In.Body.Should().BeOfType().Subject; resp.ClientId.Should().Be("read-pipeline"); } [Fact] public async Task ListApps_ThroughPipeline_ReturnsPaginated() { var items = Enumerable.Range(1, 3) .Select(i => MockRedbQuery.CreateObject(i, $"App{i}", new ApplicationProps { ClientId = $"list-{i}" })) .ToList(); MockRedbQuery.Setup(_fixture.Redb, items); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, new ListRequest { Offset = 0, Count = 10 }, new Dictionary { ["operation"] = "list" }); exchange.Exception.Should().BeNull(); var result = exchange.In.Body.Should().BeOfType>().Subject; result.Total.Should().Be(3); result.Items.Should().HaveCount(3); } [Fact] public async Task DeleteApp_ThroughPipeline_ReturnsSuccess() { // The delete looks the record up first; it exists and is of this resource. _fixture.Redb.LoadAsync(55).Returns(new RedbObject(new ApplicationProps()) { id = 55 }); _fixture.Redb.DeleteAsync(55).Returns(true); // The delete revokes the client's tokens first; this client has none. MockRedbQuery.Setup(_fixture.Redb, new List>()); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, new Dictionary { ["id"] = 55L }, new Dictionary { ["operation"] = "delete" }); exchange.Exception.Should().BeNull(); var body = exchange.In.Body.Should().BeOfType().Subject; body.Success.Should().BeTrue(); } [Fact] public async Task UnknownOperation_ThroughPipeline_ReturnsError() { var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, null, new Dictionary { ["operation"] = "nuke" }); exchange.Exception.Should().BeNull(); var body = exchange.In.Body.Should().BeOfType().Subject; body.Error.Should().Be("invalid_operation"); } } Path: redb-identity/tests/redb.Identity.Tests/Pipeline/DiscoveryPipelineTests.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/Pipeline/DiscoveryPipelineTests.cs ---- using AwesomeAssertions; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Pipeline; /// /// Discovery and JWKS endpoints through the full route pipeline. /// [Collection("IdentityRoute")] public class DiscoveryPipelineTests { private readonly IdentityRouteFixture _fixture; public DiscoveryPipelineTests(IdentityRouteFixture fixture) => _fixture = fixture; [Fact] public async Task Discovery_ThroughPipeline_ReturnsConfiguration() { var result = await _fixture.Request(IdentityEndpoints.Discovery, new { }); result.Should().NotBeNull(); var dict = result.Should().BeOfType>().Subject; dict.Should().ContainKey("issuer"); dict["issuer"]!.ToString().Should().Contain("identity.test.local"); } [Fact] public async Task Jwks_ThroughPipeline_ReturnsKeys() { var result = await _fixture.Request(IdentityEndpoints.Jwks, new { }); result.Should().NotBeNull(); var dict = result.Should().BeOfType>().Subject; dict.Should().ContainKey("keys"); } [Fact] public async Task Discovery_ContainsTokenEndpoint() { var result = await _fixture.Request(IdentityEndpoints.Discovery, new { }); var dict = result.Should().BeOfType>().Subject; dict.Should().ContainKey("token_endpoint"); } [Fact] public async Task Discovery_ContainsGrantTypesSupported() { var result = await _fixture.Request(IdentityEndpoints.Discovery, new { }); var dict = result.Should().BeOfType>().Subject; dict.Should().ContainKey("grant_types_supported"); } } Path: redb-identity/tests/redb.Identity.Tests/Pipeline/ErrorHandlingPipelineTests.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/Pipeline/ErrorHandlingPipelineTests.cs ---- using System.Data.Common; using AwesomeAssertions; using NSubstitute; using NSubstitute.ExceptionExtensions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Identity.Contracts; using redb.Identity.Contracts.Applications; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using Xunit; using redb.Identity.Contracts.Users; using CoreCreateUserRequest = redb.Core.Models.Users.CreateUserRequest; namespace redb.Identity.Tests.Pipeline; /// /// Tests that builder-level error handling (OnException, DoTry/DoCatch) works end-to-end. /// These are the bugs that ONLY integration tests catch — unit tests bypass error handling. /// [Collection("IdentityRoute")] public class ErrorHandlingPipelineTests { private readonly IdentityRouteFixture _fixture; public ErrorHandlingPipelineTests(IdentityRouteFixture fixture) => _fixture = fixture; [Fact] public async Task DbException_ReturnsDatabaseUnavailable_NotStackTrace() { // Simulate DB failure during app creation MockRedbQuery.Setup(_fixture.Redb, new List>()); _fixture.Redb.SaveAsync(Arg.Any>()) .ThrowsAsync(CreateDbException("connection refused")); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, new CreateApplicationRequest { ClientId = "db-fail-app", ClientSecret = "secret", ClientType = "confidential" }, new Dictionary { ["operation"] = "create" }); // Reset mock to avoid contaminating other tests _fixture.Redb.SaveAsync(Arg.Any>()) .Returns(ci => { ci.Arg>().Id = 1; return 1L; }); // Builder-level OnException should catch this exchange.ExceptionHandled.Should().BeTrue(); var body = exchange.In.Body; body.Should().NotBeNull(); if (body is Dictionary dict) { dict["error"].Should().Be("server_error"); dict["error_description"]!.ToString().Should().Contain("Database temporarily unavailable"); // No stack trace leaked dict["error_description"]!.ToString().Should().NotContain("connection refused"); } } [Fact] public async Task UnexpectedException_ReturnsGenericError_NotInternals() { // Simulate unexpected exception _fixture.Redb.LoadAsync(Arg.Any()) .ThrowsAsync(new InvalidOperationException("Internal details should not leak")); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, new Dictionary { ["id"] = 999L }, new Dictionary { ["operation"] = "read" }); // Reset mock to avoid contaminating other tests _fixture.Redb.LoadAsync(Arg.Any()).Returns((RedbObject?)null); // Builder-level OnException catch-all exchange.ExceptionHandled.Should().BeTrue(); var body = exchange.Out!.Body; body.Should().NotBeNull(); if (body is Dictionary dict) { dict["error"].Should().Be("server_error"); dict["error_description"]!.ToString().Should().Contain("unexpected error"); // No internal details leaked dict["error_description"]!.ToString().Should().NotContain("Internal details"); } } [Fact] public async Task MissingOperationHeader_CaughtByErrorHandler() { // Missing "operation" header → processor throws InvalidOperationException var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, new CreateApplicationRequest { ClientId = "test" }, new Dictionary()); // Should be handled, not thrown out exchange.ExceptionHandled.Should().BeTrue(); var body = exchange.In.Body; body.Should().NotBeNull(); } [Fact] public async Task ManageScopes_DbException_ReturnsDatabaseError() { // DB failure on scope save (avoids ThrowsForAnyArgs on Query which can't be reset) MockRedbQuery.Setup(_fixture.Redb, new List>()); _fixture.Redb.SaveAsync(Arg.Any>()) .ThrowsAsync(CreateDbException("timeout")); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageScopes, new Contracts.Scopes.CreateScopeRequest { Name = "fail-scope", DisplayName = "Fail" }, new Dictionary { ["operation"] = "create" }); // Reset mock to avoid contaminating other tests _fixture.Redb.SaveAsync(Arg.Any>()) .Returns(ci => { ci.Arg>().Id = 1; return 1L; }); exchange.ExceptionHandled.Should().BeTrue(); if (exchange.In.Body is Dictionary dict) { dict["error"].Should().Be("server_error"); } } [Fact] public async Task ManageUsers_UnexpectedError_HandledGracefully() { _fixture.Redb.UserProvider.GetUserByIdAsync(Arg.Any()) .ThrowsAsync(new NullReferenceException("oops")); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageUsers, new Dictionary { ["id"] = 1L }, new Dictionary { ["operation"] = "read" }); // Reset mock to avoid contaminating other tests _fixture.Redb.UserProvider.GetUserByIdAsync(Arg.Any()).Returns((IRedbUser?)null); exchange.ExceptionHandled.Should().BeTrue(); if (exchange.Out!.Body is Dictionary dict) { dict["error"].Should().Be("server_error"); dict["error_description"]!.ToString().Should().NotContain("oops"); } } /// /// Creates a minimal DbException subclass for testing. /// DbException is abstract, so we need a concrete implementation. /// [Fact] public async Task UniqueViolation_IsAConflict_NotADatabaseOutage() { // A unique-constraint violation is deterministic: retrying it cannot help, and 503 tells the // caller "the database is down, come back later" about a conflict only they can resolve. // // Deliberately on the users surface. ApplicationManagementProcessor catches unique violations // itself, so that path was always right; users, groups, roles and SCIM do not, and fell through // to the builder-level handler that answered 503. A SCIM demo reusing one e-mail address was // reported as a database outage, and the hunt started there instead of ending there. _fixture.Redb.UserProvider.CreateUserAsync(Arg.Any(), Arg.Any()) .ThrowsAsync(CreateDbException("SQLite Error 19: 'UNIQUE constraint failed: _users._email'.")); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageUsers, new CreateUserRequest { Login = "dup-user", Password = "P@ssw0rd!", DisplayName = "Duplicate User" }, new Dictionary { ["operation"] = "create" }); exchange.ExceptionHandled.Should().BeTrue(); var target = exchange.HasOut ? exchange.Out! : exchange.In; target.Headers["redbHttp.ResponseCode"].Should().Be(409, "a conflict is the caller's to fix; 503 invites a retry that can never succeed"); var body = (target.Body as Dictionary) ?? (exchange.In.Body as Dictionary); body.Should().NotBeNull(); body!["error"].Should().Be("duplicate"); var description = body["error_description"]!.ToString()!; description.Should().NotContain("temporarily unavailable"); description.Should().NotContain("_users._email", "the failing statement is not the caller's business"); } [Fact] public async Task TransientDbErrors_AreRetried_ButABoundedNumberOfTimes() { // The guard on the fix above. RetryWhile does not narrow MaximumRedeliveries, it REPLACES it: // the processor takes the predicate instead of the count check, inside a `while (true)` with no // outer bound. A predicate that only asked "is this not a unique violation?" would retry an // ordinary outage forever, which is a far worse failure than the 503 it set out to fix. var attempts = 0; _fixture.Redb.UserProvider.CreateUserAsync(Arg.Any(), Arg.Any()) .Returns(_ => { attempts++; throw CreateDbException("connection refused"); }); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageUsers, new CreateUserRequest { Login = "outage-user", Password = "P@ssw0rd!", DisplayName = "Outage User" }, new Dictionary { ["operation"] = "create" }); exchange.ExceptionHandled.Should().BeTrue(); var target = exchange.HasOut ? exchange.Out! : exchange.In; target.Headers["redbHttp.ResponseCode"].Should().Be(503, "a real outage is still transient"); // One first call plus at most three redeliveries. The number matters less than the fact that it // terminates at all: without a bound this test would never return. attempts.Should().BeGreaterThan(1, "a transient error is worth retrying"); attempts.Should().BeLessThanOrEqualTo(4, "and the retries must stop"); } private static DbException CreateDbException(string message) { return new TestDbException(message); } private sealed class TestDbException : DbException { public TestDbException(string message) : base(message) { } } } Path: redb-identity/tests/redb.Identity.Tests/Pipeline/EventPipelineTests.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/Pipeline/EventPipelineTests.cs ---- using AwesomeAssertions; using NSubstitute; using redb.Core.Models.Entities; using redb.Identity.Contracts.Applications; using redb.Identity.Contracts.Events; using redb.Identity.Contracts.Scopes; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Pipeline; /// /// Tests that WireTap event dispatch actually fires through the pipeline. /// Creates a second consumer on the Events endpoint to capture dispatched events. /// [Collection("IdentityRoute")] public class EventPipelineTests { private readonly IdentityRouteFixture _fixture; public EventPipelineTests(IdentityRouteFixture fixture) => _fixture = fixture; [Fact] public async Task CreateApp_WireTap_DispatchesClientRegisteredEvent() { MockRedbQuery.Setup(_fixture.Redb, new List>()); _fixture.Redb.SaveAsync(Arg.Any>()) .Returns(ci => { ci.Arg>().Id = 200; return 200L; }); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, new CreateApplicationRequest { ClientId = "event-test-app", ClientSecret = "secret", ClientType = "confidential" }, new Dictionary { ["operation"] = "create" }); exchange.Exception.Should().BeNull(); // The WireTap copies exchange properties to the event route. // Verify the original exchange has the event metadata set by the processor. exchange.Properties.Should().ContainKey("identity-event-type"); exchange.Properties["identity-event-type"].Should().Be("ClientRegistered"); } [Fact] public async Task CreateScope_WireTap_DispatchesScopeCreatedEvent() { MockRedbQuery.Setup(_fixture.Redb, new List>()); _fixture.Redb.SaveAsync(Arg.Any>()) .Returns(ci => { ci.Arg>().Id = 201; return 201L; }); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageScopes, new CreateScopeRequest { Name = "event-scope", DisplayName = "Event Scope" }, new Dictionary { ["operation"] = "create" }); exchange.Exception.Should().BeNull(); exchange.Properties.Should().ContainKey("identity-event-type"); exchange.Properties["identity-event-type"].Should().Be("ScopeCreated"); } [Fact] public async Task TokenIssuance_Success_DispatchesTokenIssuedEvent() { var body = new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "event-token-client", ["client_secret"] = "secret" }; var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.Token, body, new Dictionary()); exchange.Exception.Should().BeNull(); var dict = exchange.In.Body.Should().BeOfType>().Subject; dict.Should().ContainKey("access_token"); // TokenEndpointProcessor sets event on success exchange.Properties.Should().ContainKey("identity-event-type"); exchange.Properties["identity-event-type"].Should().Be("TokenIssued"); } [Fact] public async Task TokenIssuance_Failure_DoesNotDispatchEvent() { var body = new Dictionary { ["grant_type"] = "client_credentials" // missing client_id → will fail }; var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.Token, body, new Dictionary()); // On error, TokenEndpointProcessor should NOT set event (fix #5) exchange.Properties.Should().NotContainKey("identity-event-type"); } [Fact] public async Task DeleteApp_WireTap_DispatchesClientDeletedEvent() { // The delete looks the record up first; it exists and is of this resource. _fixture.Redb.LoadAsync(300).Returns(new RedbObject(new ApplicationProps()) { id = 300 }); _fixture.Redb.DeleteAsync(300).Returns(true); // The delete revokes the client's tokens first; this client has none. MockRedbQuery.Setup(_fixture.Redb, new List>()); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageApps, new Dictionary { ["id"] = 300L }, new Dictionary { ["operation"] = "delete" }); exchange.Exception.Should().BeNull(); exchange.Properties.Should().ContainKey("identity-event-type"); exchange.Properties["identity-event-type"].Should().Be("ClientDeleted"); } } Path: redb-identity/tests/redb.Identity.Tests/Pipeline/IntrospectionRevocationPipelineTests.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/Pipeline/IntrospectionRevocationPipelineTests.cs ---- using AwesomeAssertions; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Pipeline; /// /// Introspection and Revocation endpoints through the full route pipeline. /// Exercises: DoTry/DoCatch (introspection), WireTap (revocation), error handling. /// [Collection("IdentityRoute")] public class IntrospectionRevocationPipelineTests { private readonly IdentityRouteFixture _fixture; public IntrospectionRevocationPipelineTests(IdentityRouteFixture fixture) => _fixture = fixture; // ── Helpers ── private async Task ObtainAccessToken() { var body = new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "introspect-client", ["client_secret"] = "introspect-secret" }; var result = await _fixture.Request(IdentityEndpoints.Token, body); var dict = (Dictionary)result!; return dict["access_token"]!.ToString()!; } /// /// Extracts the response dictionary from the exchange. /// The processor writes to Out.Body; after pipeline merge it may end up in In.Body. /// private static Dictionary GetResponseBody(Exchange exchange) { // Out.Body is the canonical location the processor writes to if (exchange.Out?.Body is Dictionary outDict) return outDict; // After In/Out merge, result may be in In.Body if (exchange.In.Body is Dictionary inDict) return inDict; throw new InvalidOperationException( $"No Dict found. In.Body={exchange.In.Body?.GetType()}, Out.Body={exchange.Out?.Body?.GetType()}"); } // ── Introspection pipeline tests ── [Fact] public async Task Introspect_ValidToken_ThroughPipeline_ReturnsActive() { var token = await ObtainAccessToken(); var body = new Dictionary { ["token"] = token }; var headers = new Dictionary { ["Authorization"] = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("introspect-client:introspect-secret")) }; var exchange = await _fixture.RequestWithHeaders(IdentityEndpoints.Introspect, body, headers); var dict = GetResponseBody(exchange); dict.Should().ContainKey("active"); dict["active"].Should().Be(true); } [Fact] public async Task Introspect_InvalidToken_ThroughPipeline_ReturnsError() { var body = new Dictionary { ["token"] = "completely-invalid-jwt-garbage" }; var headers = new Dictionary { ["Authorization"] = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("test-client:test-secret")) }; var exchange = await _fixture.RequestWithHeaders(IdentityEndpoints.Introspect, body, headers); // OpenIddict returns an error for completely invalid tokens (not parseable JWT) var dict = GetResponseBody(exchange); dict.Should().ContainKey("error"); } [Fact] public async Task Introspect_MissingToken_ThroughPipeline_ReturnsInvalidRequest() { var body = new Dictionary(); var headers = new Dictionary { ["Authorization"] = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("test-client:test-secret")) }; var exchange = await _fixture.RequestWithHeaders(IdentityEndpoints.Introspect, body, headers); var dict = GetResponseBody(exchange); dict.Should().ContainKey("error"); dict["error"].Should().Be("invalid_request"); } // ── Revocation pipeline tests ── [Fact] public async Task Revoke_ValidToken_ThroughPipeline_ReturnsSuccess() { var token = await ObtainAccessToken(); var body = new Dictionary { ["token"] = token }; var headers = new Dictionary { ["Authorization"] = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("introspect-client:introspect-secret")) }; var exchange = await _fixture.RequestWithHeaders(IdentityEndpoints.Revoke, body, headers); // RFC 7009: successful revocation returns 200 with no error var dict = GetResponseBody(exchange); dict.Should().NotContainKey("error", "revocation should not return an error for a valid token"); } [Fact] public async Task Revoke_InvalidToken_ThroughPipeline_Succeeds() { // RFC 7009 §2.1: invalid/unknown token → still 200 var body = new Dictionary { ["token"] = "not-a-real-token" }; var headers = new Dictionary { ["Authorization"] = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("test-client:test-secret")) }; var exchange = await _fixture.RequestWithHeaders(IdentityEndpoints.Revoke, body, headers); // Should not throw — pipeline handles it gracefully exchange.Exception.Should().BeNull("revocation of invalid token should not throw"); } [Fact] public async Task Revoke_MissingToken_ThroughPipeline_ReturnsError() { var body = new Dictionary(); var headers = new Dictionary { ["Authorization"] = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("test-client:test-secret")) }; var exchange = await _fixture.RequestWithHeaders(IdentityEndpoints.Revoke, body, headers); var dict = GetResponseBody(exchange); dict.Should().ContainKey("error"); dict["error"].Should().Be("invalid_request"); } } Path: redb-identity/tests/redb.Identity.Tests/Pipeline/RouteTransactionMarkingTests.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/Pipeline/RouteTransactionMarkingTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NSubstitute; using OpenIddict.Server; using redb.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Route.Abstractions; using Xunit; using static OpenIddict.Server.OpenIddictServerEvents; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Pipeline; /// /// G6 / E1 — verifies the route-level IsTransacted bit at definition time. /// The bit is set by WithRedbTx / WithIdempotentTx(wrapInRedbTx:true) /// in and is what guarantees rollback of /// partial writes when a mid-pipeline exception fires. /// /// As of commit 02d408a7 the mutation routes split into two architectural classes: /// /// /// /// Still transacted (). /// The processor body writes through the per-exchange IRedbService that /// WithRedbTx wraps — atomicity is real and load-bearing, e.g. Logout /// revokes session + tokens in one route-level tx; Manage* CRUD writes multi-row /// mutations against the same connection the wrap covers. /// /// /// No longer transacted (). /// The processor's primary writers run through a DI-scoped store /// (OpenIddict managers like RedbApplicationStore / RedbTokenStore, /// or _sp.GetService<IPasswordHistoryStore>() et al.) that resolves /// its own IRedbService on a separate DI scope. The route-level wrap /// covered a different connection from the one doing the actual write; on SQLite /// this held the writer lock during Argon2id + the OpenIddict pipeline (~30s) /// while the store's separate connection raced against it on the same file, with /// 5s busy_timeout × ~7 retries surfacing as 34-second test latencies. The wrap /// was removed because its atomicity guarantee was already false. The proper fix /// for these flows is for those stores to share the per-exchange IRedbService /// (separate refactor); the assert below pins the current architecture so the /// wrap doesn't get silently re-added and bring the 34-second self-deadlock back. /// /// /// public sealed class RouteTransactionMarkingTests { private readonly IdentityCoreRouteBuilder _builder; public RouteTransactionMarkingTests() { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); // Critical: WithRedbTx is a no-op when RedbInstanceName is null. Production // bootstraps via AddRedbIdentityServer always populates this; mimic that here // so the assertions below test the production code path, not the dev fallback. services.AddSingleton(Options.Create(new RedbIdentityOptions { RedbInstanceName = "identity-test" })); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddOpenIddict() .AddServer(options => { options.EnableDegradedMode(); options.SetIssuer(new Uri("https://identity.test.local/")); options.SetTokenEndpointUris("/connect/token"); options.AllowClientCredentialsFlow(); options.AddEphemeralEncryptionKey(); options.AddEphemeralSigningKey(); options.DisableAccessTokenEncryption(); options.UseRedbRoute(); options.AddEventHandler(builder => builder.UseInlineHandler(_ => default) .SetOrder(int.MaxValue - 100_000).Build()); }); var sp = services.BuildServiceProvider(); _builder = new IdentityCoreRouteBuilder(sp, sp.GetRequiredService>()); ((IRouteBuilder)_builder).Configure(null!); } public static IEnumerable MutatingRouteIds_StillTransacted() => new[] { // OAuth/OIDC protocol routes whose primary writers go through the per-exchange // IRedbService that WithRedbTx wraps: new object[] { IdentityEndpoints.RouteIds.Logout }, // revokes session + tokens via _context's redb in one tx new object[] { IdentityEndpoints.RouteIds.ConsentGrant }, // grants consent through the per-exchange redb // Token — RESTORED. It was in the no-longer-transacted list below because the OpenIddict // stores resolved their IRedbService from Identity's child container, which opened a host // scope of its OWN per DI scope: a SECOND connection. The route wrap therefore covered a // different connection from the one doing the writes (no atomicity), and that second // connection deadlocked against the row locks the first one held. // // Fixed at the root: HostRedbScope now binds IRedbService to the exchange's instance (see // IdentityExchangeAccessor), so the stores write on the SAME connection the transaction was // opened on. One connection, one transaction, the stores enlisted in it — and the token // entry plus the authorization entry now either both land or neither does. new object[] { IdentityEndpoints.RouteIds.Token }, // Management mutation endpoints — wrapped via WithIdempotentTx(wrapInRedbTx:true): new object[] { IdentityEndpoints.RouteIds.ManageScopes }, new object[] { IdentityEndpoints.RouteIds.ManageUsers }, new object[] { IdentityEndpoints.RouteIds.ManageTokens }, new object[] { IdentityEndpoints.RouteIds.ManageGroups }, new object[] { IdentityEndpoints.RouteIds.ManageConsents }, new object[] { IdentityEndpoints.RouteIds.ManageSessions }, }; public static IEnumerable MutatingRouteIds_NoLongerTransacted() => new[] { // Routes whose primary writers run through a store that opens its OWN DI scope from the // inside (PropsPasswordHistoryStore, ISigningKeyStore, FederationCallbackProcessor, …) and // therefore resolves its own IRedbService on a separate connection. The route-level wrap // would cover a different connection from the one doing the writes, and on SQLite that // produced ~34-second self-deadlocks (5 s busy_timeout × ~7 retries). Removed in 02d408a7. // // NOTE: Token has MOVED to the transacted list above. Its root cause was different — the // second connection came from HostRedbScope in the child container, not from a store calling // CreateScope() on itself — and that is now fixed (IdentityExchangeAccessor binds the child // scope's IRedbService to the exchange). The routes still listed here need the same // treatment: thread the exchange's IRedbService into those stores instead of letting them // open a scope. That is the remaining cleanup. new object[] { IdentityEndpoints.RouteIds.Authorize }, new object[] { IdentityEndpoints.RouteIds.Revoke }, new object[] { IdentityEndpoints.RouteIds.Login }, new object[] { IdentityEndpoints.RouteIds.MfaVerify }, new object[] { IdentityEndpoints.RouteIds.MfaRecovery }, new object[] { IdentityEndpoints.RouteIds.MfaManage }, new object[] { IdentityEndpoints.RouteIds.ManageApps }, }; [Theory] [MemberData(nameof(MutatingRouteIds_StillTransacted))] public void MutatingRoute_IsTransacted(string routeId) { var route = _builder.Definitions.FirstOrDefault(d => d.GetRouteId() == routeId); route.Should().NotBeNull("route '{0}' must be registered", routeId); route!.IsTransacted.Should().BeTrue( "E1: route '{0}' performs multi-row writes (auth, token, session, consent, " + "or admin mutation) and must run inside a redb transaction so that any " + "exception thrown after partial writes triggers rollback. WithRedbTx wires " + "this in IdentityCoreRouteBuilder; if a refactor drops it the route will " + "leak orphan rows on failure (per SPRINT-E/E1 spec).", routeId); } [Theory] [MemberData(nameof(MutatingRouteIds_NoLongerTransacted))] public void MutatingRoute_NoLongerTransacted(string routeId) { var route = _builder.Definitions.FirstOrDefault(d => d.GetRouteId() == routeId); route.Should().NotBeNull("route '{0}' must be registered", routeId); route!.IsTransacted.Should().BeFalse( "Route '{0}' had WithRedbTx removed in commit 02d408a7: its primary writers are stores " + "that open their OWN DI scope from the inside (PropsPasswordHistoryStore, " + "ISigningKeyStore, FederationCallbackProcessor, …) and so write on a second connection. " + "A route-level wrap would cover a different connection from the one doing the writes — " + "no atomicity — and the second connection then deadlocks against the row locks the " + "first one holds (~34 s on SQLite: 5 s busy_timeout × OnException retries). " + "Do NOT simply reinstate the wrap to make this assert pass: fix the root cause first, " + "the way Token was fixed — thread the exchange's IRedbService into those stores instead " + "of letting them call CreateScope().", routeId); } [Fact] public void ReadOnlyDiscoveryRoutes_AreNotTransacted() { // Discovery / JWKS / userinfo / introspect are pure reads — wrapping them in // a tx adds latency and connection contention without correctness benefit. // If somebody accidentally bolted Transacted() onto them, JWKS/discovery // would start contending for write transactions on the redb pool. var readOnlyIds = new[] { IdentityEndpoints.RouteIds.Discovery, IdentityEndpoints.RouteIds.Jwks, IdentityEndpoints.RouteIds.Userinfo, IdentityEndpoints.RouteIds.Introspect, IdentityEndpoints.RouteIds.MfaListMethods, }; foreach (var id in readOnlyIds) { var route = _builder.Definitions.FirstOrDefault(d => d.GetRouteId() == id); if (route is null) continue; // route is conditionally registered — skip route.IsTransacted.Should().BeFalse( "read-only route '{0}' must NOT carry a transaction wrapper — it would add " + "contention without atomicity benefit", id); } } } Path: redb-identity/tests/redb.Identity.Tests/Pipeline/TokenPipelineTests.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/Pipeline/TokenPipelineTests.cs ---- using AwesomeAssertions; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Pipeline; /// /// Token endpoint tests through the full route pipeline. /// Unlike unit tests, these exercise: throttle → processor → WireTap → event dispatch. /// [Collection("IdentityRoute")] public class TokenPipelineTests { private readonly IdentityRouteFixture _fixture; public TokenPipelineTests(IdentityRouteFixture fixture) => _fixture = fixture; [Fact] public async Task ClientCredentials_ThroughPipeline_ReturnsAccessToken() { var body = new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = "pipeline-client", ["client_secret"] = "pipeline-secret" }; var result = await _fixture.Request(IdentityEndpoints.Token, body); result.Should().NotBeNull(); var dict = result.Should().BeOfType>().Subject; dict.Should().ContainKey("access_token"); dict["token_type"].Should().Be("Bearer"); dict["expires_in"].Should().NotBeNull(); } [Fact] public async Task ClientCredentials_WithHeaders_ReturnsAccessToken() { var body = new Dictionary { ["grant_type"] = "client_credentials" }; var credentials = Convert.ToBase64String( System.Text.Encoding.UTF8.GetBytes("basic-client:basic-secret")); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.Token, body, new Dictionary { ["Authorization"] = $"Basic {credentials}" }); exchange.In.Body.Should().NotBeNull(); var dict = exchange.In.Body.Should().BeOfType>().Subject; dict.Should().ContainKey("access_token"); } [Fact] public async Task InvalidGrant_ThroughPipeline_ReturnsOAuthError() { var body = new Dictionary { ["grant_type"] = "client_credentials" // missing client_id → OpenIddict returns invalid_request }; var result = await _fixture.Request(IdentityEndpoints.Token, body); result.Should().NotBeNull(); var dict = result.Should().BeOfType>().Subject; dict.Should().ContainKey("error"); } [Fact] public async Task Token_MultipleCalls_ThrottleDoesNotBlock() { // Fixture has relaxed throttle (100/s). Verify multiple calls succeed. for (int i = 0; i < 5; i++) { var body = new Dictionary { ["grant_type"] = "client_credentials", ["client_id"] = $"throttle-client-{i}", ["client_secret"] = "secret" }; var result = await _fixture.Request(IdentityEndpoints.Token, body); result.Should().NotBeNull(); } } } Path: redb-identity/tests/redb.Identity.Tests/Pipeline/UserManagementPipelineTests.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/Pipeline/UserManagementPipelineTests.cs ---- using redb.Identity.Contracts.Common; using AwesomeAssertions; using NSubstitute; using NSubstitute.ExceptionExtensions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Identity.Contracts.Users; using redb.Identity.Core.Models; using redb.Identity.Contracts.Routes; using redb.Identity.Tests.Infrastructure; using Xunit; using CoreCreateUserRequest = redb.Core.Models.Users.CreateUserRequest; namespace redb.Identity.Tests.Pipeline; /// /// User management through the full route pipeline including WireTap event dispatch. /// [Collection("IdentityRoute")] public class UserManagementPipelineTests { private readonly IdentityRouteFixture _fixture; public UserManagementPipelineTests(IdentityRouteFixture fixture) => _fixture = fixture; private static IRedbUser MockUser(long id, string login, bool enabled = true, string? name = null) { var user = NSubstitute.Substitute.For(); user.Id.Returns(id); user.Login.Returns(login); user.Name.Returns(name ?? login); user.Enabled.Returns(enabled); user.DateRegister.Returns(DateTimeOffset.UtcNow); return user; } [Fact] public async Task CreateUser_ThroughPipeline_ReturnsUserResponse() { var coreUser = MockUser(10, "pipeline-user", name: "Pipeline User"); _fixture.Redb.UserProvider.CreateUserAsync(Arg.Any(), Arg.Any()) .Returns(coreUser); _fixture.Redb.SaveAsync(Arg.Any>()).Returns(100L); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageUsers, new CreateUserRequest { Login = "pipeline-user", Password = "P@ssw0rd!", DisplayName = "Pipeline User" }, new Dictionary { ["operation"] = "create" }); exchange.Exception.Should().BeNull(); var resp = exchange.In.Body.Should().BeOfType().Subject; resp.Login.Should().Be("pipeline-user"); } [Fact] public async Task CreateUser_PasswordDelegatedToCore() { var coreUser = MockUser(11, "hash-test"); _fixture.Redb.UserProvider.CreateUserAsync(Arg.Any(), Arg.Any()) .Returns(coreUser); _fixture.Redb.SaveAsync(Arg.Any>()).Returns(100L); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageUsers, new CreateUserRequest { Login = "hash-test", Password = "secret123" }, new Dictionary { ["operation"] = "create" }); exchange.Exception.Should().BeNull(); // Verify password was passed to Core provider (which handles hashing) await _fixture.Redb.UserProvider.Received(1).CreateUserAsync( Arg.Is(r => r.Password == "secret123"), Arg.Any()); } [Fact] public async Task CreateUser_MissingLogin_ReturnsValidationError() { var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageUsers, new CreateUserRequest { Login = "", Password = "pass1234" }, new Dictionary { ["operation"] = "create" }); exchange.Exception.Should().BeNull(); var body = exchange.In.Body.Should().BeOfType().Subject; body.Error.Should().Be("validation_error"); } [Fact] public async Task ChangePassword_ThroughPipeline_Works() { var coreUser = MockUser(20, "pwd-user"); _fixture.Redb.UserProvider.GetUserByIdAsync(20).Returns(coreUser); _fixture.Redb.UserProvider.ChangePasswordAsync(coreUser, "old-pass", "new-pass", Arg.Any()) .Returns(true); // C7: ChangePassword now triggers SessionService.LogoutAsync — stub session/auth // queries with empty in-memory lists so the mock chain doesn't NRE. MockRedbQuery.Setup(_fixture.Redb, new List>()); MockRedbQuery.Setup(_fixture.Redb, new List>()); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageUsers, new ChangePasswordRequest { Id = 20, OldPassword = "old-pass", NewPassword = "new-pass" }, new Dictionary { ["operation"] = "change-password" }); exchange.Exception.Should().BeNull(); var body = exchange.In.Body.Should().BeOfType().Subject; body.Success.Should().BeTrue(); } [Fact] public async Task ChangePassword_WrongOldPassword_ReturnsError() { var coreUser = MockUser(21, "pwd-user2"); _fixture.Redb.UserProvider.GetUserByIdAsync(21).Returns(coreUser); _fixture.Redb.UserProvider.ChangePasswordAsync(coreUser, "wrong-pass", "new-pass", Arg.Any()) .Returns(false); var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageUsers, new ChangePasswordRequest { Id = 21, OldPassword = "wrong-pass", NewPassword = "new-pass" }, new Dictionary { ["operation"] = "change-password" }); exchange.Exception.Should().BeNull(); var body = exchange.In.Body.Should().BeOfType().Subject; body.Error.Should().Be("invalid_password"); } [Fact] public async Task MissingOperationHeader_ThroughPipeline_ErrorHandled() { // No "operation" header → processor throws InvalidOperationException → caught by OnException var exchange = await _fixture.RequestWithHeaders( IdentityEndpoints.ManageUsers, new CreateUserRequest { Login = "x", Password = "pass1234" }, new Dictionary()); // The builder-level OnException catches this and returns server_error var body = exchange.In.Body; body.Should().NotBeNull(); if (body is Dictionary dict) { dict.Should().ContainKey("error"); dict["error"].Should().Be("server_error"); } } } Path: redb-identity/tests/redb.Identity.Tests/Routes/AuthorizationCheckProcessorTests.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/Routes/AuthorizationCheckProcessorTests.cs ---- using System.Text.Json; using AwesomeAssertions; using redb.Identity.Contracts.Configuration; using redb.Route.Abstractions; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// F5 — the granular scope table, now that it lives in Core behind /// direct-vm://identity-authz-check and serves every transport. /// /// The table was moved verbatim, so these tests are written against the rules rather than against the /// move: each one states a decision the table has always made, and would fail if the move had shifted an /// ordering, dropped a branch, or reworded a refusal. The refusal wording is part of the contract — the /// HTTP negative matrix reads it, and quietly rewording it is how that net stops catching anything. /// /// public class AuthorizationCheckProcessorTests { [Fact] public async Task An_anonymous_route_is_not_checked_at_all() { var e = Request("/api/v1/identity/users", "read"); e.Properties["identity:management-anonymous"] = true; // Deliberately no scopes: an anonymous route is open by design, not open by accident. await Enforce(e); Allowed(e); } [Fact] public async Task The_master_scope_passes_everything() { var e = Request("/api/v1/identity/signing-keys", "write", IdentityScopes.Manage); await Enforce(e); Allowed(e); } [Fact] public async Task A_token_with_no_scopes_is_refused_even_though_it_authenticated() { // Authentication ran and left nothing behind. Defensive deny: the alternative is granting on the // strength of a bug elsewhere. var e = Request("/api/v1/identity/users", "read"); await Enforce(e); Refused(e, "Access token carries no scopes."); } // ── read-only admin ────────────────────────────────────── [Fact] public async Task Read_only_admin_may_read_any_surface() { var e = Request("/api/v1/identity/federation-providers", "read", IdentityScopes.ReadOnly); await Enforce(e); Allowed(e); } [Fact] public async Task Read_only_admin_may_not_write() { var e = Request("/api/v1/identity/federation-providers", "write", IdentityScopes.ReadOnly); await Enforce(e); Refused(e); } // ── the account branch ─────────────────────────────────── [Theory] [InlineData("/api/v1/identity/me/profile")] [InlineData("/api/v1/identity/account/verify-email")] [InlineData("/api/v1/identity/password/reset")] public async Task Self_service_paths_are_admitted_on_the_account_scope(string path) { // Admitted here, narrowed downstream: RequireSelfOrAdminProcessor is what keeps one account // holder out of another's data. var e = Request(path, "write", IdentityScopes.Account); await Enforce(e); Allowed(e); } [Fact] public async Task The_account_scope_does_not_reach_the_admin_surface() { var e = Request("/api/v1/identity/users", "read", IdentityScopes.Account); await Enforce(e); Refused(e); } // ── per-surface scopes ─────────────────────────────────── [Fact] public async Task A_surfaces_read_scope_admits_a_read() { var e = Request("/api/v1/identity/users/42", "read", IdentityScopes.UsersRead); await Enforce(e); Allowed(e); } [Fact] public async Task Write_implies_read_on_the_same_surface() { // RBAC convention: holding :write means a GET on that surface does not also require :read. var e = Request("/api/v1/identity/users/42", "read", IdentityScopes.UsersWrite); await Enforce(e); Allowed(e); } [Fact] public async Task Read_never_implies_write() { var e = Request("/api/v1/identity/users/42", "write", IdentityScopes.UsersRead); await Enforce(e); Refused(e, $"This endpoint requires the '{IdentityScopes.UsersWrite}' scope"); } [Fact] public async Task A_scope_for_another_surface_does_not_carry_over() { var e = Request("/api/v1/identity/groups", "read", IdentityScopes.UsersWrite); await Enforce(e); Refused(e, $"This endpoint requires the '{IdentityScopes.GroupsRead}' scope"); } [Fact] public async Task An_unmapped_surface_is_denied_by_default() { // Adding a management surface must not silently open it to any admin token that happens to exist. var e = Request("/api/v1/identity/something-brand-new", "read", IdentityScopes.UsersRead); await Enforce(e); Refused(e, "does not carry a scope authorising '/api/v1/identity/something-brand-new'"); } [Fact] public async Task Audit_is_read_only_by_construction() { // Its read and write slots hold the same scope, so a write cannot be granted separately. var e = Request("/api/v1/identity/audit", "write", IdentityScopes.AuditRead); await Enforce(e); Allowed(e, "the table maps audit's write slot to the read scope; nothing else grants it"); } // ── transport neutrality ───────────────────────────────── [Fact] public async Task A_caller_without_http_headers_states_resource_and_action_itself() { // What makes the endpoint reusable: no redbHttp.Path, no redbHttp.Method, same decision. var e = new Exchange(new Message(Array.Empty())); e.Properties["identity:management-scopes"] = new[] { IdentityScopes.UsersRead }; e.Properties["identity:authz-resource"] = "/api/v1/identity/users"; e.Properties["identity:authz-action"] = "write"; await Enforce(e); Refused(e, $"This endpoint requires the '{IdentityScopes.UsersWrite}' scope"); } [Fact] public async Task Http_headers_are_read_when_nothing_states_the_resource() { // The HTTP facade leans on this: its path is already the canonical identifier, and carrying it a // second time would let the two copies disagree. var e = new Exchange(new Message(Array.Empty())); e.In.Headers["redbHttp.Path"] = "/api/v1/identity/roles"; e.In.Headers["redbHttp.Method"] = "DELETE"; e.Properties["identity:management-scopes"] = new[] { IdentityScopes.RolesRead }; await Enforce(e); Refused(e, $"This endpoint requires the '{IdentityScopes.RolesWrite}' scope"); } // ── helpers ─────────────────────────────────────────────── private static Exchange Request(string resource, string action, params string[] scopes) { var e = new Exchange(new Message(Array.Empty())); e.Properties["identity:authz-resource"] = resource; e.Properties["identity:authz-action"] = action; if (scopes.Length > 0) e.Properties["identity:management-scopes"] = scopes; return e; } private static async Task Enforce(IExchange exchange) { var type = typeof(redb.Identity.Core.RedbIdentityServiceExtensions).Assembly .GetType("redb.Identity.Core.Routes.Processors.AuthorizationCheckProcessor")!; var processor = (IProcessor)Activator.CreateInstance(type, nonPublic: true)!; await processor.Process(exchange, CancellationToken.None); } private static void Allowed(IExchange e, string because = "") { e.HasOut.Should().BeFalse(because.Length > 0 ? because : "an allowed call writes no refusal"); e.IsStopped.Should().BeFalse(); } private static void Refused(IExchange e, string detailContains = "") { e.HasOut.Should().BeTrue("a refusal must be written, not implied"); e.Out!.Headers["redbHttp.ResponseCode"].Should().Be(403); e.IsStopped.Should().BeTrue("the request must not reach the controller"); var body = JsonSerializer.Deserialize((byte[])e.Out.Body!); body.GetProperty("error").GetString().Should().Be("insufficient_scope"); if (detailContains.Length > 0) { body.GetProperty("error_description").GetString() .Should().Contain(detailContains, "the wording is part of the contract the HTTP matrix reads"); } } } Path: redb-identity/tests/redb.Identity.Tests/Routes/BearerParsingD6Tests.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/Routes/BearerParsingD6Tests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Routes.Processors; using Xunit; namespace redb.Identity.Tests.Routes; /// /// D6 — Bearer token parsing per RFC 6750 §2.1 + RFC 7230 §3.2.4. /// Verifies case-insensitive scheme matching and tolerance of multiple /// whitespace characters between the scheme name and the token68 value. /// public class BearerParsingD6Tests { [Theory] [InlineData("Bearer abc", "abc")] [InlineData("bearer abc", "abc")] [InlineData("BEARER abc", "abc")] [InlineData("BeArEr abc", "abc")] [InlineData("Bearer abc", "abc")] // multiple SP per RFC 7230 OWS [InlineData("Bearer\tabc", "abc")] // HTAB allowed in OWS [InlineData(" Bearer abc ", "abc")] public void TryExtractBearerToken_AcceptsValidVariants(string header, string expected) { ManagementBearerAuthProcessor.TryExtractBearerToken(header).Should().Be(expected); } [Theory] [InlineData("Basic dXNlcjpwYXNz")] [InlineData("Bearerabc")] // no separator — must be rejected [InlineData("Token abc")] [InlineData("")] [InlineData(null)] public void TryExtractBearerToken_RejectsNonBearerOrMalformed(string? header) { ManagementBearerAuthProcessor.TryExtractBearerToken(header).Should().BeNull(); } [Fact] public void TryExtractBearerToken_EmptyTokenRecognised() { // "Bearer " with no token still parses to empty string — caller turns this // into a 401 invalid_token response per RFC 6750 §3.1. ManagementBearerAuthProcessor.TryExtractBearerToken("Bearer ").Should().Be(string.Empty); ManagementBearerAuthProcessor.TryExtractBearerToken("Bearer ").Should().Be(string.Empty); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/LoginFailureRecorderProcessorTests.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/Routes/LoginFailureRecorderProcessorTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using redb.Identity.Core.Configuration; using redb.Identity.Core.Routes.Processors; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// C1 — Verifies that increments the per-IP+ /// username failure bucket on bad logins, resets it on success, and emits HTTP 429 once /// the configured ceiling is reached. /// public sealed class LoginFailureRecorderProcessorTests { private static IExchange MakeExchange(string ip, string username, bool success) { var msg = new Message { Body = new Dictionary { ["username"] = username } }; msg.Headers["redbHttp.RemoteAddress"] = ip; var ex = new Exchange(msg) { Pattern = ExchangePattern.InOut }; ex.Out = new Message { Body = new Dictionary { ["success"] = success } }; return ex; } private static IServiceProvider BuildSp(RateLimitOptions rl, IRateLimitStore store) { var opts = new RedbIdentityOptions { RateLimit = rl }; var sc = new ServiceCollection(); sc.AddSingleton(store); sc.AddSingleton>(Options.Create(opts)); return sc.BuildServiceProvider(); } [Fact] public async Task SuccessfulLogin_ResetsBucket() { var rl = new RateLimitOptions { Enabled = true, PerIpUsernameFailures = 3, PerIpUsernameWindow = TimeSpan.FromMinutes(15) }; using var store = new InMemoryRateLimitStore(); var sp = BuildSp(rl, store); var p = new LoginFailureRecorderProcessor(sp); // Pre-fill 2 failures for "alice" from 1.1.1.1 await p.Process(MakeExchange("1.1.1.1", "alice", success: false)); await p.Process(MakeExchange("1.1.1.1", "alice", success: false)); // Successful login should reset. await p.Process(MakeExchange("1.1.1.1", "alice", success: true)); // Three more failures should still be allowed (bucket reset). for (int i = 0; i < 3; i++) { var ex = MakeExchange("1.1.1.1", "alice", success: false); await p.Process(ex); // Below ceiling (3) → outBody untouched, success still false (the original). (ex.Out!.Body as IDictionary)!["success"].Should().Be(false); } } [Fact] public async Task BreachingCeiling_Emits429() { var rl = new RateLimitOptions { Enabled = true, PerIpUsernameFailures = 2, PerIpUsernameWindow = TimeSpan.FromMinutes(15), DefaultRetryAfterSeconds = 30 }; using var store = new InMemoryRateLimitStore(); var sp = BuildSp(rl, store); var p = new LoginFailureRecorderProcessor(sp); await p.Process(MakeExchange("1.1.1.1", "alice", success: false)); await p.Process(MakeExchange("1.1.1.1", "alice", success: false)); var breach = MakeExchange("1.1.1.1", "alice", success: false); await p.Process(breach); breach.Out!.Headers["redbHttp.ResponseCode"].Should().Be(429); var body = breach.Out.Body as IDictionary; body!["error"].Should().Be("rate_limited"); breach.Exception.Should().BeOfType(); } [Fact] public async Task DifferentUsername_HasIndependentBucket() { var rl = new RateLimitOptions { Enabled = true, PerIpUsernameFailures = 2, PerIpUsernameWindow = TimeSpan.FromMinutes(15) }; using var store = new InMemoryRateLimitStore(); var sp = BuildSp(rl, store); var p = new LoginFailureRecorderProcessor(sp); await p.Process(MakeExchange("1.1.1.1", "alice", success: false)); await p.Process(MakeExchange("1.1.1.1", "alice", success: false)); // bob from same IP must not be blocked by alice's bucket. var bob = MakeExchange("1.1.1.1", "bob", success: false); await p.Process(bob); bob.Out!.Headers.ContainsKey("Retry-After").Should().BeFalse(); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MeConsentsProcessorTests.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/Routes/MeConsentsProcessorTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Routes.Processors; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// H3 (v1.0 DoD §6) unit tests for . Covers the /// token-subject precondition paths which reject before any /// access, so no DB or service wiring is required. /// Happy-path list + revoke flows (incl. ownership and 404-on-unknown-clientId) /// live in the integration suite. /// public sealed class MeConsentsProcessorTests { private static Exchange BuildExchange(long? userId, string operation, object? body = null) { var ex = new Exchange(new Message { Body = body ?? new Dictionary() }); ex.In.Headers["operation"] = operation; if (userId is not null) ex.Properties["identity:management-user-id"] = userId.Value; return ex; } [Fact] public async Task MissingSubject_List_Returns401() { var sut = new MeConsentsProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: null, operation: "list"); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); ex.IsStopped.Should().BeTrue(); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("invalid_token"); } [Fact] public async Task MissingSubject_Revoke_Returns401() { var sut = new MeConsentsProcessor(context: null!, redbName: null); var ex = BuildExchange( userId: null, operation: "revoke", body: new Dictionary { ["clientId"] = "demo-client" }); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); } [Fact] public async Task NonPositiveSubject_Returns401() { var sut = new MeConsentsProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: 0, operation: "list"); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); } [Fact] public async Task Grant_MissingSubject_Returns401() { var sut = new MeConsentsProcessor(context: null!, redbName: null); var ex = BuildExchange( userId: null, operation: "grant", body: new Dictionary { ["clientId"] = "demo-client", ["scopes"] = new[] { "openid" }, }); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); } [Fact] public async Task Grant_MissingClientId_Returns400() { var sut = new MeConsentsProcessor(context: null!, redbName: null); var ex = BuildExchange( userId: 42, operation: "grant", body: new Dictionary { ["clientId"] = " ", ["scopes"] = new[] { "openid" }, }); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("validation_error"); } [Fact] public async Task Grant_MissingScopes_Returns400() { var sut = new MeConsentsProcessor(context: null!, redbName: null); var ex = BuildExchange( userId: 42, operation: "grant", body: new Dictionary { ["clientId"] = "demo-client", ["scopes"] = Array.Empty(), }); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("validation_error"); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MeMfaProcessorTests.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/Routes/MeMfaProcessorTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Routes.Processors; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// H3 (v1.0 DoD §6) unit tests for . Covers the /// caller-id precondition paths which reject before the /// scope is created, so no DI wiring is required. /// Happy-path setup/confirm/disable/regenerate flows live in the integration suite /// where a real is wired. /// public sealed class MeMfaProcessorTests { private static Exchange BuildExchange(long? userId, string operation) { var ex = new Exchange(new Message { Body = new Dictionary() }); ex.In.Headers["operation"] = operation; if (userId is not null) ex.Properties["identity:management-user-id"] = userId.Value; return ex; } [Fact] public async Task MissingSubject_Returns401() { var sut = new MeMfaProcessor(sp: null!); var ex = BuildExchange(userId: null, operation: "status"); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); ex.IsStopped.Should().BeTrue(); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("invalid_token"); } [Fact] public async Task NonPositiveSubject_Returns401() { var sut = new MeMfaProcessor(sp: null!); var ex = BuildExchange(userId: 0, operation: "setup"); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MePasswordProcessorTests.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/Routes/MePasswordProcessorTests.cs ---- using AwesomeAssertions; using redb.Identity.Contracts.Users; using redb.Identity.Core.Routes.Processors; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// H3 (v1.0 DoD §6) unit tests for . Covers the /// caller-id and request-body precondition paths which reject before /// any access, so no DB or service wiring is required. /// Happy-path change + session-revocation flow lives in the integration suite. /// public sealed class MePasswordProcessorTests { private static Exchange BuildExchange(long? userId, object? body) { var ex = new Exchange(new Message { Body = body }); ex.In.Headers["operation"] = "change"; if (userId is not null) ex.Properties["identity:management-user-id"] = userId.Value; return ex; } [Fact] public async Task MissingSubject_Returns401() { var sut = new MePasswordProcessor(context: null!, redbName: null); var ex = BuildExchange( userId: null, body: new MeChangePasswordRequest { OldPassword = "old-pass-123", NewPassword = "new-pass-456" }); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); ex.IsStopped.Should().BeTrue(); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("invalid_token"); } [Fact] public async Task InvalidBodyType_Returns400_ValidationError() { var sut = new MePasswordProcessor(context: null!, redbName: null); // Body is a generic dict, not MeChangePasswordRequest — must be rejected. var ex = BuildExchange(userId: 42, body: new Dictionary()); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("validation_error"); } [Fact] public async Task EmptyOldPassword_Returns400() { var sut = new MePasswordProcessor(context: null!, redbName: null); var ex = BuildExchange( userId: 42, body: new MeChangePasswordRequest { OldPassword = "", NewPassword = "new-pass-456" }); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("validation_error"); body["error_description"].Should().Be("OldPassword is required"); } [Fact] public async Task WeakNewPassword_Returns400() { var sut = new MePasswordProcessor(context: null!, redbName: null); var ex = BuildExchange( userId: 42, body: new MeChangePasswordRequest { OldPassword = "old-pass-123", NewPassword = "x" }); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("validation_error"); ((string)body["error_description"]!).Should().Contain("NewPassword"); } [Fact] public async Task SameOldAndNewPassword_Returns400() { var sut = new MePasswordProcessor(context: null!, redbName: null); var ex = BuildExchange( userId: 42, body: new MeChangePasswordRequest { OldPassword = "same-pass-123", NewPassword = "same-pass-123" }); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("validation_error"); ((string)body["error_description"]!).Should().Contain("differ"); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MeProfileProcessorTests.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/Routes/MeProfileProcessorTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Routes.Processors; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// H3 (v1.0 DoD §6) unit tests for . Covers the /// caller-id precondition paths (missing / non-positive) which reject before /// any access, so no DB or service wiring is required. /// Happy-path read/update flows live in the integration suite. /// public sealed class MeProfileProcessorTests { private static Exchange BuildExchange(long? userId, string operation, object? body = null) { var ex = new Exchange(new Message { Body = body ?? new Dictionary() }); ex.In.Headers["operation"] = operation; if (userId is not null) ex.Properties["identity:management-user-id"] = userId.Value; return ex; } [Fact] public async Task MissingSubject_Returns401() { var sut = new MeProfileProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: null, operation: "read"); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); ex.IsStopped.Should().BeTrue(); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("invalid_token"); } [Fact] public async Task NonPositiveSubject_Returns401() { var sut = new MeProfileProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: 0, operation: "update"); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); } [Fact] public async Task NegativeSubject_Returns401() { var sut = new MeProfileProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: -7, operation: "read"); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MeSessionsProcessorTests.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/Routes/MeSessionsProcessorTests.cs ---- using AwesomeAssertions; using redb.Identity.Contracts.Common; using redb.Identity.Core.Routes.Processors; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// H3-SSO unit tests for . Covers the caller-id /// precondition paths (missing / non-positive) which reject before /// touching any redb service, so no DB or IRouteContext is required. /// Full happy-path list/revoke and ownership-mismatch flows are covered by the /// integration suite where a real service is wired. /// public sealed class MeSessionsProcessorTests { private static Exchange BuildExchange(long? userId, string operation) { var ex = new Exchange(new Message { Body = new Dictionary() }); ex.In.Headers["operation"] = operation; if (userId is not null) ex.Properties["identity:management-user-id"] = userId.Value; return ex; } [Fact] public async Task MissingSubject_Returns401() { // IRouteContext is not reached — the subject check short-circuits first. var sut = new MeSessionsProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: null, operation: "list"); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); ex.IsStopped.Should().BeTrue(); ex.Out.Body.Should().BeOfType().Subject.Error.Should().Be("invalid_token"); } [Fact] public async Task NonPositiveSubject_Returns401() { var sut = new MeSessionsProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: 0, operation: "list"); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); } [Fact] public async Task RevokeCurrent_MissingSidClaim_Returns400_SidUnavailable() { // Caller is authenticated (subject present) but the token has no sid claim // (e.g. client_credentials grant). revoke-current is inapplicable → 400. var sut = new MeSessionsProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: 42, operation: "revoke-current"); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); ex.Out.Body.Should().BeOfType().Subject.Error.Should().Be("sid_unavailable"); } [Fact] public async Task RevokeCurrent_NonNumericSid_Returns400() { var sut = new MeSessionsProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: 42, operation: "revoke-current"); ex.Properties["identity:management-sid"] = "not-a-number"; await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(400); } [Fact] public async Task RevokeOthers_MissingSubject_Returns401() { // Same subject-precondition as every other operation — no token, no API. var sut = new MeSessionsProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: null, operation: "revoke-others"); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); ex.Out.Body.Should().BeOfType().Subject.Error.Should().Be("invalid_token"); } [Fact] public async Task RevokeOthers_MissingSidClaim_DoesNotReject400() { // CRITICAL contract: unlike revoke-current, revoke-others MUST NOT 400 when sid // is absent — the processor falls through and revokes ALL sessions of the caller. // // This unit test only covers the *precondition gate*: the processor must NOT // short-circuit with a 400/sid_unavailable response. To prove the gate let through // we drive the processor with a null IRouteContext and assert two facts: // 1. Process(...) throws ArgumentNullException from RedbRouteExtensions // .GetRedbService(...) (ThrowIfNull guard at the entry). // 2. The exchange was NOT stopped before the throw — i.e. no Reject(400) ran. // A regression that re-introduces the sid_unavailable check for revoke-others // would either set Out+IsStopped=true and return (no throw at all), violating #1, // or reach Reject before throwing, violating #2. // // The full happy-path (list → revoke-each → audit event) requires a wired // SessionService and is covered by the integration suite (see STATUS W-6 backlog). var sut = new MeSessionsProcessor(context: null!, redbName: null); var ex = BuildExchange(userId: 42, operation: "revoke-others"); var act = async () => await sut.Process(ex); await act.Should().ThrowAsync(); ex.IsStopped.Should().BeFalse("revoke-others must not reject 400 for tokens without a sid claim"); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MeWebAuthnProcessorTests.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/Routes/MeWebAuthnProcessorTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Routes.Processors; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// MFA-3 unit tests for . Mirrors /// — covers caller-id precondition paths which /// reject before any DI scope is created, so no MfaService / IFido2 wiring is /// required. Happy-path register/credentials/rename/delete flows live in the integration /// suite where a real MfaService + IWebAuthnMfaMethod are wired. /// public sealed class MeWebAuthnProcessorTests { private static Exchange BuildExchange(long? userId, string operation) { var ex = new Exchange(new Message { Body = new Dictionary() }); ex.In.Headers["operation"] = operation; if (userId is not null) ex.Properties["identity:management-user-id"] = userId.Value; return ex; } [Fact] public async Task MissingSubject_Returns401() { var sut = new MeWebAuthnProcessor(sp: null!); var ex = BuildExchange(userId: null, operation: "status"); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); ex.IsStopped.Should().BeTrue(); var body = (Dictionary)ex.Out.Body!; body["error"].Should().Be("invalid_token"); } [Fact] public async Task NonPositiveSubject_Returns401() { var sut = new MeWebAuthnProcessor(sp: null!); var ex = BuildExchange(userId: -3, operation: "credentials"); await sut.Process(ex); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(401); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MfaIdorTests.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/Routes/MfaIdorTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Routes.Processors; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// B8 — IDOR fix verification. Exercises /// directly with synthetic objects to validate the /// self-vs-admin authorization rule without spinning up the full HTTP stack. /// public sealed class MfaIdorTests { private const string AdminScope = "identity:manage"; private const string AccountScope = "identity:account"; private static RequireSelfOrAdminProcessor CreateSut() => new(AdminScope, AccountScope); private static Exchange BuildExchange(long? bodyUserId, long? callerUserId, string[]? scopes) { var body = bodyUserId.HasValue ? new Dictionary { ["userId"] = bodyUserId.Value } : new Dictionary(); var msg = new Message { Body = body }; var ex = new Exchange(msg); if (scopes is not null) ex.Properties["identity:management-scopes"] = scopes; if (callerUserId is not null) ex.Properties["identity:management-user-id"] = callerUserId.Value; return ex; } [Fact] public async Task SelfScope_WithMatchingSubject_AllowsRequest() { var sut = CreateSut(); var ex = BuildExchange(bodyUserId: 42, callerUserId: 42, scopes: new[] { AccountScope }); await sut.Process(ex); ex.HasOut.Should().BeFalse(); ex.IsStopped.Should().BeFalse(); } [Fact] public async Task SelfScope_TargetingOtherUser_IsForbidden_NoLeakage() { var sut = CreateSut(); var ex = BuildExchange(bodyUserId: 99, callerUserId: 42, scopes: new[] { AccountScope }); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(403); ex.IsStopped.Should().BeTrue(); // C4: application-level authorization denials use RFC 9457 Problem Details // (the RFC 6750 OAuth error envelope is produced upstream by ManagementBearerAuth // for scope/token failures; this processor enforces an application IDOR guard // which is not an OAuth concept and therefore uses problem+json). ex.Out!.ContentType.Should().Be("application/problem+json"); // Generic message — must not distinguish "no such user" from "not authorized". // The stable machine token is preserved as the RFC 9457 `code` extension member. var bodyText = System.Text.Encoding.UTF8.GetString((byte[])ex.Out!.Body!); bodyText.Should().Contain("not_authorized"); bodyText.Should().NotContain("99"); bodyText.Should().NotContain("42"); } [Fact] public async Task AdminScope_TargetingOtherUser_IsAllowed() { var sut = CreateSut(); var ex = BuildExchange(bodyUserId: 99, callerUserId: 42, scopes: new[] { AdminScope }); await sut.Process(ex); ex.HasOut.Should().BeFalse(); ex.IsStopped.Should().BeFalse(); } [Fact] public async Task BothScopes_AdminWins_AllowsAnyUser() { var sut = CreateSut(); var ex = BuildExchange(bodyUserId: 99, callerUserId: 42, scopes: new[] { AccountScope, AdminScope }); await sut.Process(ex); ex.HasOut.Should().BeFalse(); ex.IsStopped.Should().BeFalse(); } [Fact] public async Task SelfScope_BodyMissingUserId_IsForbidden() { var sut = CreateSut(); var ex = BuildExchange(bodyUserId: null, callerUserId: 42, scopes: new[] { AccountScope }); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(403); ex.IsStopped.Should().BeTrue(); } [Fact] public async Task SelfScope_MissingCallerUserId_IsForbidden() { // client_credentials tokens have no internal user-id mirrored. Self-service // requires an end-user grant — without a caller user-id we MUST deny. var sut = CreateSut(); var ex = BuildExchange(bodyUserId: 42, callerUserId: null, scopes: new[] { AccountScope }); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(403); ex.IsStopped.Should().BeTrue(); } [Fact] public async Task NoAuthContext_IsForbidden_DirectVmIsATransportNotATrustLevel() { // An exchange without identity:management-scopes is one nobody authenticated. This test used // to pin the opposite ("internal direct-vm callers bypass the check - direct-vm is not // network-reachable"): in a Tsak worker the direct-vm registry is shared by every module in // the process, so that bypass handed any module admin rights over users' MFA. The route gate // (RequireManagementContextProcessor) refuses first; this processor refuses on its own too. var sut = CreateSut(); var ex = BuildExchange(bodyUserId: 42, callerUserId: null, scopes: null); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(403); ex.IsStopped.Should().BeTrue(); } [Fact] public async Task UnknownScope_NeitherAdminNorSelf_IsForbidden() { // Defensive: even if upstream auth admitted some other scope (e.g. scim only), // self-or-admin must still deny. var sut = CreateSut(); var ex = BuildExchange(bodyUserId: 42, callerUserId: 42, scopes: new[] { "scim" }); await sut.Process(ex); ex.HasOut.Should().BeTrue(); ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(403); ex.IsStopped.Should().BeTrue(); } // ── The granular scopes of the surface, as the MFA route wires them ── private static RequireSelfOrAdminProcessor CreateMfaSurfaceSut() => new(AdminScope, AccountScope, surface: new RequireSelfOrAdminProcessor.SurfaceScopes( "identity:mfa:write", "identity:mfa:read", new HashSet(StringComparer.Ordinal) { "status" })); [Theory] [InlineData("identity:mfa:write", "setup", true)] [InlineData("identity:mfa:write", "disable", true)] [InlineData("identity:mfa:write", "status", true)] [InlineData("identity:mfa:read", "status", true)] [InlineData("identity:mfa:read", "setup", false)] [InlineData("identity:mfa:read", "confirm", false)] [InlineData("identity:mfa:read", "disable", false)] [InlineData("identity:mfa:read", "regenerate-recovery", false)] [InlineData("identity:mfa:read", null, false)] [InlineData("identity:users:write", "status", false)] [InlineData("identity:users:write", "setup", false)] public async Task Surface_scopes_admit_another_user_by_operation(string scope, string? operation, bool admitted) { var sut = CreateMfaSurfaceSut(); var ex = BuildExchange(bodyUserId: 99, callerUserId: null, scopes: new[] { scope }); if (operation is not null) ex.In.Headers["operation"] = operation; await sut.Process(ex); ex.IsStopped.Should().Be(!admitted); if (!admitted) ex.Out!.Headers["redbHttp.ResponseCode"].Should().Be(403); } [Fact] public async Task Without_the_surface_the_granular_write_scope_is_refused() { var sut = CreateSut(); var ex = BuildExchange(bodyUserId: 99, callerUserId: null, scopes: new[] { "identity:mfa:write" }); ex.In.Headers["operation"] = "setup"; await sut.Process(ex); ex.IsStopped.Should().BeTrue("a guard built without surface scopes keeps admitting only the master scope"); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MfaListMethodsProcessorTests.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/Routes/MfaListMethodsProcessorTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using NSubstitute; using redb.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Routes; /// /// B9 / BUG-9 — verifies the Auth0-style gated method enumeration: /// returns the methods only when given a /// valid encrypted state, never to anonymous callers. /// public sealed class MfaListMethodsProcessorTests { private readonly MfaService _mfaService; private readonly MfaStateProtector _stateProtector; private readonly MfaListMethodsProcessor _sut; public MfaListMethodsProcessorTests() { var redb = Substitute.For(); var dpProvider = DataProtectionProvider.Create("redb-mfa-listmethods-tests"); var secretProtector = new MfaSecretProtector(dpProvider); _stateProtector = new MfaStateProtector(dpProvider); _mfaService = new MfaService( redb, new IMfaMethod[] { new TotpMfaMethod(secretProtector) }, Array.Empty(), _stateProtector, new MfaSetupTokenProtector(dpProvider), Options.Create(new RedbIdentityOptions()), RecoveryCodePepperProvider.ForTesting(), NullLogger.Instance); _sut = new MfaListMethodsProcessor(BuildServiceProvider(_mfaService)); } private static IServiceProvider BuildServiceProvider(MfaService mfaService) { var scopedSp = Substitute.For(); scopedSp.GetService(typeof(MfaService)).Returns(mfaService); var scope = Substitute.For(); scope.ServiceProvider.Returns(scopedSp); var scopeFactory = Substitute.For(); scopeFactory.CreateScope().Returns(scope); var sp = Substitute.For(); sp.GetService(typeof(IServiceScopeFactory)).Returns(scopeFactory); return sp; } private TestExchange CreateExchange(IDictionary? body = null) { return new TestExchange { Pattern = redb.Route.Abstractions.ExchangePattern.InOut, In = { Body = body } }; } [Fact] public async Task MissingState_ReturnsInvalidRequest() { var exchange = CreateExchange(new Dictionary()); await _sut.Process(exchange); var result = (IDictionary)exchange.Out!.Body!; result["success"].Should().Be(false); result["error"].Should().Be("invalid_request"); } [Fact] public async Task InvalidState_ReturnsInvalidGrant_NoLeakage() { var exchange = CreateExchange(new Dictionary { ["mfa_state"] = "garbage-token" }); await _sut.Process(exchange); var result = (IDictionary)exchange.Out!.Body!; result["success"].Should().Be(false); result["error"].Should().Be("invalid_grant"); result.Should().NotContainKey("methods"); } [Fact] public async Task ValidState_ReturnsMethods() { var protectedState = _stateProtector.Protect(new MfaState { Jti = Guid.NewGuid(), UserId = 42, Username = "alice", Methods = new[] { "totp", "sms" } }); var exchange = CreateExchange(new Dictionary { ["mfa_state"] = protectedState }); await _sut.Process(exchange); var result = (IDictionary)exchange.Out!.Body!; result["success"].Should().Be(true); result["methods"].Should().BeEquivalentTo(new[] { "totp", "sms" }); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MfaRecoveryProcessorTests.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/Routes/MfaRecoveryProcessorTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Routes; /// /// Unit tests for : /// Recovery code verification during login — state decryption, one-time code consumption. /// public sealed class MfaRecoveryProcessorTests { private readonly IRedbService _redb = Substitute.For(); private readonly MfaStateProtector _stateProtector; private readonly MfaService _mfaService; private readonly MfaRecoveryProcessor _sut; public MfaRecoveryProcessorTests() { var dpProvider = DataProtectionProvider.Create("redb-mfa-recovery-tests"); var secretProtector = new MfaSecretProtector(dpProvider); _stateProtector = new MfaStateProtector(dpProvider); var totpMethod = new TotpMfaMethod(secretProtector); _mfaService = new MfaService( _redb, new IMfaMethod[] { totpMethod }, Array.Empty(), _stateProtector, new MfaSetupTokenProtector(dpProvider), Microsoft.Extensions.Options.Options.Create(new redb.Identity.Core.Configuration.RedbIdentityOptions()), RecoveryCodePepperProvider.ForTesting(), NullLogger.Instance); // B1-recovery: processor now wraps the verify in BeginTransactionAsync + LockForUpdateAsync. // Wire no-op tx + no-op lock on the substitute so the processor path executes to completion. var tx = Substitute.For(); tx.CommitAsync().Returns(Task.CompletedTask); var ctx = Substitute.For(); ctx.BeginTransactionAsync().Returns(Task.FromResult(tx)); _redb.Context.Returns(ctx); // LockForUpdateAsync returns Task (locked-row count) and, since the // CancellationToken waves, has a second (long[], ct) overload — stub both. _redb.LockForUpdateAsync(Arg.Any()).Returns(0); _redb.LockForUpdateAsync(Arg.Any(), Arg.Any()).Returns(0); var sp = BuildServiceProvider(_mfaService, _redb); _sut = new MfaRecoveryProcessor(sp); } private static IServiceProvider BuildServiceProvider(MfaService mfaService, IRedbService redb) { var scopedSp = Substitute.For(); scopedSp.GetService(typeof(MfaService)).Returns(mfaService); scopedSp.GetService(typeof(IRedbService)).Returns(redb); var scope = Substitute.For(); scope.ServiceProvider.Returns(scopedSp); var scopeFactory = Substitute.For(); scopeFactory.CreateScope().Returns(scope); var sp = Substitute.For(); sp.GetService(typeof(IServiceScopeFactory)).Returns(scopeFactory); return sp; } private static string HashCode(string code) { var normalized = code.Replace("-", "", StringComparison.Ordinal).ToUpperInvariant(); var bytes = System.Security.Cryptography.SHA256.HashData( System.Text.Encoding.UTF8.GetBytes(normalized)); return Convert.ToHexStringLower(bytes); } [Fact] public async Task Process_ValidRecoveryCode_ReturnsSuccessAndConsumesCode() { var plainCode = "ABCD-EF23"; var hash = HashCode(plainCode); var obj = new RedbObject(new MfaProps { Enabled = true, TotpConfirmed = true, RecoveryCodes = new List { hash, "other-hash" } }) { Id = 100 }; obj.key = 42; MockRedbQuery.Setup(_redb, new List> { obj }); var state = new MfaState { UserId = 42, Username = "alice", Methods = ["totp"], ReturnUrl = "/cb" }; var mfaToken = _stateProtector.Protect(state); var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["mfa_state"] = mfaToken, ["recovery_code"] = plainCode }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["success"].Should().Be(true); result["userId"].Should().Be(42L); result["username"].Should().Be("alice"); result["returnUrl"].Should().Be("/cb"); // Code should be consumed obj.Props.RecoveryCodes.Should().HaveCount(1); obj.Props.RecoveryCodes.Should().NotContain(hash); // Event exchange.Properties["identity-event-type"].Should().Be("UserLoggedIn"); } [Fact] public async Task Process_InvalidRecoveryCode_ReturnsErrorWithState() { var obj = new RedbObject(new MfaProps { Enabled = true, RecoveryCodes = new List { "some-hash" } }) { Id = 100 }; obj.key = 42; MockRedbQuery.Setup(_redb, new List> { obj }); var state = new MfaState { UserId = 42, Username = "alice", Methods = ["totp"] }; var mfaToken = _stateProtector.Protect(state); var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["mfa_state"] = mfaToken, ["recovery_code"] = "WRONG-CODE" }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["success"].Should().Be(false); result["error"].Should().Be("invalid_code"); result["mfa_state"].Should().Be(mfaToken); } [Fact] public async Task Process_MissingMfaState_ReturnsInvalidRequest() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["recovery_code"] = "ABCD-EF23" }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["error"].Should().Be("invalid_request"); } [Fact] public async Task Process_MissingRecoveryCode_ReturnsInvalidRequest() { var state = new MfaState { UserId = 42, Username = "alice" }; var mfaToken = _stateProtector.Protect(state); var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["mfa_state"] = mfaToken }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["error"].Should().Be("invalid_request"); } [Fact] public async Task Process_ExpiredState_ReturnsInvalidGrant() { var state = new MfaState { UserId = 42, Username = "alice", IssuedAt = DateTimeOffset.UtcNow.AddMinutes(-10) }; var mfaToken = _stateProtector.Protect(state); var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["mfa_state"] = mfaToken, ["recovery_code"] = "ABCD-EF23" }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["error"].Should().Be("invalid_grant"); } [Fact] public async Task Process_TamperedState_ReturnsInvalidGrant() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["mfa_state"] = "garbage-token", ["recovery_code"] = "ABCD-EF23" }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["error"].Should().Be("invalid_grant"); } [Fact] public async Task Process_NullBody_ReturnsInvalidRequest() { var exchange = new TestExchange(); exchange.In.Body = null; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["error"].Should().Be("invalid_request"); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MfaSetupProcessorTests.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/Routes/MfaSetupProcessorTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using OtpNet; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Contracts.Common; using redb.Identity.Contracts.Mfa; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Routes; /// /// Unit tests for : /// All 5 MFA management operations (status, setup, confirm, disable, regenerate-recovery). /// public sealed class MfaSetupProcessorTests { private readonly IRedbService _redb = Substitute.For(); private readonly MfaSecretProtector _secretProtector; private readonly MfaService _mfaService; private readonly MfaSetupProcessor _sut; public MfaSetupProcessorTests() { var dpProvider = DataProtectionProvider.Create("redb-mfa-processor-tests"); _secretProtector = new MfaSecretProtector(dpProvider); var stateProtector = new MfaStateProtector(dpProvider); var totpMethod = new TotpMfaMethod(_secretProtector); _mfaService = new MfaService( _redb, new IMfaMethod[] { totpMethod }, Array.Empty(), stateProtector, new MfaSetupTokenProtector(dpProvider), Microsoft.Extensions.Options.Options.Create(new redb.Identity.Core.Configuration.RedbIdentityOptions()), RecoveryCodePepperProvider.ForTesting(), NullLogger.Instance); // Build a minimal IServiceProvider that returns MfaService from scopes var sp = BuildServiceProvider(_mfaService); _sut = new MfaSetupProcessor(sp); } private static IServiceProvider BuildServiceProvider(MfaService mfaService) { var scopedSp = Substitute.For(); scopedSp.GetService(typeof(MfaService)).Returns(mfaService); var scope = Substitute.For(); scope.ServiceProvider.Returns(scopedSp); var scopeFactory = Substitute.For(); scopeFactory.CreateScope().Returns(scope); var sp = Substitute.For(); sp.GetService(typeof(IServiceScopeFactory)).Returns(scopeFactory); return sp; } private TestExchange CreateExchange(string operation, IDictionary? body = null) { var exchange = new TestExchange { Pattern = redb.Route.Abstractions.ExchangePattern.InOut }; exchange.In.Headers["operation"] = operation; exchange.In.Body = body; return exchange; } // ── Status ── [Fact] public async Task Status_MissingUserId_ReturnsError() { MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("status", new Dictionary { }); await _sut.Process(exchange); exchange.Out!.Body.Should().BeOfType().Subject.Error.Should().Be("invalid_request"); } [Fact] public async Task Status_ValidUserId_ReturnsStatus() { var obj = new RedbObject(new MfaProps { Enabled = true, TotpConfirmed = true, RecoveryCodes = new List { "a", "b" } }) { Id = 100 }; obj.key = 42; MockRedbQuery.Setup(_redb, new List> { obj }); var exchange = CreateExchange("status", new Dictionary { ["userId"] = 42L }); await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeOfType().Subject; result.Enabled.Should().BeTrue(); result.Methods.Should().Contain("totp"); result.RecoveryCodesRemaining.Should().Be(2); } // ── Setup ── [Fact] public async Task Setup_ValidRequest_ReturnsSecretAndQrUri() { MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("setup", new Dictionary { ["userId"] = 10L, ["username"] = "bob" }); await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeOfType().Subject; result.Method.Should().Be("totp"); result.SecretBase32.Should().NotBeNull(); result.QrUri.Should().Contain("bob"); } [Fact] public async Task Setup_MissingUserId_ReturnsError() { var exchange = CreateExchange("setup", new Dictionary { ["username"] = "bob" }); await _sut.Process(exchange); exchange.Out!.Body.Should().BeOfType().Subject.Error.Should().Be("invalid_request"); } // ── Confirm ── [Fact] public async Task Confirm_ValidCode_ReturnsConfirmedWithRecoveryCodes() { // First setup — issues setup_token, no DB write. MockRedbQuery.Setup(_redb, new List>()); var setupExchange = CreateExchange("setup", new Dictionary { ["userId"] = 10L, ["username"] = "alice" }); await _sut.Process(setupExchange); var setupResult = setupExchange.Out!.Body.Should().BeOfType().Subject; var secret = setupResult.SecretBase32!; var setupToken = setupResult.SetupToken!; setupToken.Should().NotBeNullOrEmpty(); // Confirm path will create the props row on demand. MockRedbQuery.Setup(_redb, new List>()); var code = GenerateValidCode(secret); var confirmExchange = CreateExchange("confirm", new Dictionary { ["userId"] = 10L, ["code"] = code, ["setup_token"] = setupToken }); await _sut.Process(confirmExchange); var result = confirmExchange.Out!.Body.Should().BeOfType().Subject; result.Confirmed.Should().BeTrue(); result.RecoveryCodes.Should().HaveCount(10); } [Fact] public async Task Confirm_InvalidCode_ReturnsError() { MockRedbQuery.Setup(_redb, new List>()); var setupExchange = CreateExchange("setup", new Dictionary { ["userId"] = 10L, ["username"] = "alice" }); await _sut.Process(setupExchange); var setupToken = setupExchange.Out!.Body.Should().BeOfType().Subject.SetupToken!; MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("confirm", new Dictionary { ["userId"] = 10L, ["code"] = "000000", ["setup_token"] = setupToken }); await _sut.Process(exchange); exchange.Out!.Body.Should().BeOfType().Subject.Error.Should().Be("invalid_code"); } [Fact] public async Task Confirm_MissingSetupToken_ReturnsError() { var exchange = CreateExchange("confirm", new Dictionary { ["userId"] = 10L, ["code"] = "123456" // setup_token deliberately missing }); await _sut.Process(exchange); exchange.Out!.Body.Should().BeOfType().Subject.Error.Should().Be("invalid_request"); } [Fact] public async Task Confirm_MissingCode_ReturnsError() { var exchange = CreateExchange("confirm", new Dictionary { ["userId"] = 10L }); await _sut.Process(exchange); exchange.Out!.Body.Should().BeOfType().Subject.Error.Should().Be("invalid_request"); } // ── Disable ── [Fact] public async Task Disable_ValidRequest_ReturnsDisabled() { var obj = new RedbObject(new MfaProps { Enabled = true, TotpConfirmed = true, TotpSecret = "enc" }) { Id = 100 }; obj.key = 10; MockRedbQuery.Setup(_redb, new List> { obj }); var exchange = CreateExchange("disable", new Dictionary { ["userId"] = 10L }); await _sut.Process(exchange); exchange.Out!.Body.Should().BeOfType().Subject.Disabled.Should().BeTrue(); } // ── Regenerate Recovery ── [Fact] public async Task RegenerateRecovery_MfaEnabled_ReturnsCodes() { var obj = new RedbObject(new MfaProps { Enabled = true, TotpConfirmed = true, RecoveryCodes = new List { "old" } }) { Id = 100 }; obj.key = 10; MockRedbQuery.Setup(_redb, new List> { obj }); var exchange = CreateExchange("regenerate-recovery", new Dictionary { ["userId"] = 10L }); await _sut.Process(exchange); exchange.Out!.Body.Should().BeOfType().Subject.RecoveryCodes.Should().HaveCount(10); } [Fact] public async Task RegenerateRecovery_MfaNotEnabled_ReturnsError() { var obj = new RedbObject(new MfaProps { Enabled = false }) { Id = 100 }; obj.key = 10; MockRedbQuery.Setup(_redb, new List> { obj }); var exchange = CreateExchange("regenerate-recovery", new Dictionary { ["userId"] = 10L }); await _sut.Process(exchange); exchange.Out!.Body.Should().BeOfType().Subject.Error.Should().Be("mfa_not_enabled"); } // ── Invalid operation ── [Fact] public async Task UnknownOperation_ReturnsError() { var exchange = CreateExchange("nonexistent"); await _sut.Process(exchange); exchange.Out!.Body.Should().BeOfType().Subject.Error.Should().Be("invalid_operation"); } [Fact] public async Task MissingOperationHeader_Throws() { var exchange = new TestExchange(); // no operation header var act = () => _sut.Process(exchange); await act.Should().ThrowAsync(); } // ── GetUserId type handling ── [Theory] [InlineData(42L)] // long [InlineData(42)] // int public async Task GetUserId_HandlesNumericTypes(object userId) { MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("status", new Dictionary { ["userId"] = userId }); await _sut.Process(exchange); // Not an error: the userId was parsed. exchange.Out!.Body.Should().BeOfType(); } [Fact] public async Task GetUserId_HandlesStringType() { MockRedbQuery.Setup(_redb, new List>()); var exchange = CreateExchange("status", new Dictionary { ["userId"] = "42" }); await _sut.Process(exchange); exchange.Out!.Body.Should().BeOfType(); } private static string GenerateValidCode(string base32Secret) { var key = Base32Encoding.ToBytes(base32Secret); var totp = new Totp(key, step: 30, totpSize: 6); return totp.ComputeTotp(); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/MfaVerifyProcessorTests.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/Routes/MfaVerifyProcessorTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; using NSubstitute; using OtpNet; using redb.Core; using redb.Core.Models.Entities; using redb.Identity.Core.Models; using redb.Identity.Core.Routes.Processors; using redb.Identity.Core.Services; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Routes; /// /// Unit tests for : /// TOTP verification during login — state decryption, code validation, session creation. /// public sealed class MfaVerifyProcessorTests { private readonly IRedbService _redb = Substitute.For(); private readonly MfaSecretProtector _secretProtector; private readonly MfaStateProtector _stateProtector; private readonly MfaService _mfaService; private readonly MfaVerifyProcessor _sut; public MfaVerifyProcessorTests() { var dpProvider = DataProtectionProvider.Create("redb-mfa-verify-tests"); _secretProtector = new MfaSecretProtector(dpProvider); _stateProtector = new MfaStateProtector(dpProvider); var totpMethod = new TotpMfaMethod(_secretProtector); _mfaService = new MfaService( _redb, new IMfaMethod[] { totpMethod }, Array.Empty(), _stateProtector, new MfaSetupTokenProtector(dpProvider), Microsoft.Extensions.Options.Options.Create(new redb.Identity.Core.Configuration.RedbIdentityOptions()), RecoveryCodePepperProvider.ForTesting(), NullLogger.Instance); var sp = BuildServiceProvider(_mfaService, _redb); _sut = new MfaVerifyProcessor(sp); } private static IServiceProvider BuildServiceProvider(MfaService mfaService, IRedbService redb) { // Stub redb.Context.BeginTransactionAsync — returns a no-op transaction var tx = Substitute.For(); var ctx = Substitute.For(); ctx.BeginTransactionAsync().Returns(Task.FromResult(tx)); redb.Context.Returns(ctx); var scopedSp = Substitute.For(); scopedSp.GetService(typeof(MfaService)).Returns(mfaService); scopedSp.GetService(typeof(IRedbService)).Returns(redb); var scope = Substitute.For(); scope.ServiceProvider.Returns(scopedSp); var scopeFactory = Substitute.For(); scopeFactory.CreateScope().Returns(scope); var sp = Substitute.For(); sp.GetService(typeof(IServiceScopeFactory)).Returns(scopeFactory); return sp; } [Fact] public async Task Process_ValidStateAndCode_ReturnsSuccess() { var base32 = "JBSWY3DPEHPK3PXP"; var obj = new RedbObject(new MfaProps { Enabled = true, TotpConfirmed = true, TotpSecret = _secretProtector.Protect(base32) }) { Id = 100 }; obj.key = 42; MockRedbQuery.Setup(_redb, new List> { obj }); var state = new MfaState { UserId = 42, Username = "alice", Methods = ["totp"], ReturnUrl = "/cb" }; var mfaToken = _stateProtector.Protect(state); var code = GenerateValidCode(base32); var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["mfa_state"] = mfaToken, ["code"] = code }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["success"].Should().Be(true); result["userId"].Should().Be(42L); result["username"].Should().Be("alice"); result["returnUrl"].Should().Be("/cb"); // Event should be set exchange.Properties["identity-event-type"].Should().Be("UserLoggedIn"); } [Fact] public async Task Process_MissingMfaState_ReturnsInvalidRequest() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["code"] = "123456" }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["success"].Should().Be(false); result["error"].Should().Be("invalid_request"); } [Fact] public async Task Process_MissingCode_ReturnsInvalidRequest() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["mfa_state"] = "some-token" }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["success"].Should().Be(false); result["error"].Should().Be("invalid_request"); } [Fact] public async Task Process_ExpiredState_ReturnsInvalidGrant() { var state = new MfaState { UserId = 42, Username = "alice", Methods = ["totp"], IssuedAt = DateTimeOffset.UtcNow.AddMinutes(-10) }; var mfaToken = _stateProtector.Protect(state); var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["mfa_state"] = mfaToken, ["code"] = "123456" }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["success"].Should().Be(false); result["error"].Should().Be("invalid_grant"); } [Fact] public async Task Process_TamperedState_ReturnsInvalidGrant() { var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["mfa_state"] = "tampered-garbage-data", ["code"] = "123456" }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["success"].Should().Be(false); result["error"].Should().Be("invalid_grant"); } [Fact] public async Task Process_InvalidCode_ReturnsInvalidCodeWithState() { var base32 = "JBSWY3DPEHPK3PXP"; var obj = new RedbObject(new MfaProps { Enabled = true, TotpConfirmed = true, TotpSecret = _secretProtector.Protect(base32) }) { Id = 100 }; obj.key = 42; MockRedbQuery.Setup(_redb, new List> { obj }); var state = new MfaState { UserId = 42, Username = "alice", Methods = ["totp"] }; var mfaToken = _stateProtector.Protect(state); var exchange = new TestExchange(); exchange.In.Body = new Dictionary { ["mfa_state"] = mfaToken, ["code"] = "000000" }; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["success"].Should().Be(false); result["error"].Should().Be("invalid_code"); result["mfa_state"].Should().Be(mfaToken, "state should be returned for retry"); } [Fact] public async Task Process_NullBody_ReturnsInvalidRequest() { var exchange = new TestExchange(); exchange.In.Body = null; await _sut.Process(exchange); var result = exchange.Out!.Body.Should().BeAssignableTo>().Subject; result["error"].Should().Be("invalid_request"); } private static string GenerateValidCode(string base32Secret) { var key = Base32Encoding.ToBytes(base32Secret); var totp = new Totp(key, step: 30, totpSize: 6); return totp.ComputeTotp(); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/RateLimitMetricsAndRetryAfterTests.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/Routes/RateLimitMetricsAndRetryAfterTests.cs ---- using System.Diagnostics.Metrics; using System.Globalization; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using redb.Identity.Core.Configuration; using redb.Identity.Core.Metrics; using redb.Identity.Core.Routes.Processors; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// G4 gap-fill — closes the "metrics" and "Retry-After RFC 7231 format" rows of the /// rate-limit test matrix. Covers: /// /// RateLimitProcessor increments identity.rate_limit.rejections with /// key_dimension=ip when the per-IP ceiling is breached. /// LoginFailureRecorderProcessor increments the same counter with /// key_dimension=ip_user so SRE dashboards can distinguish credential-stuffing /// blocks from generic per-IP throttle. /// The emitted Retry-After header is a valid RFC 7231 §7.1.3 /// delta-seconds value (1*DIGIT, positive) regardless of store-supplied /// TTL, with fallback to . /// /// public sealed class RateLimitMetricsAndRetryAfterTests { // ── Helpers ───────────────────────────────────────────────── private static IExchange MakeIpExchange(string ip) { var msg = new Message(); msg.Headers["redbHttp.RemoteAddress"] = ip; return new Exchange(msg) { Pattern = ExchangePattern.InOnly }; } private static IExchange MakeLoginExchange(string ip, string username, bool success) { var msg = new Message { Body = new Dictionary { ["username"] = username } }; msg.Headers["redbHttp.RemoteAddress"] = ip; var ex = new Exchange(msg) { Pattern = ExchangePattern.InOut }; ex.Out = new Message { Body = new Dictionary { ["success"] = success } }; return ex; } private static IServiceProvider BuildSp( RateLimitOptions rl, IRateLimitStore store, IdentityMetrics? metrics) { var opts = new RedbIdentityOptions { RateLimit = rl }; var sc = new ServiceCollection(); sc.AddSingleton(store); sc.AddSingleton>(Options.Create(opts)); if (metrics is not null) sc.AddSingleton(metrics); return sc.BuildServiceProvider(); } /// /// Wires a onto the /// meter and captures every identity.rate_limit.rejections measurement with its /// tag set. Returns a list the test can inspect after running the SUT. /// private static (IdentityMetrics Metrics, List<(long Value, Dictionary Tags)> Measurements, MeterListener Listener) BuildCapturedMetrics() { var metrics = new IdentityMetrics(); var captured = new List<(long, Dictionary)>(); var listener = new MeterListener { InstrumentPublished = (instrument, l) => { if (instrument.Meter.Name == IdentityMetrics.MeterName && instrument.Name == "identity.rate_limit.rejections") { l.EnableMeasurementEvents(instrument); } } }; listener.SetMeasurementEventCallback((instrument, value, tags, _) => { var dict = new Dictionary(tags.Length); for (var i = 0; i < tags.Length; i++) dict[tags[i].Key] = tags[i].Value; captured.Add((value, dict)); }); listener.Start(); return (metrics, captured, listener); } // ── Metrics — per-IP bucket ───────────────────────────────── [Fact] public async Task RateLimitProcessor_OverLimit_IncrementsRejectionsCounter_WithIpDimension() { var (metrics, captured, listener) = BuildCapturedMetrics(); using var _l = listener; using var _m = metrics; var rl = new RateLimitOptions { Enabled = true, PerIpPerMinute = 1, DefaultRetryAfterSeconds = 60 }; using var store = new InMemoryRateLimitStore(); var sp = BuildSp(rl, store, metrics); var p = new RateLimitProcessor(sp, "token", o => o.PerIpPerMinute, _ => TimeSpan.FromMinutes(1)); await p.Process(MakeIpExchange("1.2.3.4")); // first — passes await p.Process(MakeIpExchange("1.2.3.4")); // second — denied captured.Should().HaveCount(1, "exactly one rejection must be emitted for the single over-limit request"); captured[0].Value.Should().Be(1); captured[0].Tags.Should().ContainKey("key_dimension").WhoseValue.Should().Be("ip"); captured[0].Tags.Should().ContainKey("bucket").WhoseValue.Should().Be("token"); } // ── Metrics — per-(IP+user) bucket ────────────────────────── [Fact] public async Task LoginFailureRecorder_BreachCeiling_IncrementsRejectionsCounter_WithIpUserDimension() { var (metrics, captured, listener) = BuildCapturedMetrics(); using var _l = listener; using var _m = metrics; var rl = new RateLimitOptions { Enabled = true, PerIpUsernameFailures = 2, PerIpUsernameWindow = TimeSpan.FromMinutes(15), DefaultRetryAfterSeconds = 30 }; using var store = new InMemoryRateLimitStore(); var sp = BuildSp(rl, store, metrics); var p = new LoginFailureRecorderProcessor(sp); // Two failures below ceiling — no rejection. await p.Process(MakeLoginExchange("1.1.1.1", "alice", success: false)); await p.Process(MakeLoginExchange("1.1.1.1", "alice", success: false)); captured.Should().BeEmpty("no metric until the ceiling is breached"); // Third failure breaches the ceiling. await p.Process(MakeLoginExchange("1.1.1.1", "alice", success: false)); captured.Should().HaveCount(1); captured[0].Tags.Should().ContainKey("key_dimension").WhoseValue.Should().Be("ip_user"); captured[0].Tags.Should().ContainKey("endpoint").WhoseValue.Should().Be("login"); } // ── Retry-After — RFC 7231 delta-seconds ──────────────────── [Fact] public async Task RateLimit429_RetryAfter_IsPositiveIntegerSeconds() { // RFC 7231 §7.1.3: Retry-After = HTTP-date / delta-seconds; the latter is 1*DIGIT. // Our implementation always emits delta-seconds → must parse as a non-negative int. var rl = new RateLimitOptions { Enabled = true, PerIpPerMinute = 1, DefaultRetryAfterSeconds = 45 }; using var store = new InMemoryRateLimitStore(); var sp = BuildSp(rl, store, metrics: null); var p = new RateLimitProcessor(sp, "any", o => o.PerIpPerMinute, _ => TimeSpan.FromMinutes(1)); await p.Process(MakeIpExchange("9.9.9.9")); var denied = MakeIpExchange("9.9.9.9"); await p.Process(denied); denied.Out!.Headers.Should().ContainKey("Retry-After"); var raw = denied.Out.Headers["Retry-After"]!.ToString()!; int.TryParse(raw, NumberStyles.None, CultureInfo.InvariantCulture, out var delta) .Should().BeTrue( "Retry-After must be pure delta-seconds (1*DIGIT, no decimals / signs / whitespace); " + $"was '{raw}'"); delta.Should().BePositive( "delta-seconds must be > 0 so clients can actually wait"); // Bounded by the sliding-window length (1 min) — a broken implementation that sent // >= 3600 would effectively black-hole the client. delta.Should().BeLessThanOrEqualTo(60); } [Fact] public async Task RateLimit429_RetryAfter_FallsBackToDefault_WhenStoreHasNoHint() { // Store returns decision with RetryAfter=Zero → processor must fall back to the // configured default, not emit "0" (which clients typically retry immediately, // defeating the purpose of the throttle). var rl = new RateLimitOptions { Enabled = true, DefaultRetryAfterSeconds = 90 }; var store = new HintlessDenyingStore(); var sp = BuildSp(rl, store, metrics: null); var p = new RateLimitProcessor(sp, "any", _ => 1, _ => TimeSpan.FromMinutes(1)); var ex = MakeIpExchange("7.7.7.7"); await p.Process(ex); ex.Out!.Headers["Retry-After"].Should().Be("90"); } /// /// Test double: always denies, always reports zero TTL. Exercises the fallback path in /// . /// private sealed class HintlessDenyingStore : IRateLimitStore { public Task TryIncrementAsync(string key, int limit, TimeSpan window, CancellationToken ct = default) => Task.FromResult(new RateLimitDecision(Allowed: false, Count: limit + 1, RetryAfter: TimeSpan.Zero)); public Task ResetAsync(string key, CancellationToken ct = default) => Task.CompletedTask; } } Path: redb-identity/tests/redb.Identity.Tests/Routes/RateLimitProcessorTests.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/Routes/RateLimitProcessorTests.cs ---- using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using redb.Identity.Core.Configuration; using redb.Identity.Core.Routes.Processors; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// C1 — Verifies that is a no-op when disabled, passes /// requests below the limit, and short-circuits with HTTP 429 + Retry-After once the /// configured ceiling is breached. /// public sealed class RateLimitProcessorTests { private static IExchange MakeExchange(string ip) { var msg = new Message(); msg.Headers["redbHttp.RemoteAddress"] = ip; return new Exchange(msg) { Pattern = ExchangePattern.InOnly }; } private static IServiceProvider BuildSp(RateLimitOptions rl, IRateLimitStore store) { var opts = new RedbIdentityOptions { RateLimit = rl }; var sc = new ServiceCollection(); sc.AddSingleton(store); sc.AddSingleton>(Options.Create(opts)); return sc.BuildServiceProvider(); } [Fact] public async Task Disabled_NoOp_DoesNotTouchExchange() { var rl = new RateLimitOptions { Enabled = false }; using var store = new InMemoryRateLimitStore(); var sp = BuildSp(rl, store); var p = new RateLimitProcessor(sp, "any", o => 1, _ => TimeSpan.FromMinutes(1)); var ex = MakeExchange("1.2.3.4"); await p.Process(ex); ex.Out.Should().BeNull(); } [Fact] public async Task BelowLimit_DoesNotTouchExchange() { var rl = new RateLimitOptions { Enabled = true, PerIpPerMinute = 5 }; using var store = new InMemoryRateLimitStore(); var sp = BuildSp(rl, store); var p = new RateLimitProcessor(sp, "any", o => o.PerIpPerMinute, _ => TimeSpan.FromMinutes(1)); var ex = MakeExchange("1.2.3.4"); await p.Process(ex); ex.Out.Should().BeNull(); } [Fact] public async Task OverLimit_Sets429_RetryAfter_AndStops() { var rl = new RateLimitOptions { Enabled = true, PerIpPerMinute = 1, DefaultRetryAfterSeconds = 60 }; using var store = new InMemoryRateLimitStore(); var sp = BuildSp(rl, store); var p = new RateLimitProcessor(sp, "any", o => o.PerIpPerMinute, _ => TimeSpan.FromMinutes(1)); var ex1 = MakeExchange("1.2.3.4"); await p.Process(ex1); // first hit — passes var ex2 = MakeExchange("1.2.3.4"); await p.Process(ex2); // second hit — denied ex2.Out.Should().NotBeNull(); ex2.Out!.Headers["redbHttp.ResponseCode"].Should().Be(429); ex2.Out.Headers["redbHttp.ResponseContentType"].Should().Be("application/json"); ex2.Out.Headers.ContainsKey("Retry-After").Should().BeTrue(); var body = ex2.Out.Body as IDictionary; body.Should().NotBeNull(); body!["success"].Should().Be(false); body["error"].Should().Be("rate_limited"); ex2.Exception.Should().BeOfType(); ex2.ExceptionHandled.Should().BeTrue(); } // ── G4 — sliding-window recovery ── [Fact] public async Task PerIpBuckets_DistinctIPs_DoNotShareCounter() { // C1 contract: bucket key includes the IP. A spike from 1.2.3.4 must not block // unrelated 5.6.7.8 traffic. var rl = new RateLimitOptions { Enabled = true, PerIpPerMinute = 1, DefaultRetryAfterSeconds = 60 }; using var store = new InMemoryRateLimitStore(); var sp = BuildSp(rl, store); var p = new RateLimitProcessor(sp, "any", o => o.PerIpPerMinute, _ => TimeSpan.FromMinutes(1)); var first = MakeExchange("1.2.3.4"); var second = MakeExchange("1.2.3.4"); var third = MakeExchange("5.6.7.8"); // different IP → independent bucket await p.Process(first); await p.Process(second); await p.Process(third); first.Out.Should().BeNull(); second.Out!.Headers["redbHttp.ResponseCode"].Should().Be(429); third.Out.Should().BeNull("a different IP must not inherit the first IP's counter"); } [Fact] public async Task SlidingWindow_RecoversAfterWindowExpires() { // C1 contract: counter is a sliding window, not a fixed bucket. Once the window // elapses since the recorded hit, a new attempt is allowed. var rl = new RateLimitOptions { Enabled = true, PerIpPerMinute = 1, DefaultRetryAfterSeconds = 60 }; var clock = new Microsoft.Extensions.Time.Testing.FakeTimeProvider( startDateTime: new DateTimeOffset(2026, 1, 1, 12, 0, 0, TimeSpan.Zero)); using var store = new InMemoryRateLimitStore(clock); var sp = BuildSp(rl, store); var p = new RateLimitProcessor(sp, "any", o => o.PerIpPerMinute, _ => TimeSpan.FromMinutes(1)); var ex1 = MakeExchange("1.2.3.4"); await p.Process(ex1); // first hit — passes ex1.Out.Should().BeNull(); // Immediately retry → still throttled. var ex2 = MakeExchange("1.2.3.4"); await p.Process(ex2); ex2.Out!.Headers["redbHttp.ResponseCode"].Should().Be(429); // Advance past the 1-minute window → bucket recovers. clock.Advance(TimeSpan.FromMinutes(1) + TimeSpan.FromSeconds(1)); var ex3 = MakeExchange("1.2.3.4"); await p.Process(ex3); ex3.Out.Should().BeNull("after the sliding window elapses the previous hit must be forgotten"); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/RequireManagementContextProcessorTests.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/Routes/RequireManagementContextProcessorTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Routes; /// /// The management gate starts every operation without an event, so an exchange reused for several /// in-process management calls does not carry the previous call's event into the next route's WireTap. /// public class RequireManagementContextProcessorTests { [Theory] [InlineData(true)] [InlineData(false)] public async Task PreviousEventMarkers_AreClearedOnEntry(bool withContext) { var exchange = new TestExchange(); exchange.Properties["identity-event-type"] = "RoleScopeAttached"; exchange.Properties["identity-event-data"] = new { RoleId = 1L, ScopeId = 2L }; if (withContext) ManagementCallerContext.Apply(exchange, ManagementCaller.Admin); await new RequireManagementContextProcessor().Process(exchange); exchange.Properties.Should().NotContainKey("identity-event-type"); exchange.Properties.Should().NotContainKey("identity-event-data"); exchange.IsStopped.Should().Be(!withContext, "the gate itself still admits or refuses as before"); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/RequireSelfOrAdminProcessorTests.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/Routes/RequireSelfOrAdminProcessorTests.cs ---- using AwesomeAssertions; using redb.Identity.Core.Routes.Processors; using redb.Route.Abstractions; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// The self-or-admin rule is an authorization gate, and a gate has one direction it must never fail. /// An exchange with no management context is not an internal trusted caller — it is a caller nobody /// authenticated — and it is refused like any other unauthorized one. /// public sealed class RequireSelfOrAdminProcessorTests { private const string Admin = "identity:manage"; private const string Account = "identity:account"; private static Exchange Request(long bodyUserId, string[]? scopes, long? callerUserId = null) { var message = new Message { Body = new Dictionary { ["userId"] = bodyUserId } }; var exchange = new Exchange(message) { Pattern = ExchangePattern.InOut }; if (scopes is not null) exchange.Properties["identity:management-scopes"] = scopes; if (callerUserId is not null) exchange.Properties["identity:management-user-id"] = callerUserId.Value; return exchange; } private static int? StatusOf(IExchange exchange) => exchange.Out is { } o && o.Headers.TryGetValue("redbHttp.ResponseCode", out var raw) && raw is not null ? Convert.ToInt32(raw) : null; [Fact] public async Task No_management_context_is_refused() { var sut = new RequireSelfOrAdminProcessor(Admin, Account); var exchange = Request(bodyUserId: 42, scopes: null); await sut.Process(exchange); StatusOf(exchange).Should().Be(403, "absence of a management context means nobody authenticated this caller; it is not a trusted internal one"); } [Fact] public async Task Admin_scope_passes() { var sut = new RequireSelfOrAdminProcessor(Admin, Account); var exchange = Request(bodyUserId: 42, scopes: new[] { Admin }); await sut.Process(exchange); StatusOf(exchange).Should().BeNull(); } [Fact] public async Task Account_scope_passes_only_for_the_caller_itself() { var sut = new RequireSelfOrAdminProcessor(Admin, Account); var self = Request(bodyUserId: 42, scopes: new[] { Account }, callerUserId: 42); await sut.Process(self); StatusOf(self).Should().BeNull("the body targets the caller"); var other = Request(bodyUserId: 43, scopes: new[] { Account }, callerUserId: 42); await sut.Process(other); StatusOf(other).Should().Be(403, "the body targets another user"); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/RouteRegistrationTests.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/Routes/RouteRegistrationTests.cs ---- using AwesomeAssertions; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NSubstitute; using OpenIddict.Server; using redb.Core; using redb.Identity.Contracts.Configuration; using redb.Identity.Core.Configuration; using redb.Identity.Core.OpenIddict; using redb.Identity.Contracts.Routes; using redb.Identity.Core.Services; using redb.Route.Abstractions; using redb.Route.Definitions; using Xunit; using static OpenIddict.Server.OpenIddictServerEvents; using redb.Identity.Core.Routes; namespace redb.Identity.Tests.Routes; public class RouteRegistrationTests { private readonly IdentityCoreRouteBuilder _builder; public RouteRegistrationTests() { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); services.AddSingleton(Options.Create(new RedbIdentityOptions())); // MFA protectors required by IdentityCoreRouteBuilder.Configure(). services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddOpenIddict() .AddServer(options => { options.EnableDegradedMode(); options.SetIssuer(new Uri("https://identity.test.local/")); options.SetTokenEndpointUris("/connect/token"); options.AllowClientCredentialsFlow(); options.AddEphemeralEncryptionKey(); options.AddEphemeralSigningKey(); options.DisableAccessTokenEncryption(); options.UseRedbRoute(); options.AddEventHandler(builder => builder.UseInlineHandler(context => default) .SetOrder(int.MaxValue - 100_000).Build()); }); var sp = services.BuildServiceProvider(); _builder = new IdentityCoreRouteBuilder(sp, sp.GetRequiredService>()); ((IRouteBuilder)_builder).Configure(null!); } [Fact] public void Configure_DoesNotThrow() { // Already called in constructor — if we got here, it didn't throw. _builder.Definitions.Should().NotBeEmpty(); } [Fact] public void AllRoutes_Count_Is_45() { // 25 OIDC/MFA routes + 2 cleanup timer routes added by B3 hardening // (identity-mfa-otp-cleanup) and A1 (identity-xml-refresh, materialized via // redb.Route TimerDsl → separate RouteDefinition) + 1 admin audit query route // (identity-manage-audit) added by H9 (v1.0 DoD) + 1 self-service sessions route // (identity-me-sessions) added by H3-SSO (v1.0 DoD §6 scoped-subset) + 4 // self-service account-console routes (identity-me-profile/password/mfa/consents) // added by H3 full closure (v1.0 DoD §6) + 2 H5 admin routes // (identity-manage-claim-mappers, identity-manage-claim-scopes) + 2 H8 federation // routes (identity-me-federated-identities, identity-manage-federation-providers) // + 3 unconditional routes added later (token-cleanup, session-cleanup, // mfa-otp-cleanup are timer routes; trusted-proxy-resolver wires HTTP transport) // + 1 B1 emergency-admin bootstrap route (identity-bootstrap-admin) registered // unconditionally; processor self-disables when BootstrapOptions.Enabled=false. // + 2 W6-0 backchannel routes (identity-revoked-sids manage + identity-revoked-sids-cleanup timer). // + 2 N-4 password-recovery routes (identity-password-forgot + identity-password-reset). // The identity-email-send SMTP route is NOT counted here: RedbIdentityOptions defaults to // Smtp.Enabled=false so the route is conditionally skipped. // + 1 N7-3 admin impersonation overlay route (identity-manage-impersonation), unconditional. // + 1 B.3 role management (identity-manage-roles). // + 1 S2 claim-definitions management (identity-manage-claim-definitions). // + 1 W1 webhook subscription management (identity-manage-webhooks). // + 1 F5 transport-neutral authorization check (identity-authz-check), unconditional: // a facade calling an address that is not registered would fail open. // Total: 49 + 1 = 50. _builder.Definitions.Should().HaveCount(53); // +2: the outbox timers (identity-webhook-delivery, identity-delivery-cleanup); +1: identity-idempotency-cleanup } [Fact] public void AllRoutes_HaveRouteIds() { foreach (var def in _builder.Definitions) { def.GetRouteId().Should().NotBeNullOrWhiteSpace( $"route from '{def.GetFromUri()}' must have a RouteId"); } } [Fact] public void AllRouteIds_AreUnique() { var ids = _builder.Definitions.Select(d => d.GetRouteId()).ToList(); ids.Should().OnlyHaveUniqueItems(); } [Fact] public void AllRoutes_RegisteredWithCorrectUris() { var uris = _builder.Definitions.Select(d => d.GetFromUri()).ToList(); uris.Should().Contain(IdentityEndpoints.Token); uris.Should().Contain(IdentityEndpoints.Authorize); uris.Should().Contain(IdentityEndpoints.Userinfo); uris.Should().Contain(IdentityEndpoints.Introspect); uris.Should().Contain(IdentityEndpoints.Revoke); uris.Should().Contain(IdentityEndpoints.Discovery); uris.Should().Contain(IdentityEndpoints.Jwks); uris.Should().Contain(IdentityEndpoints.ManageApps); uris.Should().Contain(IdentityEndpoints.ManageScopes); uris.Should().Contain(IdentityEndpoints.ManageUsers); uris.Should().Contain(IdentityEndpoints.ManageTokens); uris.Should().Contain(IdentityEndpoints.ManageGroups); uris.Should().Contain(IdentityEndpoints.Events); uris.Should().Contain(IdentityEndpoints.ManageConsents); uris.Should().Contain(IdentityEndpoints.Logout); uris.Should().Contain(IdentityEndpoints.ManageSessions); uris.Should().Contain(IdentityEndpoints.MeSessions); uris.Should().Contain(IdentityEndpoints.MeProfile); uris.Should().Contain(IdentityEndpoints.MePassword); uris.Should().Contain(IdentityEndpoints.MeMfa); uris.Should().Contain(IdentityEndpoints.MeConsents); uris.Should().Contain(IdentityEndpoints.ManageClaimMappers); uris.Should().Contain(IdentityEndpoints.ManageClaimScopes); uris.Should().Contain(IdentityEndpoints.MeFederatedIdentities); uris.Should().Contain(IdentityEndpoints.ManageFederationProviders); } [Theory] [InlineData("identity-token", "direct-vm://identity-token")] [InlineData("identity-authorize", "direct-vm://identity-authorize")] [InlineData("identity-userinfo", "direct-vm://identity-userinfo")] [InlineData("identity-introspect", "direct-vm://identity-introspect")] [InlineData("identity-revoke", "direct-vm://identity-revoke")] [InlineData("identity-discovery", "direct-vm://identity-discovery")] [InlineData("identity-jwks", "direct-vm://identity-jwks")] [InlineData("identity-manage-apps", "direct-vm://identity-manage-apps")] [InlineData("identity-manage-scopes", "direct-vm://identity-manage-scopes")] [InlineData("identity-manage-users", "direct-vm://identity-manage-users")] [InlineData("identity-manage-tokens", "direct-vm://identity-manage-tokens")] [InlineData("identity-manage-groups", "direct-vm://identity-manage-groups")] [InlineData("identity-events", "direct-vm://identity-events")] [InlineData("identity-manage-consents", "direct-vm://identity-manage-consents")] [InlineData("identity-logout", "direct-vm://identity-logout")] [InlineData("identity-manage-sessions", "direct-vm://identity-manage-sessions")] [InlineData("identity-me-sessions", "direct-vm://identity-me-sessions")] [InlineData("identity-me-profile", "direct-vm://identity-me-profile")] [InlineData("identity-me-password", "direct-vm://identity-me-password")] [InlineData("identity-me-mfa", "direct-vm://identity-me-mfa")] [InlineData("identity-me-consents", "direct-vm://identity-me-consents")] [InlineData("identity-manage-claim-mappers", "direct-vm://identity-manage-claim-mappers")] [InlineData("identity-manage-claim-scopes", "direct-vm://identity-manage-claim-scopes")] [InlineData("identity-me-federated-identities", "direct-vm://identity-me-federated-identities")] [InlineData("identity-manage-federation-providers", "direct-vm://identity-manage-federation-providers")] public void Route_HasCorrectIdAndUri(string expectedRouteId, string expectedUri) { var route = _builder.Definitions .FirstOrDefault(d => d.GetRouteId() == expectedRouteId); route.Should().NotBeNull($"route with id '{expectedRouteId}' should exist"); route!.GetFromUri().Should().Be(expectedUri); } [Fact] public void AllRoutes_Count_With_WebAuthn_Enabled_Is_48() { // Default builder above has WebAuthn.Enabled = false (49 routes — see // AllRoutes_Count_Is_45 for the breakdown). With WebAuthn toggled on the // conditional block in IdentityCoreRouteBuilder adds 3 more: identity-me-webauthn // (self-service), identity-mfa-webauthn (assertion login), // identity-mfa-webauthn-challenge-cleanup (timer). Total → 49 + 3 = 52. var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); var opts = new RedbIdentityOptions(); opts.WebAuthn.Enabled = true; opts.WebAuthn.RpId = "auth.test.local"; opts.WebAuthn.Origins.Add("https://auth.test.local"); services.AddSingleton(Options.Create(opts)); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddOpenIddict() .AddServer(o => { o.EnableDegradedMode(); o.SetIssuer(new Uri("https://identity.test.local/")); o.SetTokenEndpointUris("/connect/token"); o.AllowClientCredentialsFlow(); o.AddEphemeralEncryptionKey(); o.AddEphemeralSigningKey(); o.DisableAccessTokenEncryption(); o.UseRedbRoute(); o.AddEventHandler(b => b.UseInlineHandler(_ => default).SetOrder(int.MaxValue - 100_000).Build()); }); var sp = services.BuildServiceProvider(); var builder = new IdentityCoreRouteBuilder(sp, sp.GetRequiredService>()); ((IRouteBuilder)builder).Configure(null!); builder.Definitions.Should().HaveCount(56); // +2: the outbox timers (identity-webhook-delivery, identity-delivery-cleanup); +1: identity-idempotency-cleanup var ids = builder.Definitions.Select(d => d.GetRouteId()).ToList(); ids.Should().Contain("identity-me-webauthn"); ids.Should().Contain("identity-mfa-webauthn"); ids.Should().Contain("identity-mfa-webauthn-challenge-cleanup"); } [Fact] public void AllRoutes_Count_With_Par_Enabled_Is_44() { // Default builder above has EnablePushedAuthorization = false (46 routes — see // AllRoutes_Count_Is_45 for the breakdown, incl. the N7-3 admin impersonation overlay). // With PAR toggled on the conditional block in IdentityCoreRouteBuilder // adds exactly one route: identity-par. var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); var opts = new RedbIdentityOptions { Features = new IdentityFeatureFlags { EnablePushedAuthorization = true } }; services.AddSingleton(Options.Create(opts)); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddOpenIddict() .AddServer(o => { o.EnableDegradedMode(); o.SetIssuer(new Uri("https://identity.test.local/")); o.SetTokenEndpointUris("/connect/token"); o.SetPushedAuthorizationEndpointUris("/connect/par"); o.AllowClientCredentialsFlow(); o.AddEphemeralEncryptionKey(); o.AddEphemeralSigningKey(); o.DisableAccessTokenEncryption(); o.UseRedbRoute(); o.AddEventHandler(b => b.UseInlineHandler(_ => default).SetOrder(int.MaxValue - 100_000).Build()); }); var sp = services.BuildServiceProvider(); var builder = new IdentityCoreRouteBuilder(sp, sp.GetRequiredService>()); ((IRouteBuilder)builder).Configure(null!); // Default 49 + 1 PAR route = 50. builder.Definitions.Should().HaveCount(54); // +2: the outbox timers (identity-webhook-delivery, identity-delivery-cleanup); +1: identity-idempotency-cleanup var ids = builder.Definitions.Select(d => d.GetRouteId()).ToList(); ids.Should().Contain("identity-par"); } [Fact] public void Pepper_usage_report_is_registered_only_while_previous_peppers_are_configured() { _builder.Definitions.Select(d => d.GetRouteId()).Should().NotContain("identity-pepper-usage-report"); var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); services.AddSingleton(Options.Create(new RedbIdentityOptions { RecoveryCodePreviousPeppers = [Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32))], })); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddOpenIddict() .AddServer(o => { o.EnableDegradedMode(); o.SetIssuer(new Uri("https://identity.test.local/")); o.SetTokenEndpointUris("/connect/token"); o.AllowClientCredentialsFlow(); o.AddEphemeralEncryptionKey(); o.AddEphemeralSigningKey(); o.DisableAccessTokenEncryption(); o.UseRedbRoute(); o.AddEventHandler(b => b.UseInlineHandler(_ => default).SetOrder(int.MaxValue - 100_000).Build()); }); var sp = services.BuildServiceProvider(); var builder = new IdentityCoreRouteBuilder(sp, sp.GetRequiredService>()); ((IRouteBuilder)builder).Configure(null!); builder.Definitions.Should().HaveCount(_builder.Definitions.Count + 1); builder.Definitions.Select(d => d.GetRouteId()).Should().Contain("identity-pepper-usage-report"); } [Fact] public void AllRoutes_With_ScimBulk_Enabled_RegistersBulkRoute() { // SCIM is opt-in; bulk is an additional opt-in on top of SCIM. Default builder // above has both off (46 routes — see AllRoutes_Count_Is_45 for the breakdown). // Enabling EnableScim adds /Users + /Groups (2 routes); EnableScimBulk adds the // bulk dispatcher (1 route) → 46 + 3 = 49. var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); var opts = new RedbIdentityOptions { Features = new IdentityFeatureFlags { EnableScim = true, EnableScimBulk = true } }; services.AddSingleton(Options.Create(opts)); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddOpenIddict() .AddServer(o => { o.EnableDegradedMode(); o.SetIssuer(new Uri("https://identity.test.local/")); o.SetTokenEndpointUris("/connect/token"); o.AllowClientCredentialsFlow(); o.AddEphemeralEncryptionKey(); o.AddEphemeralSigningKey(); o.DisableAccessTokenEncryption(); o.UseRedbRoute(); o.AddEventHandler(b => b.UseInlineHandler(_ => default).SetOrder(int.MaxValue - 100_000).Build()); }); var sp = services.BuildServiceProvider(); var builder = new IdentityCoreRouteBuilder(sp, sp.GetRequiredService>()); ((IRouteBuilder)builder).Configure(null!); // Default 50 + 2 SCIM (Users + Groups) + 1 SCIM Bulk = 53. builder.Definitions.Should().HaveCount(56); // +2: the outbox timers (identity-webhook-delivery, identity-delivery-cleanup); +1: identity-idempotency-cleanup var ids = builder.Definitions.Select(d => d.GetRouteId()).ToList(); ids.Should().Contain(IdentityEndpoints.RouteIds.ScimUsers); ids.Should().Contain(IdentityEndpoints.RouteIds.ScimGroups); ids.Should().Contain(IdentityEndpoints.RouteIds.ScimBulk); } [Fact] public void AllRoutes_With_Scim_Enabled_But_Bulk_Disabled_OmitsBulkRoute() { var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(Substitute.For()); var opts = new RedbIdentityOptions { Features = new IdentityFeatureFlags { EnableScim = true, EnableScimBulk = false } }; services.AddSingleton(Options.Create(opts)); services.AddDataProtection().UseEphemeralDataProtectionProvider(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddOpenIddict() .AddServer(o => { o.EnableDegradedMode(); o.SetIssuer(new Uri("https://identity.test.local/")); o.SetTokenEndpointUris("/connect/token"); o.AllowClientCredentialsFlow(); o.AddEphemeralEncryptionKey(); o.AddEphemeralSigningKey(); o.DisableAccessTokenEncryption(); o.UseRedbRoute(); o.AddEventHandler(b => b.UseInlineHandler(_ => default).SetOrder(int.MaxValue - 100_000).Build()); }); var sp = services.BuildServiceProvider(); var builder = new IdentityCoreRouteBuilder(sp, sp.GetRequiredService>()); ((IRouteBuilder)builder).Configure(null!); // Default 49 + 2 SCIM (Users + Groups), bulk omitted = 51. builder.Definitions.Should().HaveCount(55); // +2: the outbox timers (identity-webhook-delivery, identity-delivery-cleanup); +1: identity-idempotency-cleanup var ids = builder.Definitions.Select(d => d.GetRouteId()).ToList(); ids.Should().NotContain(IdentityEndpoints.RouteIds.ScimBulk); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/TrustedProxyResolverProcessorTests.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/Routes/TrustedProxyResolverProcessorTests.cs ---- using System.Net; using AwesomeAssertions; using redb.Identity.Core.Configuration; using redb.Identity.Core.Routes.Processors; using redb.Route.Abstractions; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// C2 — Verifies that sanitizes the /// redbHttp.RemoteAddress header according to the secure-by-default trust model /// described on . /// public sealed class TrustedProxyResolverProcessorTests { private const string SocketIpHeader = "redbHttp.RemoteAddress"; private const string XForwardedFor = "X-Forwarded-For"; private static IExchange MakeExchange(string socketIp, string? xForwardedFor) { var msg = new Message(); msg.Headers[SocketIpHeader] = socketIp; if (xForwardedFor is not null) msg.Headers[XForwardedFor] = xForwardedFor; return new Exchange(msg) { Pattern = ExchangePattern.InOnly }; } [Fact] public async Task TrustForwardedForFalse_DoesNothing_EvenWithProxyWhitelisted() { var opts = new ReverseProxyOptions { TrustForwardedFor = false, KnownProxies = { IPAddress.Parse("10.0.0.1") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("10.0.0.1", "1.2.3.4"); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("10.0.0.1"); } [Fact] public async Task UntrustedSocketPeer_IgnoresXForwardedFor() { // The peer is NOT in the whitelist — XFF can be spoofed and must be discarded. var opts = new ReverseProxyOptions { TrustForwardedFor = true, KnownProxies = { IPAddress.Parse("10.0.0.1") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("203.0.113.99", "1.2.3.4"); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("203.0.113.99"); } [Fact] public async Task TrustedSocketPeer_OverwritesWithRightmostUntrustedHop() { var opts = new ReverseProxyOptions { TrustForwardedFor = true, KnownProxies = { IPAddress.Parse("10.0.0.1") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("10.0.0.1", "1.2.3.4"); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("1.2.3.4"); } [Fact] public async Task MultiHopChain_SkipsTrustedHopsRightToLeft() { // Two trusted proxies in series; the real client is the leftmost untrusted IP. var opts = new ReverseProxyOptions { TrustForwardedFor = true, KnownProxies = { IPAddress.Parse("10.0.0.1"), IPAddress.Parse("10.0.0.2") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("10.0.0.1", "1.2.3.4, 10.0.0.2"); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("1.2.3.4"); } [Fact] public async Task KnownNetworks_CidrMatch_TreatsPeerAsTrusted() { var opts = new ReverseProxyOptions { TrustForwardedFor = true, KnownNetworks = { IPNetwork.Parse("10.0.0.0/24") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("10.0.0.42", "1.2.3.4"); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("1.2.3.4"); } [Fact] public async Task ChainEntirelyTrusted_LeavesSocketIpUnchanged() { var opts = new ReverseProxyOptions { TrustForwardedFor = true, KnownProxies = { IPAddress.Parse("10.0.0.1"), IPAddress.Parse("10.0.0.2") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("10.0.0.1", "10.0.0.2"); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("10.0.0.1"); } [Fact] public async Task NoXForwardedFor_LeavesHeaderUnchanged() { var opts = new ReverseProxyOptions { TrustForwardedFor = true, KnownProxies = { IPAddress.Parse("10.0.0.1") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("10.0.0.1", null); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("10.0.0.1"); } [Fact] public async Task IPv4WithPort_StripsPort() { var opts = new ReverseProxyOptions { TrustForwardedFor = true, KnownProxies = { IPAddress.Parse("10.0.0.1") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("10.0.0.1", "1.2.3.4:54321"); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("1.2.3.4"); } [Fact] public async Task IPv6BracketWithPort_StripsBracketsAndPort() { var opts = new ReverseProxyOptions { TrustForwardedFor = true, KnownProxies = { IPAddress.Parse("10.0.0.1") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("10.0.0.1", "[2001:db8::1]:443"); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("2001:db8::1"); } [Fact] public async Task UnparseableHop_StopsTheWalk_KeepsSocketIp() { // "unknown" is a legal RFC 7239 identifier a proxy may write for a peer it could not name. // It must END the walk. Skipping it would carry the walk left into "203.0.113.7", which in // this header is the client-supplied part, and hand the client its own throttle bucket. var opts = new ReverseProxyOptions { TrustForwardedFor = true, KnownProxies = { IPAddress.Parse("10.0.0.1") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("10.0.0.1", "203.0.113.7, unknown"); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("10.0.0.1"); } [Fact] public async Task HostAlreadyResolved_PeerNotInList_IsIdempotent() { // When the shared Kestrel host has already rewritten RemoteAddress to the client, the // processor sees a peer that is not a trusted proxy and must leave it alone. This is what // makes host-level and processor-level resolution safe to run together. var opts = new ReverseProxyOptions { TrustForwardedFor = true, KnownProxies = { IPAddress.Parse("10.0.0.1") } }; var sut = new TrustedProxyResolverProcessor(opts); var ex = MakeExchange("203.0.113.7", "203.0.113.7, 10.0.0.9"); await sut.Process(ex); ex.In.Headers[SocketIpHeader].Should().Be("203.0.113.7"); } } Path: redb-identity/tests/redb.Identity.Tests/Routes/UniqueViolationMetricCallSitesTests.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/Routes/UniqueViolationMetricCallSitesTests.cs ---- using System.Diagnostics.Metrics; using AwesomeAssertions; using Microsoft.Extensions.DependencyInjection; using redb.Identity.Core.Metrics; using redb.Identity.Core.Routes.Processors; using redb.Route.Core; using Xunit; namespace redb.Identity.Tests.Routes; /// /// The processors that catch a unique violation themselves and answer the caller with a conflict /// count it on identity.unique_violation as the builder-level handlers do. The list below is /// the whole of them; a processor added to it or taken from it changes what the metric means. /// public class UniqueViolationMetricCallSitesTests { private static readonly string ProcessorsFolder = LocateProcessorsFolder(); public static IEnumerable ProcessorsThatAnswerAConflictThemselves() => new[] { new object[] { "ApplicationManagementProcessor.cs" }, new object[] { "ScopeManagementProcessor.cs" }, new object[] { "ClaimScopeManagementProcessor.cs" }, new object[] { "BootstrapAdminProcessor.cs" }, new object[] { "AccountRegisterProcessor.cs" }, new object[] { "ScimUserProcessor.cs" }, }; [Theory] [MemberData(nameof(ProcessorsThatAnswerAConflictThemselves))] public void TheProcessorCountsTheViolationItCatches(string file) { var source = File.ReadAllText(Path.Combine(ProcessorsFolder, file)); source.Should().Contain("IdentityProcessorHelpers.CountUniqueViolation(_context, exchange,", $"{file} answers a unique violation itself, so it has to count it itself"); } [Fact] public async Task TheProcessorSideCount_ReachesTheMeterOfTheHost() { var seen = new List>(); using var listener = new MeterListener(); listener.InstrumentPublished = (instrument, l) => { if (instrument.Meter.Name == IdentityMetrics.MeterName && instrument.Name == "identity.unique_violation") l.EnableMeasurementEvents(instrument); }; listener.SetMeasurementEventCallback((_, _, tags, _) => { var map = new Dictionary(); foreach (var tag in tags) map[tag.Key] = tag.Value?.ToString(); lock (seen) seen.Add(map); }); var services = new ServiceCollection(); services.AddSingleton(); await using var provider = services.BuildServiceProvider(); listener.Start(); await using var context = new RouteContext(provider, "unique-violation-call-site"); var exchange = new Exchange(new Message()); IdentityProcessorHelpers.CountUniqueViolation(context, exchange, new InvalidOperationException("UNIQUE constraint failed: _users._email")); seen.Should().ContainSingle(); seen[0]["scheme"].Should().Be("_users"); seen[0]["column"].Should().Be("_email"); } private static string LocateProcessorsFolder() { for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) { foreach (var root in new[] { dir.FullName, Path.Combine(dir.FullName, "redb.Identity") }) { var candidate = Path.Combine(root, "src", "redb.Identity.Core", "Routes", "Processors"); if (Directory.Exists(candidate)) return candidate; } } throw new InvalidOperationException("Could not locate redb.Identity.Core/Routes/Processors from the test base directory."); } }