Bundle: redb-identity / tests/redb.Identity.Tests (tests.redb.Identity.Tests.txt), 233 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-identity/_index.txt
====
Path: redb-identity/tests/redb.Identity.Tests/Architecture/HttpRouteReservedHeaderStripTests.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/Architecture/HttpRouteReservedHeaderStripTests.cs
----
using System.Text.RegularExpressions;
using AwesomeAssertions;
using Xunit;
namespace redb.Identity.Tests.Architecture;
///
/// Every HTTP route strips the reserved inbound headers before it does anything else.
///
/// The HTTP consumer copies every request header into the exchange verbatim, while processors downstream
/// trust a handful of names as if a facade had set them — session_user_id becomes the principal,
/// user_id / ip_address / user_agent sign the audit log. The facade's answer is
/// PropagateCorrelationId, whose first act is to remove those names, documented as "the first
/// processor on every HTTP route — so no route can forget it". It was a promise kept by hand: the
/// management catch-all (http-management-api) and the SCIM catch-all (http-scim-api)
/// never called it. Nothing on those two routes reads a reserved name today, so this was a structural
/// gap rather than an exploit — which is exactly why it needs a check: the next processor that reads
/// one there would have trusted whatever the caller sent.
///
///
/// Read from source, like the other fitness tests here: for each From(...) in the HTTP route
/// builder, the very first call after RouteId(...) must be the strip — whatever that call is,
/// not only a step from some list of DSL names, because a method the list does not know would otherwise
/// pass unseen in front of the strip. A route without a RouteId is an offender too: every route
/// here is named, and the supervisor's error attribution depends on it.
///
///
public class HttpRouteReservedHeaderStripTests
{
private const string Strip = "Process(HttpIdentityProcessors.PropagateCorrelationId)";
///
/// From the end of RouteId(...) to the start of the next fluent call: optional statement end,
/// optional receiver (route.), then the dot. What follows must be the strip.
///
private static readonly Regex NextCall = new(@"^\s*;?\s*(?:\w+\s*)?\.", RegexOptions.Compiled);
private static string LocateRouteBuilder()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null)
{
foreach (var candidate in new[]
{
Path.Combine(dir.FullName, "src", "redb.Identity.Http", "HttpFacadeRouteBuilder.cs"),
Path.Combine(dir.FullName, "redb.Identity", "src", "redb.Identity.Http", "HttpFacadeRouteBuilder.cs"),
})
{
if (File.Exists(candidate)) return candidate;
}
dir = dir.Parent;
}
throw new InvalidOperationException("Could not locate HttpFacadeRouteBuilder.cs from the test base directory.");
}
[Fact]
public void Every_http_route_strips_the_reserved_headers_first()
{
var source = File.ReadAllText(LocateRouteBuilder());
// Comments talk about From(...) and the strip constantly; only code counts.
source = Regex.Replace(source, @"/\*.*?\*/", string.Empty, RegexOptions.Singleline);
source = Regex.Replace(source, @"//.*?$", string.Empty, RegexOptions.Multiline);
var starts = Regex.Matches(source, @"\bFrom\(").Select(m => m.Index).ToList();
starts.Should().NotBeEmpty("the HTTP facade declares its routes in this file");
var offenders = new List();
for (var i = 0; i < starts.Count; i++)
{
var end = i + 1 < starts.Count ? starts[i + 1] : source.Length;
var route = source[starts[i]..end];
var routeIdCall = Regex.Match(route, @"\.RouteId\(([^)]*)\)");
if (!routeIdCall.Success)
{
offenders.Add(" " + route[..Math.Min(80, route.Length)].ReplaceLineEndings(" "));
continue;
}
var afterRouteId = route[(routeIdCall.Index + routeIdCall.Length)..];
var next = NextCall.Match(afterRouteId);
var stripsFirst = next.Success
&& afterRouteId.AsSpan(next.Length).StartsWith(Strip, StringComparison.Ordinal);
if (!stripsFirst)
offenders.Add(routeIdCall.Groups[1].Value);
}
// BeEmpty names only the first offender; the list is spelled out so a failure shows all of them.
offenders.Should().BeEmpty(
"every HTTP route must remove the caller-supplied reserved headers before any step can read them; "
+ "a route that skips it trusts whatever the caller sent for session_user_id, user_id, ip_address and "
+ "the rest. Routes without the strip first: {0}", string.Join(", ", offenders));
}
}
Path: redb-identity/tests/redb.Identity.Tests/Architecture/ReferenceTokenGuardTests.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/Architecture/ReferenceTokenGuardTests.cs
----
using System.Text.RegularExpressions;
using AwesomeAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OpenIddict.Server;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Architecture;
///
/// The resource side's entry check (ValidateTokenEntryStatusHandler) reads only the token's object row and does not
/// refuse an entry that carries a ReferenceId, as OpenIddict's built-in RestoreTokenEntryProperties does (a leaked
/// reference payload presented as a plain token). That is sound only while the server issues no reference access or
/// refresh tokens. These tests fail the day either is turned on.
///
[Collection("ProductionHttp")]
public class ReferenceTokenGuardTests
{
private const string Reason =
"reference access or refresh tokens are on: ValidateTokenEntryStatusHandler must then also refuse a token " +
"entry that carries a ReferenceId when the token was not validated as a reference token, as OpenIddict's " +
"RestoreTokenEntryProperties does";
private readonly ProductionHttpFixture _fx;
public ReferenceTokenGuardTests(ProductionHttpFixture fx) => _fx = fx;
[Fact]
public void The_server_issues_no_reference_access_or_refresh_tokens()
{
var options = _fx.ServiceProvider.GetRequiredService>().CurrentValue;
options.UseReferenceAccessTokens.Should().BeFalse(Reason);
options.UseReferenceRefreshTokens.Should().BeFalse(Reason);
}
[Fact]
public void No_source_turns_reference_tokens_on()
{
// The options check above sees the test host's configuration only; a switch behind a setting the tests do
// not set is caught here.
var root = LocateSourceRoot();
var sep = Path.DirectorySeparatorChar;
var pattern = new Regex(@"\b(UseReferenceAccessTokens|UseReferenceRefreshTokens)\b", RegexOptions.Compiled);
var offenders = Directory.EnumerateFiles(root, "*.cs", SearchOption.AllDirectories)
.Where(f => !f.Contains($"{sep}obj{sep}", StringComparison.Ordinal) && !f.Contains($"{sep}bin{sep}", StringComparison.Ordinal))
.Where(f => pattern.IsMatch(Regex.Replace(File.ReadAllText(f), @"//[^\n]*", string.Empty)))
.Select(f => Path.GetRelativePath(root, f))
.ToList();
offenders.Should().BeEmpty(Reason);
}
private static string LocateSourceRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null)
{
var candidate = Path.Combine(dir.FullName, "redb.Identity", "src");
if (Directory.Exists(Path.Combine(candidate, "redb.Identity.Core")))
return candidate;
candidate = Path.Combine(dir.FullName, "src");
if (Directory.Exists(Path.Combine(candidate, "redb.Identity.Core")))
return candidate;
dir = dir.Parent;
}
throw new InvalidOperationException("Could not locate redb.Identity/src from the test base directory.");
}
}
Path: redb-identity/tests/redb.Identity.Tests/Architecture/TokenStatusWriteTests.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/Architecture/TokenStatusWriteTests.cs
----
using System.Text.RegularExpressions;
using AwesomeAssertions;
using OpenIddict.Abstractions;
using redb.Core.Models.Entities;
using redb.Identity.Core.Models;
using redb.Identity.Core.Stores;
using Xunit;
namespace redb.Identity.Tests.Architecture;
///
/// A token's status is written only through , which keeps the object row's
/// value_bool in step with it; the resource side's entry check reads only that column. A status written past
/// the helper would leave the column stale and a revoked token accepted.
///
/// The scan is by text, so it fails closed: every .Props.Status = in the Identity sources outside the helper
/// has to be one of the known writes of another kind of object (sessions, authorizations), named by file and
/// variable below. A new write of a session or authorization status is added to that list; a write of a token's
/// status goes through the helper.
///
///
public class TokenStatusWriteTests
{
private static readonly string SourceRoot = LocateSourceRoot();
// file name -> variables whose Props.Status is written there and which are not tokens.
private static readonly Dictionary OtherObjectStatusWrites = new(StringComparer.Ordinal)
{
["SessionCleanupProcessor.cs"] = ["s"],
["ConsentService.cs"] = ["target"],
["SessionService.cs"] = ["s", "session", "auth"],
["RedbAuthorizationStore.cs"] = ["target", "authorization"],
};
private static readonly Regex StatusWrite = new(@"(?[\w\.\]\)]+?)\.Props\.Status\s*=(?![=>])", RegexOptions.Compiled);
private static readonly Regex TokenPropsInitializerStatus =
new(@"new\s+TokenProps\s*(\(\s*\))?\s*\{[^}]*\bStatus\s*=", RegexOptions.Compiled | RegexOptions.Singleline);
private static string LocateSourceRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null)
{
var candidate = Path.Combine(dir.FullName, "redb.Identity", "src");
if (Directory.Exists(Path.Combine(candidate, "redb.Identity.Core")))
return candidate;
candidate = Path.Combine(dir.FullName, "src");
if (Directory.Exists(Path.Combine(candidate, "redb.Identity.Core")))
return candidate;
dir = dir.Parent;
}
throw new InvalidOperationException("Could not locate redb.Identity/src from the test base directory.");
}
private static IEnumerable<(string Path, string Source)> Sources()
{
var sep = Path.DirectorySeparatorChar;
foreach (var file in Directory.EnumerateFiles(SourceRoot, "*.cs", SearchOption.AllDirectories))
{
if (file.Contains($"{sep}obj{sep}", StringComparison.Ordinal) || file.Contains($"{sep}bin{sep}", StringComparison.Ordinal))
continue;
var source = File.ReadAllText(file);
source = Regex.Replace(source, @"/\*.*?\*/", string.Empty, RegexOptions.Singleline);
source = Regex.Replace(source, @"//[^\n]*", string.Empty);
yield return (file, source);
}
}
[Fact]
public void A_token_status_is_written_only_through_the_helper()
{
var offenders = new List();
foreach (var (path, source) in Sources())
{
var name = Path.GetFileName(path);
if (name == "TokenStatus.cs")
continue;
OtherObjectStatusWrites.TryGetValue(name, out var allowed);
foreach (Match m in StatusWrite.Matches(source))
{
var target = m.Groups["target"].Value;
if (allowed is null || !allowed.Contains(target, StringComparer.Ordinal))
offenders.Add($"{Path.GetRelativePath(SourceRoot, path)}: {target}.Props.Status =");
}
if (TokenPropsInitializerStatus.IsMatch(source))
offenders.Add($"{Path.GetRelativePath(SourceRoot, path)}: new TokenProps {{ Status = ... }}");
}
offenders.Should().BeEmpty(
"a token's status is set with TokenStatus.Set, which keeps value_bool in step; a session or " +
"authorization status write is added to OtherObjectStatusWrites");
}
[Fact]
public void The_known_other_writes_still_exist()
{
// The list stays exact: an entry whose write is gone is removed, so the list cannot hide a later token write
// under an old name.
var seen = new HashSet(StringComparer.Ordinal);
foreach (var (path, source) in Sources())
{
var name = Path.GetFileName(path);
foreach (Match m in StatusWrite.Matches(source))
seen.Add(name + ":" + m.Groups["target"].Value);
}
foreach (var (file, variables) in OtherObjectStatusWrites)
foreach (var variable in variables)
seen.Should().Contain(file + ":" + variable);
}
[Theory]
[InlineData(OpenIddictConstants.Statuses.Valid, true)]
[InlineData(OpenIddictConstants.Statuses.Revoked, false)]
[InlineData(OpenIddictConstants.Statuses.Redeemed, false)]
[InlineData(OpenIddictConstants.Statuses.Inactive, false)]
[InlineData(OpenIddictConstants.Statuses.Rejected, false)]
[InlineData(null, false)]
public void The_helper_mirrors_valid_only(string? status, bool expected)
{
var token = new RedbObject(new TokenProps());
TokenStatus.Set(token, status);
token.Props.Status.Should().Be(status);
token.value_bool.Should().Be(expected);
}
}
Path: redb-identity/tests/redb.Identity.Tests/Architecture/TransportBoundaryTests.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/Architecture/TransportBoundaryTests.cs
----
using System.Text.RegularExpressions;
using AwesomeAssertions;
using Xunit;
using redb.Identity.Contracts.Routes;
namespace redb.Identity.Tests.Architecture;
///
/// Architectural fitness tests guarding the redb.Identity.Core transport boundary.
///
/// Identity servers live in the HTTP world by nature — the OAuth2 / OIDC / SCIM / RFC
/// specifications are defined in HTTP terms (status codes, content-types, headers), so an
/// HTTP vocabulary inside core is legitimate. What is NOT legitimate is wire-encoding
/// the response into string/byte[] directly in core: that locks the response into JSON and
/// breaks the gRPC / Kafka / MQTT facade adapters, which must be able to override the
/// native serialization.
///
///
/// These tests scan redb.Identity.Core source for forbidden assignments to
/// exchange.Out.Body. Domain JSON usage (PROPS column encoding, DataProtection blobs,
/// hashing, JsonElement composition) is allowed — only Body-targeted wire encoding is banned.
///
///
public class TransportBoundaryTests
{
private static readonly string CoreSourceRoot = LocateCoreSourceRoot();
private static string LocateCoreSourceRoot()
{
// Walk up from the test assembly location until we find redb.Identity.Core.
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null)
{
var candidate = Path.Combine(dir.FullName, "src", "redb.Identity.Core");
if (Directory.Exists(candidate))
return candidate;
// Also try repo-root layout: /redb.Identity/src/redb.Identity.Core
var repoCandidate = Path.Combine(dir.FullName, "redb.Identity", "src", "redb.Identity.Core");
if (Directory.Exists(repoCandidate))
return repoCandidate;
dir = dir.Parent;
}
throw new InvalidOperationException(
"Could not locate redb.Identity.Core source root from test base directory.");
}
private static IEnumerable<(string Path, string Source)> EnumerateCoreSources()
{
foreach (var file in Directory.EnumerateFiles(CoreSourceRoot, "*.cs", SearchOption.AllDirectories))
{
// Skip generated artefacts.
if (file.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
continue;
if (file.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
continue;
yield return (file, StripComments(File.ReadAllText(file)));
}
}
///
/// Strips line and block comments (including XML doc comments) so fitness regexes only
/// match real code, not commentary that legitimately mentions HTTP types or JSON encoding.
/// String literals are left in place — wire-encoding done via interpolated strings would
/// still surface as code.
///
private static string StripComments(string source)
{
// Block /* ... */
source = Regex.Replace(source, @"/\*.*?\*/", string.Empty, RegexOptions.Singleline);
// Line // ... and /// ...
source = Regex.Replace(source, @"//.*$", string.Empty, RegexOptions.Multiline);
return source;
}
[Fact]
public void CoreSource_DoesNotAssignSerializedJsonStringToOutBody()
{
// exchange.Out.Body = JsonSerializer.Serialize(...) ← forbidden (locks transport to JSON string).
// SerializeToElement / SerializeToNode / SerializeToUtf8Bytes are caught elsewhere or allowed.
var pattern = new Regex(
@"\.Out\.Body\s*=\s*JsonSerializer\.Serialize\b(?!ToElement|ToNode|ToUtf8Bytes)",
RegexOptions.Compiled);
var violations = new List();
foreach (var (path, source) in EnumerateCoreSources())
{
foreach (Match m in pattern.Matches(source))
{
var line = LineOf(source, m.Index);
violations.Add($"{path}:{line} -> {m.Value}");
}
}
violations.Should().BeEmpty(
"core processors must keep exchange.Out.Body as a typed object; wire-encoding to JSON " +
"string belongs to the transport facade or an explicit .Marshal(...) DSL step");
}
[Fact]
public void CoreSource_DoesNotAssignUtf8BytesToOutBody()
{
// exchange.Out.Body = JsonSerializer.SerializeToUtf8Bytes(...) ← forbidden (locks transport to JSON bytes).
var pattern = new Regex(
@"\.Out\.Body\s*=\s*JsonSerializer\.SerializeToUtf8Bytes\b",
RegexOptions.Compiled);
var violations = new List();
foreach (var (path, source) in EnumerateCoreSources())
{
foreach (Match m in pattern.Matches(source))
{
var line = LineOf(source, m.Index);
violations.Add($"{path}:{line} -> {m.Value}");
}
}
violations.Should().BeEmpty(
"core processors must keep exchange.Out.Body as a typed object; pre-encoding to UTF-8 " +
"bytes locks the response into a single wire format");
}
[Fact]
public void CoreSource_DoesNotReferenceAspNetCoreHttp()
{
// No HttpContext / IHttpContextAccessor leakage — transport is owned by facades.
var usingPattern = new Regex(
@"^\s*using\s+Microsoft\.AspNetCore\.Http\b",
RegexOptions.Compiled | RegexOptions.Multiline);
var typeRefPattern = new Regex(
@"\b(HttpContext|IHttpContextAccessor)\b",
RegexOptions.Compiled);
var violations = new List();
foreach (var (path, source) in EnumerateCoreSources())
{
foreach (Match m in usingPattern.Matches(source))
violations.Add($"{path}:{LineOf(source, m.Index)} -> {m.Value.Trim()}");
foreach (Match m in typeRefPattern.Matches(source))
violations.Add($"{path}:{LineOf(source, m.Index)} -> {m.Value}");
}
violations.Should().BeEmpty(
"redb.Identity.Core must not depend on Microsoft.AspNetCore.Http; HTTP-specific " +
"wiring belongs to redb.Identity.Http (or another facade)");
}
[Fact]
public void CoreSource_AuditEventTypeAssignments_UseCatalogConstants()
{
// H6/H7/H9: every identity-event-type must be sourced from
// (or a const ref to it).
// String literals are forbidden so the catalog stays the single source of truth and
// CategoryOf(...) keeps a closed switch.
// Pattern: exchange.Properties["identity-event-type"] = ""
var pattern = new Regex(
"Properties\\[\"identity-event-type\"\\]\\s*=\\s*\"[^\"]+\"",
RegexOptions.Compiled);
var violations = new List();
foreach (var (path, source) in EnumerateCoreSources())
{
foreach (Match m in pattern.Matches(source))
{
var line = LineOf(source, m.Index);
violations.Add($"{path}:{line} -> {m.Value}");
}
}
violations.Should().BeEmpty(
"audit event types must reference IdentityAuditEventIds.* constants; literal magic " +
"strings break the catalog/category contract and bypass downstream routing.");
}
private static int LineOf(string source, int index)
{
var line = 1;
for (var i = 0; i < index && i < source.Length; i++)
if (source[i] == '\n') line++;
return line;
}
}
Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditAmqpIntegrationTests.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/AuditAmqpIntegrationTests.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.Amqp;
using redb.Route.Components;
using redb.Route.Core;
using redb.Route.Processors;
using Xunit;
using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure;
namespace redb.Identity.Tests.Audit;
///
/// Integration tests for AMQP 1.0 audit target (ActiveMQ Artemis).
/// Requires Artemis at localhost:5673 (admin/admin).
///
public class AuditAmqpIntegrationTests : IAsyncLifetime
{
private const string PgConnString =
"Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true";
private const string AmqpHost = "localhost";
private const int AmqpPort = 5673;
private const string AmqpUser = "admin";
private const string AmqpPassword = "admin";
private readonly string _amqpQueue = $"identity-audit-{Guid.NewGuid():N}";
private string AmqpUri =>
"amqp://" + _amqpQueue + "?host=" + AmqpHost + "&port=" + AmqpPort
+ "&user=" + AmqpUser + "&password=" + AmqpPassword;
private ServiceProvider _sp = null!;
private RouteContext _ctx = null!;
public async Task InitializeAsync()
{
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 = "amqp-audit", Enabled = true, Uri = AmqpUri }
]
};
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-amqp-test");
_ctx.AddComponent(new AmqpComponent());
// 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> ReceiveMessages(int expected, int timeoutMs = 10000)
{
var uri = EndpointUriParser.Parse(AmqpUri);
var component = new AmqpComponent();
var endpoint = (AmqpEndpoint)component.CreateEndpoint(uri);
var results = new System.Collections.Concurrent.ConcurrentBag();
var allReceived = new TaskCompletionSource();
var processor = new DelegateProcessor(async (exchange, _) =>
{
var body = exchange.In.Body switch
{
byte[] bytes => Encoding.UTF8.GetString(bytes),
string s => s,
_ => exchange.In.Body?.ToString() ?? ""
};
results.Add(body);
if (results.Count >= expected)
allReceived.TrySetResult();
});
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();
}
[Fact]
public async Task DirectEventSend_PublishesToQueue()
{
var message = new redb.Route.Core.Message();
message.Headers["client_id"] = "amqp-test-client";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestAmqpDirect";
exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "amqp-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(1);
messages.Should().HaveCountGreaterThanOrEqualTo(1);
var evt = JsonSerializer.Deserialize(messages[0]);
evt.GetProperty("eventType").GetString().Should().Be("TestAmqpDirect");
}
[Fact]
public async Task MultipleEvents_AllPublished()
{
for (int i = 0; i < 3; i++)
{
var message = new redb.Route.Core.Message();
message.Headers["client_id"] = $"amqp-multi-{i}";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestAmqpMulti";
exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i };
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(3);
messages.Should().HaveCount(3);
}
[Fact]
public async Task EventMessage_ContainsIdentityEventPayload()
{
var message = new redb.Route.Core.Message();
message.Headers["client_id"] = "amqp-fields-client";
message.Headers["user_id"] = "user-66";
message.Headers["ip_address"] = "10.20.0.1";
message.Headers["user_agent"] = "AmqpTestAgent/1.0";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestAmqpFields";
exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "amqp-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(1);
messages.Should().HaveCountGreaterThanOrEqualTo(1);
var evt = JsonSerializer.Deserialize(messages[0]);
evt.GetProperty("eventType").GetString().Should().Be("TestAmqpFields");
evt.GetProperty("clientId").GetString().Should().Be("amqp-fields-client");
evt.GetProperty("userId").GetString().Should().Be("user-66");
evt.GetProperty("ipAddress").GetString().Should().Be("10.20.0.1");
evt.GetProperty("userAgent").GetString().Should().Be("AmqpTestAgent/1.0");
evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty();
}
}
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();
}
}
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();
}
}
Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditKafkaIntegrationTests.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/AuditKafkaIntegrationTests.cs
----
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using Confluent.Kafka;
using Confluent.Kafka.Admin;
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.Kafka;
using redb.Route.Processors;
using Xunit;
using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure;
namespace redb.Identity.Tests.Audit;
///
/// Integration tests for Kafka audit target.
/// Requires Kafka at localhost:29092.
///
public class AuditKafkaIntegrationTests : IAsyncLifetime
{
private const string PgConnString =
"Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true";
private const string KafkaBrokers = "localhost:29092";
private const string KafkaTopic = "identity-audit-test";
private const string KafkaUri =
"kafka://" + KafkaTopic + "?brokers=" + KafkaBrokers;
private ServiceProvider _sp = null!;
private RouteContext _ctx = null!;
public async Task InitializeAsync()
{
// Delete topic if exists (best-effort cleanup via Kafka AdminClient)
try
{
using var adminClient = new AdminClientBuilder(new AdminClientConfig { BootstrapServers = KafkaBrokers }).Build();
await adminClient.DeleteTopicsAsync([KafkaTopic]);
await Task.Delay(1000);
}
catch (DeleteTopicsException ex) when (ex.Results.All(r => r.Error.Code == ErrorCode.UnknownTopicOrPart))
{
// Expected on first run when the topic hasn't been created yet.
Console.Error.WriteLine($"Kafka DeleteTopics skipped (topic not yet created): {ex.Message}");
}
catch (Exception ex)
{
// Unexpected admin failures must remain visible \u2014 don't silently swallow.
Console.Error.WriteLine($"Kafka DeleteTopics failed: {ex.GetType().Name}: {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 = "kafka-audit", Enabled = true, Uri = KafkaUri }
]
};
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-kafka-test");
_ctx.AddComponent(new KafkaComponent());
// 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> ConsumeMessages(int expected, int timeoutMs = 15000)
{
var groupId = $"audit-verify-{Guid.NewGuid():N}";
var uri = EndpointUriParser.Parse(
$"kafka://{KafkaTopic}?brokers={KafkaBrokers}&groupId={groupId}&autoOffsetReset=Earliest");
var component = new KafkaComponent();
var endpoint = (KafkaEndpoint)component.CreateEndpoint(uri);
var results = new 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() ?? ""
};
results.Add(body);
if (results.Count >= expected)
allReceived.TrySetResult();
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();
}
[Fact]
public async Task DirectEventSend_PublishesToTopic()
{
var message = new Message();
message.Headers["client_id"] = "kafka-test-client";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestKafkaDirect";
exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "kafka-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 messages = await ConsumeMessages(1);
messages.Should().HaveCountGreaterThanOrEqualTo(1);
var evt = JsonSerializer.Deserialize(messages[0]);
evt.GetProperty("eventType").GetString().Should().Be("TestKafkaDirect");
}
[Fact]
public async Task MultipleEvents_AllPublished()
{
for (int i = 0; i < 3; i++)
{
var message = new Message();
message.Headers["client_id"] = $"kafka-multi-{i}";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestKafkaMulti";
exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i };
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events);
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(exchange);
exchange.Exception.Should().BeNull();
}
var messages = await ConsumeMessages(3);
messages.Should().HaveCount(3);
}
[Fact]
public async Task EventMessage_ContainsIdentityEventPayload()
{
var message = new Message();
message.Headers["client_id"] = "kafka-fields-client";
message.Headers["user_id"] = "user-88";
message.Headers["ip_address"] = "172.16.0.10";
message.Headers["user_agent"] = "KafkaTestAgent/1.0";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestKafkaFields";
exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "kafka-check" };
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events);
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(exchange);
exchange.Exception.Should().BeNull();
var messages = await ConsumeMessages(1);
messages.Should().HaveCountGreaterThanOrEqualTo(1);
var evt = JsonSerializer.Deserialize(messages[0]);
evt.GetProperty("eventType").GetString().Should().Be("TestKafkaFields");
evt.GetProperty("clientId").GetString().Should().Be("kafka-fields-client");
evt.GetProperty("userId").GetString().Should().Be("user-88");
evt.GetProperty("ipAddress").GetString().Should().Be("172.16.0.10");
evt.GetProperty("userAgent").GetString().Should().Be("KafkaTestAgent/1.0");
evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty();
}
}
Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditMqttIntegrationTests.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/AuditMqttIntegrationTests.cs
----
using System.Collections.Concurrent;
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 MQTTnet;
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.MqttNet;
using Xunit;
using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure;
namespace redb.Identity.Tests.Audit;
///
/// Integration tests for MQTT audit target.
/// Requires Mosquitto at localhost:11883.
///
public class AuditMqttIntegrationTests : IAsyncLifetime
{
private const string PgConnString =
"Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true";
private const string MqttServer = "localhost";
private const int MqttPort = 11883;
private const string MqttTopic = "identity/audit/test";
private static readonly string MqttUri =
"mqtt://" + MqttTopic + "?mode=Publish&server=" + MqttServer + "&port=" + MqttPort + "&qos=1";
private ServiceProvider _sp = null!;
private RouteContext _ctx = null!;
private IMqttClient _subscriber = null!;
private readonly ConcurrentBag _received = new();
private readonly SemaphoreSlim _signal = new(0);
public async Task InitializeAsync()
{
// Set up MQTT subscriber BEFORE sending events
var factory = new MqttClientFactory();
_subscriber = factory.CreateMqttClient();
var opts = new MqttClientOptionsBuilder()
.WithTcpServer(MqttServer, MqttPort)
.WithClientId($"audit-verify-{Guid.NewGuid():N}")
.Build();
_subscriber.ApplicationMessageReceivedAsync += args =>
{
var payload = args.ApplicationMessage.ConvertPayloadToString();
_received.Add(payload);
_signal.Release();
return Task.CompletedTask;
};
await _subscriber.ConnectAsync(opts);
await _subscriber.SubscribeAsync(MqttTopic);
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 = "mqtt-audit", Enabled = true, Uri = MqttUri }
]
};
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-mqtt-test");
_ctx.AddComponent(new MqttComponent());
// 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 (_subscriber is { IsConnected: true })
{
await _subscriber.UnsubscribeAsync(MqttTopic);
await _subscriber.DisconnectAsync();
}
_subscriber?.Dispose();
if (_sp != null) await _sp.DisposeAsync();
_signal.Dispose();
}
private async Task WaitForMessages(int count, int timeoutMs = 5000)
{
for (int i = 0; i < count; i++)
await _signal.WaitAsync(TimeSpan.FromMilliseconds(timeoutMs));
}
[Fact]
public async Task DirectEventSend_PublishesToTopic()
{
var message = new Message();
message.Headers["client_id"] = "mqtt-test-client";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestMqttDirect";
exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "mqtt-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 WaitForMessages(1);
_received.Should().HaveCountGreaterThanOrEqualTo(1);
var evt = JsonSerializer.Deserialize(_received.First());
evt.GetProperty("eventType").GetString().Should().Be("TestMqttDirect");
}
[Fact]
public async Task MultipleEvents_AllPublished()
{
for (int i = 0; i < 3; i++)
{
var message = new Message();
message.Headers["client_id"] = $"mqtt-multi-{i}";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestMqttMulti";
exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i };
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events);
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(exchange);
exchange.Exception.Should().BeNull();
}
await WaitForMessages(3);
_received.Should().HaveCount(3);
}
[Fact]
public async Task EventMessage_ContainsIdentityEventPayload()
{
var message = new Message();
message.Headers["client_id"] = "mqtt-fields-client";
message.Headers["user_id"] = "user-55";
message.Headers["ip_address"] = "192.168.10.5";
message.Headers["user_agent"] = "MqttTestAgent/1.0";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestMqttFields";
exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "mqtt-check" };
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events);
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(exchange);
exchange.Exception.Should().BeNull();
await WaitForMessages(1);
_received.Should().HaveCountGreaterThanOrEqualTo(1);
var evt = JsonSerializer.Deserialize(_received.First());
evt.GetProperty("eventType").GetString().Should().Be("TestMqttFields");
evt.GetProperty("clientId").GetString().Should().Be("mqtt-fields-client");
evt.GetProperty("userId").GetString().Should().Be("user-55");
evt.GetProperty("ipAddress").GetString().Should().Be("192.168.10.5");
evt.GetProperty("userAgent").GetString().Should().Be("MqttTestAgent/1.0");
evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty();
}
}
Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditRabbitMqIntegrationTests.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/AuditRabbitMqIntegrationTests.cs
----
using System.Net.Http.Headers;
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.RabbitMQ;
using Xunit;
using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure;
namespace redb.Identity.Tests.Audit;
///
/// Integration tests for RabbitMQ audit target.
/// Requires RabbitMQ at localhost:5672 (management at 15672, admin/admin).
///
public class AuditRabbitMqIntegrationTests : IAsyncLifetime
{
private const string PgConnString =
"Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true";
private const string RabbitQueue = "identity-audit-test";
private const string RabbitUri =
"rabbitmq://" + RabbitQueue
+ "?host=localhost&port=5672&username=admin&password=admin&declare=true";
private ServiceProvider _sp = null!;
private RouteContext _ctx = null!;
private readonly HttpClient _http = new();
public async Task InitializeAsync()
{
// Purge queue via management API (if exists)
_http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes("admin:admin")));
try
{
using var resp = await _http.DeleteAsync($"http://localhost:15672/api/queues/%2f/{RabbitQueue}/contents");
if (!resp.IsSuccessStatusCode && resp.StatusCode != System.Net.HttpStatusCode.NotFound)
{
Console.Error.WriteLine($"RabbitMQ queue purge returned {(int)resp.StatusCode}: {await resp.Content.ReadAsStringAsync()}");
}
}
catch (HttpRequestException ex)
{
Console.Error.WriteLine($"RabbitMQ queue purge failed (mgmt API 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 = "rabbitmq-audit", Enabled = true, Uri = RabbitUri }
]
};
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-rabbitmq-test");
_ctx.AddComponent(new RabbitMQComponent());
// 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();
_http.Dispose();
}
///
/// Get messages from queue via RabbitMQ Management API (non-destructive peek).
///
private async Task> GetQueueMessages(int count = 10)
{
var body = JsonSerializer.Serialize(new
{
count,
ackmode = "ack_requeue_false",
encoding = "auto"
});
var response = await _http.PostAsync(
$"http://localhost:15672/api/queues/%2f/{RabbitQueue}/get",
new StringContent(body, Encoding.UTF8, "application/json"));
if (!response.IsSuccessStatusCode) return [];
var json = await response.Content.ReadAsStringAsync();
var messages = JsonDocument.Parse(json).RootElement;
if (messages.ValueKind != JsonValueKind.Array) return [];
return messages.EnumerateArray().ToList();
}
/// Reads (and takes) the queue until it gave at least messages or 20 s passed.
private async Task> CollectQueueMessagesAsync(int atLeast)
{
var collected = new List();
var deadline = DateTime.UtcNow.AddSeconds(20);
while (collected.Count < atLeast && DateTime.UtcNow < deadline)
{
collected.AddRange(await GetQueueMessages());
if (collected.Count < atLeast) await Task.Delay(200);
}
return collected;
}
[Fact]
public async Task DirectEventSend_PublishesToQueue()
{
var message = new Message();
message.Headers["client_id"] = "rmq-test-client";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestRmqDirect";
exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "rmq-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 messages = await CollectQueueMessagesAsync(1); // the delivery worker sends the event (it polls every 2 s)
messages.Should().HaveCountGreaterThanOrEqualTo(1);
// Decode payload — it's base64 or raw string
var payload = messages[0].GetProperty("payload").GetString();
payload.Should().NotBeNullOrEmpty();
var evt = JsonSerializer.Deserialize(payload!);
evt.GetProperty("eventType").GetString().Should().Be("TestRmqDirect");
}
[Fact]
public async Task MultipleEvents_AllPublished()
{
for (int i = 0; i < 3; i++)
{
var message = new Message();
message.Headers["client_id"] = $"rmq-multi-{i}";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestRmqMulti";
exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i };
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events);
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(exchange);
exchange.Exception.Should().BeNull();
}
var messages = await CollectQueueMessagesAsync(3);
messages.Should().HaveCount(3);
}
[Fact]
public async Task EventMessage_ContainsIdentityEventPayload()
{
var message = new Message();
message.Headers["client_id"] = "rmq-fields-client";
message.Headers["user_id"] = "user-77";
message.Headers["ip_address"] = "192.168.1.50";
message.Headers["user_agent"] = "RmqTestAgent/2.0";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestRmqFields";
exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "rmq-check" };
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events);
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(exchange);
exchange.Exception.Should().BeNull();
var messages = await CollectQueueMessagesAsync(1);
messages.Should().HaveCountGreaterThanOrEqualTo(1);
var payload = messages[0].GetProperty("payload").GetString()!;
var evt = JsonSerializer.Deserialize(payload);
evt.GetProperty("eventType").GetString().Should().Be("TestRmqFields");
evt.GetProperty("clientId").GetString().Should().Be("rmq-fields-client");
evt.GetProperty("userId").GetString().Should().Be("user-77");
evt.GetProperty("ipAddress").GetString().Should().Be("192.168.1.50");
evt.GetProperty("userAgent").GetString().Should().Be("RmqTestAgent/2.0");
evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty();
}
}
Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditRedisIntegrationTests.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/AuditRedisIntegrationTests.cs
----
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.Redis;
using StackExchange.Redis;
using Xunit;
using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure;
namespace redb.Identity.Tests.Audit;
///
/// Integration tests for Redis audit target (LPUSH to a list).
/// Requires Redis at localhost:6379.
///
public class AuditRedisIntegrationTests : IAsyncLifetime
{
private const string PgConnString =
"Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true";
private const string RedisConnString = "localhost:6379";
private const string RedisKey = "identity-audit-test";
private const string RedisUri =
"redis:LPUSH:" + RedisKey + "?connectionString=" + RedisConnString;
private ServiceProvider _sp = null!;
private RouteContext _ctx = null!;
private ConnectionMultiplexer _redis = null!;
public async Task InitializeAsync()
{
_redis = await ConnectionMultiplexer.ConnectAsync(RedisConnString);
await _redis.GetDatabase().KeyDeleteAsync(RedisKey);
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 = "redis-audit", Enabled = true, Uri = RedisUri }
]
};
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-redis-test");
_ctx.AddComponent(new RedisComponent());
// 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();
if (_redis != null) await _redis.DisposeAsync();
}
[Fact]
public async Task DirectEventSend_PushesToList()
{
var message = new Message();
message.Headers["client_id"] = "redis-test-client";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestRedisDirect";
exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "redis-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 WaitForListAsync(1); // the delivery worker sends the event (it polls every 2 s)
var db = _redis.GetDatabase();
var length = await db.ListLengthAsync(RedisKey);
length.Should().BeGreaterThanOrEqualTo(1);
var value = await db.ListGetByIndexAsync(RedisKey, 0);
value.HasValue.Should().BeTrue();
var evt = JsonSerializer.Deserialize(value.ToString());
evt.GetProperty("eventType").GetString().Should().Be("TestRedisDirect");
}
private async Task WaitForListAsync(long atLeast)
{
var db = _redis.GetDatabase();
var deadline = DateTime.UtcNow.AddSeconds(15);
while (await db.ListLengthAsync(RedisKey) < atLeast && DateTime.UtcNow < deadline)
await Task.Delay(100);
}
[Fact]
public async Task MultipleEvents_AllPushed()
{
for (int i = 0; i < 3; i++)
{
var message = new Message();
message.Headers["client_id"] = $"redis-multi-{i}";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestRedisMulti";
exchange.Properties["identity-event-data"] = new Dictionary { ["idx"] = i };
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events);
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(exchange);
exchange.Exception.Should().BeNull();
}
await WaitForListAsync(3); // the delivery worker sends the event (it polls every 2 s)
var db = _redis.GetDatabase();
var length = await db.ListLengthAsync(RedisKey);
length.Should().Be(3);
}
[Fact]
public async Task EventMessage_ContainsIdentityEventPayload()
{
var message = new Message();
message.Headers["client_id"] = "redis-fields-client";
message.Headers["user_id"] = "user-99";
message.Headers["ip_address"] = "10.10.0.1";
message.Headers["user_agent"] = "RedisTestAgent/1.0";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestRedisFields";
exchange.Properties["identity-event-data"] = new Dictionary { ["action"] = "redis-check" };
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events);
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(exchange);
exchange.Exception.Should().BeNull();
await WaitForListAsync(1); // the delivery worker sends the event (it polls every 2 s)
var db = _redis.GetDatabase();
var value = await db.ListGetByIndexAsync(RedisKey, 0);
value.HasValue.Should().BeTrue();
var evt = JsonSerializer.Deserialize(value.ToString());
evt.GetProperty("eventType").GetString().Should().Be("TestRedisFields");
evt.GetProperty("clientId").GetString().Should().Be("redis-fields-client");
evt.GetProperty("userId").GetString().Should().Be("user-99");
evt.GetProperty("ipAddress").GetString().Should().Be("10.10.0.1");
evt.GetProperty("userAgent").GetString().Should().Be("RedisTestAgent/1.0");
evt.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty();
}
}
Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditSqlIntegrationTests.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/AuditSqlIntegrationTests.cs
----
using System.Data.Common;
using AwesomeAssertions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Npgsql;
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.Contracts.Scopes;
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.Sql;
using redb.Route.Sql.Connection;
using Xunit;
using redb.Identity.Core.Routes;using redb.Identity.Tests.Infrastructure;
namespace redb.Identity.Tests.Audit;
///
/// Integration tests for the audit multicast subsystem.
/// Uses real PostgreSQL with the identity_audit_log table.
///
public class AuditSqlIntegrationTests : IAsyncLifetime
{
private const string PgConnString =
"Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Include Error Detail=true";
private const string SqlInsertUri =
"sql:INSERT INTO identity_audit_log(event_id, event_type, \"timestamp\", user_id, client_id, ip_address, user_agent, details) "
+ "VALUES(:#event_id, :#event_type, :#timestamp, :#user_id, :#client_id, :#ip_address, :#user_agent, :#details::jsonb)"
+ "?dataSource=identity-audit-pg&outputType=None"
+ "¶m.event_id=${header.event_id}"
+ "¶m.event_type=${header.event_type}"
+ "¶m.timestamp=${header.timestamp}"
+ "¶m.user_id=${header.user_id}"
+ "¶m.client_id=${header.client_id}"
+ "¶m.ip_address=${header.ip_address}"
+ "¶m.user_agent=${header.user_agent}"
+ "¶m.details=${header.details}";
// The database the audit table is created in, written to and read back from: the configured one.
private string _cs = PgConnString;
private ServiceProvider _sp = null!;
private RouteContext _ctx = null!;
private ProducerTemplate _producer = null!;
public async Task InitializeAsync()
{
DbProviderFactories.RegisterFactory("Npgsql", NpgsqlFactory.Instance);
var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var cs = _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 = "pg-audit",
Enabled = true,
Uri = SqlInsertUri
}
]
};
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();
// Clean audit table before tests (create if missing — keeps tests
// self-contained on a freshly seeded dev DB).
await using (var conn = new NpgsqlConnection(cs))
{
await conn.OpenAsync();
await using var cmd = conn.CreateCommand();
cmd.CommandText = @"
CREATE TABLE IF NOT EXISTS identity_audit_log (
id BIGSERIAL PRIMARY KEY,
event_id UUID NOT NULL,
event_type VARCHAR(100) NOT NULL,
""timestamp"" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
user_id VARCHAR(50),
client_id VARCHAR(200),
ip_address VARCHAR(50),
user_agent VARCHAR(500),
details JSONB,
CONSTRAINT uq_audit_event_id UNIQUE (event_id)
);
DELETE FROM identity_audit_log;";
await cmd.ExecuteNonQueryAsync();
}
_ctx = new RouteContext(_sp, "audit-integration-test");
_ctx.AddComponent(new SqlComponent());
_ctx.AddToRegistry("identity-audit-pg", (ISqlConnectionFactory)new SqlConnectionFactory(
new SqlConnectionOptions
{
ConnectionString = cs,
ProviderName = "Npgsql"
}));
// 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();
_producer = new ProducerTemplate(_ctx);
_producer.Start();
}
public async Task DisposeAsync()
{
_producer?.Stop();
if (_ctx != null) await _ctx.Stop();
if (_sp != null) await _sp.DisposeAsync();
}
private async Task SendScope(string operation, object body)
{
var message = new Message { Body = body };
message.Headers["operation"] = operation;
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOut };
ManagementCallerContext.Apply(exchange, ManagementCaller.Admin); // playing the facade, see ManagementCaller
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.ManageScopes);
var producer = endpoint.CreateProducer();
await producer.Process(exchange);
return exchange;
}
private async Task>> WaitForAuditRows(string eventType, int atLeast)
{
var deadline = DateTime.UtcNow.AddSeconds(15);
while (true)
{
var rows = await QueryAuditRows(eventType);
if (rows.Count >= atLeast || DateTime.UtcNow > deadline) return rows;
await Task.Delay(200);
}
}
private async Task>> QueryAuditRows(string? eventType = null)
{
await using var conn = new NpgsqlConnection(_cs);
await conn.OpenAsync();
var sql = "SELECT event_id, event_type, \"timestamp\", user_id, client_id, ip_address, user_agent, details::text FROM identity_audit_log";
if (eventType is not null)
{
sql += " WHERE event_type = @et";
}
sql += " ORDER BY id";
await using var cmd = new NpgsqlCommand(sql, conn);
if (eventType is not null)
cmd.Parameters.AddWithValue("et", eventType);
await using var reader = await cmd.ExecuteReaderAsync();
var rows = new List>();
while (await reader.ReadAsync())
{
var row = new Dictionary();
for (int i = 0; i < reader.FieldCount; i++)
row[reader.GetName(i)] = reader.IsDBNull(i) ? null : reader.GetValue(i);
rows.Add(row);
}
return rows;
}
[Fact]
public async Task BareSql_InsertAuditRow()
{
// Bypass Events route entirely — send directly to the SQL endpoint
var sqlEndpoint = _ctx.GetEndpoint(SqlInsertUri);
var sqlProducer = sqlEndpoint.CreateProducer();
await sqlProducer.Start();
var msg = new Message();
msg.Body = "{}"; // JSON body
msg.Headers["event_id"] = Guid.NewGuid();
msg.Headers["event_type"] = "BareSqlTest";
msg.Headers["timestamp"] = DateTimeOffset.UtcNow;
msg.Headers["user_id"] = DBNull.Value;
msg.Headers["client_id"] = "bare-client";
msg.Headers["ip_address"] = DBNull.Value;
msg.Headers["user_agent"] = DBNull.Value;
msg.Headers["details"] = "{}";
var exchange = new Exchange(msg) { Pattern = ExchangePattern.InOnly };
await sqlProducer.Process(exchange);
exchange.Exception.Should().BeNull("SQL INSERT should succeed: {0}", exchange.Exception?.Message);
var rows = await QueryAuditRows("BareSqlTest");
rows.Should().ContainSingle();
}
[Fact]
public async Task DirectEventSend_WritesAuditRow()
{
// Send directly to the Events endpoint, bypassing WireTap
var message = new Message();
message.Headers["client_id"] = "direct-test-client";
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestDirect";
exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "direct" };
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events);
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(exchange);
// Check that the processor ran: In should have the headers after Out→In merge
exchange.In.Headers.Should().ContainKey("event_type", "EventDispatchProcessor should set Out headers which get merged to In");
exchange.Exception.Should().BeNull("Events route should not throw: {0}", exchange.Exception?.ToString());
// The target is sent by the delivery worker (it polls every 2 s), not by the events route.
var rows = await WaitForAuditRows("TestDirect", 1);
rows.Should().ContainSingle();
rows[0]["event_type"].Should().Be("TestDirect");
rows[0]["client_id"].Should().Be("direct-test-client");
}
[Fact]
public async Task ScopeCreated_WritesAuditRow()
{
var scopeName = "audit-create-" + Guid.NewGuid().ToString("N")[..8];
var exchange = await SendScope("create",
new CreateScopeRequest { Name = scopeName, DisplayName = "Audit Test" });
exchange.Exception.Should().BeNull();
// WireTap, then the delivery worker: wait for the row.
var rows = await WaitForAuditRows("ScopeCreated", 1);
rows.Should().HaveCountGreaterThanOrEqualTo(1);
rows.Last()["event_type"].Should().Be("ScopeCreated");
rows.Last()["event_id"].Should().NotBeNull();
}
[Fact]
public async Task Event_NullFields_WrittenAsDbNull()
{
// Send event without user_id or client_id — verify nulls in DB
var message = new Message();
// No user_id or client_id headers
var exchange = new Exchange(message) { Pattern = ExchangePattern.InOnly };
exchange.Properties["identity-event-type"] = "TestNullFields";
exchange.Properties["identity-event-data"] = new Dictionary { ["info"] = "nulls" };
var endpoint = _ctx.GetEndpoint(IdentityEndpoints.Events);
var producer = endpoint.CreateProducer();
await producer.Start();
await producer.Process(exchange);
exchange.Exception.Should().BeNull();
var rows = await WaitForAuditRows("TestNullFields", 1);
rows.Should().ContainSingle();
rows[0]["user_id"].Should().BeNull();
rows[0]["client_id"].Should().BeNull();
rows[0]["ip_address"].Should().BeNull();
rows[0]["user_agent"].Should().BeNull();
}
[Fact]
public async Task AuditRow_ContainsEventIdAndTimestamp()
{
var scopeName = "audit-ts-" + Guid.NewGuid().ToString("N")[..8];
var before = DateTimeOffset.UtcNow.AddSeconds(-1);
var exchange = await SendScope("create",
new CreateScopeRequest { Name = scopeName, DisplayName = "TS Test" });
exchange.Exception.Should().BeNull();
var rows = await WaitForAuditRows("ScopeCreated", 1);
rows.Should().HaveCountGreaterThanOrEqualTo(1);
var row = rows.Last();
row["event_id"].Should().NotBeNull();
var rawTs = row["timestamp"];
var ts = rawTs is DateTimeOffset dto ? dto : new DateTimeOffset((DateTime)rawTs!);
ts.Should().BeAfter(before);
}
[Fact]
public async Task MultipleEvents_AllWritten()
{
// Clean slate for this test
await using (var conn = new NpgsqlConnection(_cs))
{
await conn.OpenAsync();
await using var cmd = conn.CreateCommand();
cmd.CommandText = "DELETE FROM identity_audit_log";
await cmd.ExecuteNonQueryAsync();
}
// Create 3 scopes → 3 ScopeCreated events
for (int i = 0; i < 3; i++)
{
var exchange = await SendScope("create",
new CreateScopeRequest
{
Name = $"audit-multi-{i}-{Guid.NewGuid():N}"[..30],
DisplayName = $"Multi {i}"
});
exchange.Exception.Should().BeNull();
}
// WireTap is fire-and-forget — then the delivery worker: poll until all 3 rows appear (up to 15 s)
List> rows = [];
for (var attempt = 0; attempt < 30; attempt++)
{
await Task.Delay(500);
rows = await QueryAuditRows("ScopeCreated");
if (rows.Count >= 3) break;
}
rows.Should().HaveCount(3);
// All event_ids should be unique
var eventIds = rows.Select(r => r["event_id"]).ToHashSet();
eventIds.Should().HaveCount(3);
}
}
Path: redb-identity/tests/redb.Identity.Tests/Audit/AuditTargetCarriesNoRequestHeadersTests.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/AuditTargetCarriesNoRequestHeadersTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using AwesomeAssertions;
using redb.Identity.Tests.Infrastructure;
using Xunit;
using Xunit.Abstractions;
namespace redb.Identity.Tests.Audit;
///
/// An audit target receives the event and its own headers, never the request that raised it. Events are
/// raised on a WireTap copy of the request exchange; up to 4.5.0 that copy's headers (client_secret and the
/// other form fields, Authorization, Host, redbHttp.*) travelled on to every audit target.
///
[Collection("ProductionHttp")]
public sealed class AuditTargetCarriesNoRequestHeadersTests
{
private static readonly string[] EventHeaders =
["event-type", "event_id", "event_type", "timestamp", "user_id", "client_id", "ip_address", "user_agent", "details"];
private readonly ProductionHttpFixture _fx;
private readonly ITestOutputHelper _output;
public AuditTargetCarriesNoRequestHeadersTests(ProductionHttpFixture fx, ITestOutputHelper output)
{
_fx = fx;
_output = output;
}
[Fact]
public async Task TokenRequest_EventAtTheTarget_CarriesNoSecretNoTokenNoRequestHeaders()
{
using var response = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary
{
["grant_type"] = "client_credentials",
["client_id"] = ProductionHttpFixture.TestClientId,
["client_secret"] = ProductionHttpFixture.TestClientSecret,
}));
var body = await response.Content.ReadAsStringAsync();
response.StatusCode.Should().Be(HttpStatusCode.OK, "token: {0}", body);
var accessToken = JsonDocument.Parse(body).RootElement.GetProperty("access_token").GetString()!;
var message = await WaitForAsync(m =>
Equals(m.Headers.GetValueOrDefault("event_type"), "TokenIssued")
&& Equals(m.Headers.GetValueOrDefault("client_id"), ProductionHttpFixture.TestClientId));
AssertClean(message, ProductionHttpFixture.TestClientSecret, accessToken);
}
[Fact]
public async Task BearerCall_EventAtTheTarget_CarriesNoAuthorization()
{
var groupName = "audit-leak-" + Guid.NewGuid().ToString("N")[..8];
using var request = new HttpRequestMessage(HttpMethod.Post, "/api/v1/identity/groups")
{
Content = JsonContent.Create(new { name = groupName }),
};
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken);
using var response = await _fx.Http.SendAsync(request);
response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync());
var message = await WaitForAsync(m => m.Body.Contains(groupName));
AssertClean(message, ProductionHttpFixture.TestMgmtSecret, _fx.ManagementToken);
// The group's name is in the event details and in the call's answer alike: the body must be the event.
JsonDocument.Parse(message.Body).RootElement.GetProperty("eventType").GetString().Should().NotBeNullOrEmpty();
}
[Fact]
public async Task ManagementRoute_EventAtTheTarget_IsTheEventNotTheResponse()
{
// A startup route of a consumer module, in process: attach a scope to a role, then read the role's
// scopes on the same exchange. Both calls answer with a body (a status, a list of scopes); the
// target must get the RoleScopeAttached event, never those answers.
var suffix = Guid.NewGuid().ToString("N")[..8];
var (roleId, scopeId) = await _fx.UseRedbAsync(async redb =>
{
var svc = new redb.Identity.Core.Services.RoleService(redb);
var role = await svc.CreateRoleAsync("audit-body-" + suffix, "organization", applicationId: null,
displayName: null, description: null);
var scope = new redb.Core.Models.Entities.RedbObject(
new redb.Identity.Core.Models.ScopeProps { ScopeName = "audit-body-" + suffix, Description = "Audit body scope" })
{ Name = "audit-body-" + suffix };
await redb.SaveAsync(scope);
return (role.Id, scope.Id);
});
var message = new redb.Route.Core.Message { Body = new Dictionary { ["roleId"] = roleId, ["scopeId"] = scopeId } };
message.Headers["operation"] = "attach-scope";
var exchange = new redb.Route.Core.Exchange(message) { Pattern = redb.Route.Abstractions.ExchangePattern.InOut };
ManagementCallerContext.Apply(exchange, ManagementCaller.Admin);
await _fx.Producer.SendAsync(redb.Identity.Contracts.Routes.IdentityEndpoints.ManageRoles, exchange);
exchange.Exception.Should().BeNull();
exchange.In = new redb.Route.Core.Message { Body = new Dictionary { ["roleId"] = roleId } };
exchange.In.Headers["operation"] = "list-scopes";
exchange.Out = null;
await _fx.Producer.SendAsync(redb.Identity.Contracts.Routes.IdentityEndpoints.ManageRoles, exchange);
exchange.Exception.Should().BeNull();
var roleMarker = "\"RoleId\":" + roleId + ",";
await WaitForAsync(m => (m.Headers.GetValueOrDefault("details")?.ToString() ?? "").Contains(roleMarker));
await Task.Delay(1500); // the second call's tap, if it raised one, lands shortly after
await _fx.DeliverOutboxAsync();
var forRole = _fx.AuditTargetMessages
.Where(m => (m.Headers.GetValueOrDefault("details")?.ToString() ?? "").Contains(roleMarker))
.ToList();
// The read on the same exchange raises nothing: the attach is reported once, not again by list-scopes.
forRole.Should().ContainSingle(m => Equals(m.Headers.GetValueOrDefault("event_type"), "RoleScopeAttached"));
forRole.Should().HaveCount(1);
foreach (var m in forRole)
{
_output.WriteLine("body: " + m.Body);
var body = JsonDocument.Parse(m.Body).RootElement;
body.ValueKind.Should().Be(JsonValueKind.Object, "the target gets the event, not the call's answer: {0}", m.Body);
body.GetProperty("eventType").GetString().Should().Be(m.Headers["event_type"]!.ToString());
body.GetProperty("eventId").GetString().Should().NotBeNullOrEmpty();
m.Body.Should().NotContain("scopeName").And.NotContain("success");
}
}
[Fact]
public async Task ManagementRead_RaisesNoEvent_AndItsAnswerReachesNoTarget()
{
// Every management operation passes the route's WireTap, reads included. A read raises no event,
// and its answer (here the role's scopes) must not be delivered to the audit targets.
var suffix = Guid.NewGuid().ToString("N")[..8];
var scopeName = "audit-read-" + suffix;
var roleId = await _fx.UseRedbAsync(async redb =>
{
var svc = new redb.Identity.Core.Services.RoleService(redb);
var role = await svc.CreateRoleAsync("audit-read-" + suffix, "organization", applicationId: null,
displayName: null, description: null);
var scope = new redb.Core.Models.Entities.RedbObject(
new redb.Identity.Core.Models.ScopeProps { ScopeName = scopeName }) { Name = scopeName };
await redb.SaveAsync(scope);
await svc.AttachScopeAsync(role.Id, scope.Id, actingUserId: null);
return role.Id;
});
var message = new redb.Route.Core.Message { Body = new Dictionary { ["roleId"] = roleId } };
message.Headers["operation"] = "list-scopes";
var exchange = new redb.Route.Core.Exchange(message) { Pattern = redb.Route.Abstractions.ExchangePattern.InOut };
ManagementCallerContext.Apply(exchange, ManagementCaller.Admin);
await _fx.Producer.SendAsync(redb.Identity.Contracts.Routes.IdentityEndpoints.ManageRoles, exchange);
exchange.Exception.Should().BeNull();
((exchange.Out ?? exchange.In).Body?.ToString() ?? "").Should().NotBeNull();
await Task.Delay(1500); // the tap is fire-and-forget
await _fx.DeliverOutboxAsync();
_fx.AuditTargetMessages.Should().NotContain(m => m.Body.Contains(scopeName),
"a read raises no event and its answer goes nowhere");
}
private void AssertClean((Dictionary Headers, string Body) message, string secret, string token)
{
_output.WriteLine("headers: " + string.Join(", ", message.Headers.Keys));
message.Headers.Keys.Should().BeSubsetOf(EventHeaders.Append("Content-Type"),
"an audit target gets the event headers only");
message.Headers.Keys.Should().NotContain(k => k.StartsWith("redbHttp.", StringComparison.OrdinalIgnoreCase));
foreach (var value in message.Headers.Values)
{
var text = value?.ToString() ?? string.Empty;
text.Should().NotContain(secret);
text.Should().NotContain(token);
}
message.Body.Should().NotContain(secret).And.NotContain(token);
}
private async Task<(Dictionary Headers, string Body)> WaitForAsync(
Func<(Dictionary Headers, string Body), bool> match)
{
var deadline = DateTime.UtcNow.AddSeconds(15);
while (DateTime.UtcNow < deadline)
{
await _fx.DeliverOutboxAsync();
foreach (var m in _fx.AuditTargetMessages)
if (match(m))
return m;
await Task.Delay(100);
}
throw new TimeoutException("the audit target did not receive the expected event");
}
}
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; }
}
}
Path: redb-identity/tests/redb.Identity.Tests/Authorization/AdminEndpointAuthMatrixTests.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/Authorization/AdminEndpointAuthMatrixTests.cs
----
using System.Net;
using System.Net.Http.Headers;
using AwesomeAssertions;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.Authorization;
///
/// G14 — endpoint-matrix smoke for management-API authorization.
///
/// The HTTP facade routes management endpoints through
/// ManagementBearerAuthProcessor which requires a bearer access token whose
/// scopes intersect { identity:manage, identity:account, scim } (see
/// ProductionHttpFixture.InitializeAsync wiring). This test asserts the
/// invariant per endpoint:
///
/// no token → 401 (cannot enumerate without an access token);
/// token without the required scope → 403 (e.g. scim token on
/// management routes, or identity:manage token on SCIM routes);
/// token with the right scope → 2xx.
///
///
///
/// Without this matrix, a refactor that drops ManagementBearerAuthProcessor
/// from a single endpoint would silently expose admin operations to unauthenticated
/// callers — exactly the IDOR-shaped regression that G14 / B8 aims to lock down.
///
///
[Collection("ProductionHttp")]
public sealed class AdminEndpointAuthMatrixTests
{
private readonly ProductionHttpFixture _fx;
public AdminEndpointAuthMatrixTests(ProductionHttpFixture fx) => _fx = fx;
/// Endpoints requiring identity:manage (or identity:account when self-scoped).
public static IEnumerable