feat(audit): stamp CorrelationId on dashboard API-key admin audit events (mxaccessgw#213)
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m29s
ci / java (push) Successful in 2m13s
ci / portable (push) Failing after 4m12s

CanonicalForwardingApiKeyAuditStore now derives CorrelationId from the ambient
request: Activity.Current trace id, else the HTTP request TraceIdentifier
(GUID used verbatim, otherwise hashed to a stable GUID) via an optional
IHttpContextAccessor. The CLI path has neither and stays null. Auth library
unchanged (option b).

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 15:04:03 -05:00
parent fccc21ba8e
commit 259d375022
2 changed files with 117 additions and 4 deletions
@@ -1,4 +1,8 @@
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.AspNetCore.Http;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
@@ -23,10 +27,18 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Audit;
/// writes to it once this adapter overrides the library's <c>SqliteApiKeyAuditStore</c>
/// registration.
/// </para>
/// <para>
/// <see cref="AuditEvent.CorrelationId"/> is stamped from the ambient request when there is
/// one — the current <see cref="Activity"/> trace id, else the HTTP request's
/// <c>TraceIdentifier</c> — so dashboard-originated key create/revoke/rotate events can be tied
/// to their request. The CLI path has neither and leaves it null. The Auth library's
/// <see cref="ApiKeyAuditEntry"/> carries no correlation field, hence the ambient lookup.
/// </para>
/// </remarks>
public sealed class CanonicalForwardingApiKeyAuditStore(
IAuditWriter auditWriter,
SqliteCanonicalAuditStore store) : IApiKeyAuditStore
SqliteCanonicalAuditStore store,
IHttpContextAccessor? httpContextAccessor = null) : IApiKeyAuditStore
{
/// <summary>The canonical <see cref="AuditEvent.Category"/> assigned to API-key events.</summary>
public const string ApiKeyCategory = "ApiKey";
@@ -66,7 +78,7 @@ public sealed class CanonicalForwardingApiKeyAuditStore(
Category = ApiKeyCategory,
Target = entry.KeyId,
SourceNode = entry.RemoteAddress,
CorrelationId = null,
CorrelationId = ResolveCorrelationId(),
DetailsJson = WrapDetails(entry.Details),
};
@@ -74,6 +86,30 @@ public sealed class CanonicalForwardingApiKeyAuditStore(
await auditWriter.WriteAsync(auditEvent, ct).ConfigureAwait(false);
}
/// <summary>
/// Derives a correlation id from the ambient request: the current activity's 128-bit trace id
/// when present, else the HTTP request's <c>TraceIdentifier</c> (parsed when it is a GUID,
/// otherwise hashed to a stable GUID). Returns null outside a request (the CLI path).
/// </summary>
private Guid? ResolveCorrelationId()
{
Activity? activity = Activity.Current;
if (activity is not null && activity.TraceId != default)
{
return Guid.ParseExact(activity.TraceId.ToHexString(), "N");
}
string? traceIdentifier = httpContextAccessor?.HttpContext?.TraceIdentifier;
if (string.IsNullOrEmpty(traceIdentifier))
{
return null;
}
return Guid.TryParse(traceIdentifier, out Guid parsed)
? parsed
: new Guid(MD5.HashData(Encoding.UTF8.GetBytes(traceIdentifier)));
}
/// <summary>Reads back the most recent entries from the canonical audit store and maps each one to an <see cref="ApiKeyAuditEntry"/>.</summary>
/// <param name="limit">The maximum number of entries to return.</param>
/// <param name="ct">Token to observe for cancellation.</param>
@@ -1,3 +1,5 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
@@ -266,11 +268,86 @@ public sealed class CanonicalAuditStoreAndAdapterTests : IDisposable
return new SqliteCanonicalAuditStore(new AuthSqliteConnectionFactory(directory.DatabasePath()));
}
private (CanonicalForwardingApiKeyAuditStore Adapter, SqliteCanonicalAuditStore Store) CreateAdapter()
private (CanonicalForwardingApiKeyAuditStore Adapter, SqliteCanonicalAuditStore Store) CreateAdapter(
IHttpContextAccessor? httpContextAccessor = null)
{
SqliteCanonicalAuditStore store = CreateStore();
CanonicalAuditWriter writer = new(store, NullLogger<CanonicalAuditWriter>.Instance);
return (new CanonicalForwardingApiKeyAuditStore(writer, store), store);
return (new CanonicalForwardingApiKeyAuditStore(writer, store, httpContextAccessor), store);
}
private static ApiKeyAuditEntry KeyedEntry() => new(
KeyId: "operator01",
EventType: "create-key",
RemoteAddress: "10.0.0.5",
CreatedUtc: DateTimeOffset.UtcNow,
Details: "created");
/// <summary>The dashboard path (HTTP request, no activity) stamps a correlation id from TraceIdentifier (#213).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Adapter_DashboardRequest_StampsCorrelationIdFromTraceIdentifier()
{
DefaultHttpContext httpContext = new() { TraceIdentifier = "0HN8EXAMPLE:00000001" };
(CanonicalForwardingApiKeyAuditStore adapter, SqliteCanonicalAuditStore store) =
CreateAdapter(new HttpContextAccessor { HttpContext = httpContext });
await adapter.AppendAsync(KeyedEntry(), CancellationToken.None);
await adapter.AppendAsync(KeyedEntry(), CancellationToken.None);
IReadOnlyList<AuditEvent> events = await store.ListRecentAsync(10, CancellationToken.None);
Assert.Equal(2, events.Count);
Assert.All(events, e => Assert.NotNull(e.CorrelationId));
// Stable per request: both events of the same request share the id.
Assert.Equal(events[0].CorrelationId, events[1].CorrelationId);
}
/// <summary>A GUID-shaped TraceIdentifier is used verbatim.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Adapter_GuidTraceIdentifier_IsUsedAsCorrelationId()
{
Guid trace = Guid.NewGuid();
DefaultHttpContext httpContext = new() { TraceIdentifier = trace.ToString() };
(CanonicalForwardingApiKeyAuditStore adapter, SqliteCanonicalAuditStore store) =
CreateAdapter(new HttpContextAccessor { HttpContext = httpContext });
await adapter.AppendAsync(KeyedEntry(), CancellationToken.None);
Assert.Equal(trace, Assert.Single(await store.ListRecentAsync(10, CancellationToken.None)).CorrelationId);
}
/// <summary>An ambient activity's trace id wins over the HTTP trace identifier.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Adapter_AmbientActivity_StampsTraceIdAsCorrelationId()
{
using Activity activity = new("test-request");
activity.Start();
DefaultHttpContext httpContext = new() { TraceIdentifier = "ignored" };
(CanonicalForwardingApiKeyAuditStore adapter, SqliteCanonicalAuditStore store) =
CreateAdapter(new HttpContextAccessor { HttpContext = httpContext });
await adapter.AppendAsync(KeyedEntry(), CancellationToken.None);
Guid expected = Guid.ParseExact(activity.TraceId.ToHexString(), "N");
Assert.Equal(expected, Assert.Single(await store.ListRecentAsync(10, CancellationToken.None)).CorrelationId);
}
/// <summary>The CLI path (no accessor, no activity, no request) leaves the correlation id null (#213).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Adapter_CliPath_LeavesCorrelationIdNull()
{
(CanonicalForwardingApiKeyAuditStore adapter, SqliteCanonicalAuditStore store) = CreateAdapter();
(CanonicalForwardingApiKeyAuditStore noRequest, _) =
CreateAdapter(new HttpContextAccessor { HttpContext = null });
Assert.Null(Activity.Current);
await adapter.AppendAsync(KeyedEntry(), CancellationToken.None);
await noRequest.AppendAsync(KeyedEntry(), CancellationToken.None);
Assert.Null(Assert.Single(await store.ListRecentAsync(10, CancellationToken.None)).CorrelationId);
}
private static AuditEvent MakeEvent(string action) => new()