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;
}
}