Path: redb-identity/tests/redb.Identity.Tests/FullStack/AuditActorTests.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/FullStack/AuditActorTests.cs
----
using Microsoft.Extensions.DependencyInjection;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
using AwesomeAssertions;
using redb.Identity.Tests.Infrastructure;
using Xunit;
namespace redb.Identity.Tests.FullStack;
///
/// An audit row of a change made through the management or account API records who made it: the client of the
/// access token in client_id, the token's subject in actor_subject (the client id for a
/// client-credentials token, the user's public subject for a user token), and the caller's address.
///
[Collection("ProductionHttp")]
public class AuditActorTests
{
private readonly ProductionHttpFixture _fx;
public AuditActorTests(ProductionHttpFixture fx) => _fx = fx;
private sealed class Row
{
[JsonPropertyName("client_id")] public string? ClientId { get; set; }
[JsonPropertyName("actor_subject")] public string? ActorSubject { get; set; }
[JsonPropertyName("ip_address")] public string? IpAddress { get; set; }
[JsonPropertyName("details")] public string? Details { get; set; }
}
/// The audit write runs on a WireTap after the answer, so the row is polled for.
private async Task AuditRowAsync(string eventType, string detailsContains)
{
for (var i = 0; i < 50; i++)
{
var rows = await _fx.UseRedbAsync(redb => redb.Context.QueryAsync(
"SELECT client_id, actor_subject, ip_address, details FROM identity_audit_log WHERE event_type = @p0",
eventType));
var row = rows.FirstOrDefault(r => r.Details?.Contains(detailsContains, StringComparison.Ordinal) == true);
if (row is not null) return row;
await Task.Delay(100);
}
throw new InvalidOperationException($"No {eventType} audit row containing '{detailsContains}'.");
}
private async Task SendAsync(string token, HttpMethod method, string path, object body)
{
using var request = new HttpRequestMessage(method, path) { Content = JsonContent.Create(body) };
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
using var response = await _fx.Http.SendAsync(request);
var text = await response.Content.ReadAsStringAsync();
((int)response.StatusCode).Should().BeInRange(200, 299, $"{method} {path}: {text}");
return text.Length == 0 ? default : JsonDocument.Parse(text).RootElement.Clone();
}
[Fact]
public async Task A_management_change_records_the_acting_client_and_subject()
{
var clientId = "audit-actor-" + Guid.NewGuid().ToString("N")[..10];
await SendAsync(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/applications", new
{
clientId, clientSecret = "audit-actor-secret-1234", clientType = "confidential", displayName = clientId,
});
var row = await AuditRowAsync("ClientRegistered", clientId);
row.ClientId.Should().Be(ProductionHttpFixture.TestMgmtClientId);
row.ActorSubject.Should().Be(ProductionHttpFixture.TestMgmtClientId, "a client-credentials token's subject is the client");
row.IpAddress.Should().NotBeNullOrEmpty();
// The audit API answers the field (optional: absent for other events and for older rows).
using var query = new HttpRequestMessage(HttpMethod.Get, "/api/v1/identity/audit?eventType=ClientRegistered&count=50");
query.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _fx.ManagementToken);
using var answer = await _fx.Http.SendAsync(query);
var text = await answer.Content.ReadAsStringAsync();
answer.StatusCode.Should().Be(HttpStatusCode.OK, text);
var item = JsonDocument.Parse(text).RootElement.GetProperty("items").EnumerateArray()
.First(i => i.GetRawText().Contains(clientId, StringComparison.Ordinal));
item.GetProperty("actorSubject").GetString().Should().Be(ProductionHttpFixture.TestMgmtClientId);
}
[Fact]
public async Task An_account_change_records_the_users_public_subject_not_an_internal_id()
{
var login = "auditactor" + Guid.NewGuid().ToString("N")[..10];
var user = await SendAsync(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/users",
new { login, password = "Str0ng!Passw0rd", displayName = login });
var internalId = user.GetProperty("id").GetInt64();
var clientId = login + "-client";
const string secret = "audit-actor-client-secret-1234";
await SendAsync(_fx.ManagementToken, HttpMethod.Post, "/api/v1/identity/applications", new
{
clientId, clientSecret = secret, displayName = clientId,
permissions = new[] { "ept:token", "gt:password", "scp:openid", "scp:identity:account" },
});
using var tokenResponse = await _fx.Http.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary
{
["grant_type"] = "password", ["username"] = login, ["password"] = "Str0ng!Passw0rd",
["scope"] = "openid identity:account", ["client_id"] = clientId, ["client_secret"] = secret,
}));
var tokenBody = await tokenResponse.Content.ReadAsStringAsync();
tokenResponse.StatusCode.Should().Be(HttpStatusCode.OK, tokenBody);
var token = JsonDocument.Parse(tokenBody).RootElement.GetProperty("access_token").GetString()!;
var subject = JsonDocument.Parse(Microsoft.IdentityModel.Tokens.Base64UrlEncoder.Decode(token.Split('.')[1]))
.RootElement.GetProperty("sub").GetString()!;
await SendAsync(token, HttpMethod.Put, "/api/v1/identity/me/password",
new { oldPassword = "Str0ng!Passw0rd", newPassword = "N3w!Str0ngPassw0rd" });
var row = await AuditRowAsync("PasswordChanged", login);
row.ClientId.Should().Be(clientId);
row.ActorSubject.Should().Be(subject).And.NotBe(internalId.ToString(System.Globalization.CultureInfo.InvariantCulture));
Guid.TryParse(row.ActorSubject, out _).Should().BeTrue("the public subject is a GUID");
row.IpAddress.Should().NotBeNullOrEmpty();
}
///
/// A table of an earlier version gains actor_subject at start, and the step is safe to run again, as a
/// second node starting later (or at once) does. Run against a scratch table of the old shape with the exact
/// statement of this provider's script; SQLite, which has no ADD COLUMN IF NOT EXISTS, through the listener's
/// own step.
///
[Fact]
public async Task The_actor_subject_column_is_added_to_an_older_table_and_the_step_can_run_again()
{
var table = "audit_probe_" + Guid.NewGuid().ToString("N")[..10];
var provider = _fx.ServiceProvider.GetRequiredService().ProviderName ?? "";
await _fx.UseRedbAsync(async redb =>
{
await redb.Context.ExecuteAsync($"CREATE TABLE {table} (id BIGINT, client_id VARCHAR(200))");
try
{
for (var run = 0; run < 2; run++)
{
if (provider.Equals("Sqlite", StringComparison.OrdinalIgnoreCase))
{
await global::redb.Identity.Core.Module.IdentityAuditLogTableInitListener.AddSqliteColumnAsync(redb, table, "actor_subject", "TEXT");
}
else
{
var isPg = provider.Equals("PostgreSQL", StringComparison.OrdinalIgnoreCase);
var script = global::redb.Identity.Core.Module.IdentityAuditLogTableInitListener.ReadEmbedded(isPg
? "redb.Identity.Core.sql.audit.pg_create_table.sql"
: "redb.Identity.Core.sql.audit.mssql_create_table.sql")!;
string statement;
if (isPg)
{
statement = script.Split('\n').Single(l => l.Contains("ADD COLUMN IF NOT EXISTS actor_subject")).Trim();
}
else
{
var start = script.IndexOf("IF NOT EXISTS (SELECT 1 FROM sys.columns", script.IndexOf("-- actor_subject:", StringComparison.Ordinal), StringComparison.Ordinal);
var end = script.IndexOf("END;", start, StringComparison.Ordinal) + "END;".Length;
statement = script[start..end];
}
await redb.Context.ExecuteAsync(statement.Replace("identity_audit_log", table, StringComparison.Ordinal));
}
}
// The column is there exactly once and takes a value.
await redb.Context.ExecuteAsync($"INSERT INTO {table} (id, client_id, actor_subject) VALUES (1, 'c', 's')");
(await redb.Context.ExecuteScalarAsync($"SELECT COUNT(*) FROM {table} WHERE actor_subject = 's'")).Should().Be(1);
}
finally
{
await redb.Context.ExecuteAsync($"DROP TABLE {table}");
}
return 0;
});
}
}