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;