Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditTargetOutboxTests.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/AuditTargetOutboxTests.cs ---- using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json; using AwesomeAssertions; using Microsoft.Extensions.Logging.Abstractions; using redb.Identity.Contracts.Events; using redb.Identity.Core.Configuration; using redb.Identity.Core.Routes.Processors; using redb.Identity.Tests.Infrastructure; using redb.Route.Serialization; using Xunit; namespace redb.Identity.Tests.Audit; /// /// External audit targets go through the delivery outbox: a target that is down gets the event when it /// is back, a target removed from the configuration gets nothing and its rows end cancelled. /// [Collection("ProductionHttp")] public sealed class AuditTargetOutboxTests { private const string Target = "test-capture"; private readonly ProductionHttpFixture _fx; public AuditTargetOutboxTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task ATargetThatIsDown_IsRetried_AndGetsTheEventOnceItIsBack() { await _fx.DeliverOutboxAsync(); // clear what earlier tests left var group = await RaiseAsync(); var row = await WaitForRowAsync(group); // The same target name, its endpoint gone: the attempt fails and the row waits for its retry. var down = new WebhookDeliveryWorker(_fx.ServiceProvider, _fx.Context, new DeliveryOptions(), TimeProvider.System, NullLogger.Instance, auditTargets: [new AuditTarget { Name = Target, Enabled = true, Uri = "nosuchtransport:identity-test-audit-down", MaxAttempts = 5, RetryBackoffMs = 50 }]); await RunUntilAsync(down, async () => (await StateAsync(row)).Attempts >= 1); var afterFailure = await StateAsync(row); afterFailure.Status.Should().Be("pending"); afterFailure.LastError.Should().NotBeNullOrEmpty(); _fx.AuditTargetMessages.Should().NotContain(m => m.Body.Contains(group)); // Back: the fixture's own target. var deadline = DateTime.UtcNow.AddSeconds(15); while (!_fx.AuditTargetMessages.Any(m => m.Body.Contains(group)) && DateTime.UtcNow < deadline) { await _fx.DeliverOutboxAsync(); await Task.Delay(50); } _fx.AuditTargetMessages.Count(m => m.Body.Contains(group)).Should().Be(1); var delivered = await StateAsync(row); delivered.Status.Should().Be("delivered"); delivered.Attempts.Should().Be(2); } [Fact] public async Task ATargetRemovedFromTheConfiguration_GetsNothing_AndItsRowIsCancelled() { await _fx.DeliverOutboxAsync(); var group = await RaiseAsync(); var row = await WaitForRowAsync(group); var withoutTargets = new WebhookDeliveryWorker(_fx.ServiceProvider, _fx.Context, new DeliveryOptions(), TimeProvider.System, NullLogger.Instance, auditTargets: []); await RunUntilAsync(withoutTargets, async () => (await StateAsync(row)).Status != "pending"); (await StateAsync(row)).Status.Should().Be("cancelled"); await _fx.DeliverOutboxAsync(); _fx.AuditTargetMessages.Should().NotContain(m => m.Body.Contains(group)); } [Fact] public void TheMessage_IsWhatTheTargetsReceivedBeforeTheOutbox() { // Nested values are encoded differently in the body (camelCase) and in the details header (as // declared); both must reach the target exactly as the events route used to produce them. var evt = new IdentityEvent { EventType = "GroupCreated", UserId = "42", ClientId = null, IpAddress = "10.0.0.1", Details = new Dictionary { ["GroupId"] = 7L, ["Nested"] = new { InnerName = "x" }, ["Text"] = "\"q\" é" }, }; var message = AuditTargetMessage.Build(AuditTargetMessage.Payload(evt)); System.Text.Encoding.UTF8.GetString((byte[])message.Body!) .Should().Be(System.Text.Encoding.UTF8.GetString(new JsonMessageSerializer().Serialize(evt))); message.ContentType.Should().Be("application/json"); message.Headers["details"].Should().Be(JsonSerializer.Serialize(evt.Details)); message.Headers["event_id"].Should().Be(Guid.Parse(evt.EventId)); message.Headers["event_type"].Should().Be("GroupCreated"); message.Headers["event-type"].Should().Be("GroupCreated"); message.Headers["timestamp"].Should().Be(evt.Timestamp); message.Headers["user_id"].Should().Be("42"); message.Headers["client_id"].Should().Be(DBNull.Value); message.Headers["ip_address"].Should().Be("10.0.0.1"); message.Headers["user_agent"].Should().Be(DBNull.Value); } [Fact] public void AnEnabledTargetWithoutAName_OrTwoWithOneName_StopTheStart() { var unnamed = new IdentityAuditOptions { Targets = [new AuditTarget { Enabled = true, Uri = "kafka:audit?brokers=secret@host" }] }; var act = () => AuditTargetEnqueueProcessor.EnabledTargets(unnamed); act.Should().Throw() .WithMessage("*Identity:Audit:Targets:N:Name*") .Which.Message.Should().NotContain("secret", "only the scheme of the URI is named"); var twice = new IdentityAuditOptions { Targets = [ new AuditTarget { Name = "a", Enabled = true, Uri = "log:x" }, new AuditTarget { Name = "a", Enabled = true, Uri = "log:y" }, ], }; var dup = () => AuditTargetEnqueueProcessor.EnabledTargets(twice); dup.Should().Throw().WithMessage("*'a'*unique*"); // A disabled or unnamed-but-disabled target is not checked: it sends nothing. AuditTargetEnqueueProcessor.EnabledTargets(new IdentityAuditOptions { Targets = [new AuditTarget { Enabled = false, Uri = "log:z" }], }).Should().BeEmpty(); } private async Task RaiseAsync() { var name = "audit-outbox-" + Guid.NewGuid().ToString("N")[..12]; using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/groups") { Content = JsonContent.Create(new { name }) }; request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken); using var response = await _fx.Http.SendAsync(request); ((int)response.StatusCode).Should().BeInRange(200, 299, await response.Content.ReadAsStringAsync()); return name; } /// The events route runs on a wire tap: wait for the target's row of the event. private async Task WaitForRowAsync(string marker) { var deadline = DateTime.UtcNow.AddSeconds(10); while (true) { var ids = await _fx.UseRedbAsync(redb => redb.Context.QueryAsync( "SELECT id FROM identity_delivery_outbox WHERE kind = 'audit' AND destination = @p0 AND payload LIKE @p1", Target, "%" + marker + "%")); if (ids.Count > 0) return ids.Single().Id; if (DateTime.UtcNow > deadline) throw new TimeoutException("no audit outbox row for the event"); await Task.Delay(50); } } private async Task StateAsync(long id) => (await _fx.UseRedbAsync(redb => redb.Context.QueryAsync( "SELECT status, attempts, last_error FROM identity_delivery_outbox WHERE id = @p0", id))).Single(); private static async Task RunUntilAsync(WebhookDeliveryWorker worker, Func> done) { var deadline = DateTime.UtcNow.AddSeconds(10); while (!await done() && DateTime.UtcNow < deadline) { await worker.RunOnceAsync(); await worker.DrainAsync(); await Task.Delay(50); } } private sealed class IdRow { [System.Text.Json.Serialization.JsonPropertyName("id")] public long Id { get; set; } } private sealed class State { [System.Text.Json.Serialization.JsonPropertyName("status")] public string Status { get; set; } = ""; [System.Text.Json.Serialization.JsonPropertyName("attempts")] public int Attempts { get; set; } [System.Text.Json.Serialization.JsonPropertyName("last_error")] public string? LastError { get; set; } } }