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