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