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