From 259d37502287823792182965ada75a2cbddeb01c Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Mon, 9 Nov 2026 15:04:03 -0500 Subject: [PATCH] feat(audit): stamp CorrelationId on dashboard API-key admin audit events (mxaccessgw#213) 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 --- .../CanonicalForwardingApiKeyAuditStore.cs | 40 ++++++++- .../CanonicalAuditStoreAndAdapterTests.cs | 81 ++++++++++++++++++- 2 files changed, 117 insertions(+), 4 deletions(-) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/CanonicalForwardingApiKeyAuditStore.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/CanonicalForwardingApiKeyAuditStore.cs index a24aa7b6..5e352d6f 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/CanonicalForwardingApiKeyAuditStore.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Audit/CanonicalForwardingApiKeyAuditStore.cs @@ -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 SqliteApiKeyAuditStore /// registration. /// +/// +/// is stamped from the ambient request when there is +/// one — the current trace id, else the HTTP request's +/// TraceIdentifier — 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 +/// carries no correlation field, hence the ambient lookup. +/// /// public sealed class CanonicalForwardingApiKeyAuditStore( IAuditWriter auditWriter, - SqliteCanonicalAuditStore store) : IApiKeyAuditStore + SqliteCanonicalAuditStore store, + IHttpContextAccessor? httpContextAccessor = null) : IApiKeyAuditStore { /// The canonical assigned to API-key events. 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); } + /// + /// Derives a correlation id from the ambient request: the current activity's 128-bit trace id + /// when present, else the HTTP request's TraceIdentifier (parsed when it is a GUID, + /// otherwise hashed to a stable GUID). Returns null outside a request (the CLI path). + /// + 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))); + } + /// Reads back the most recent entries from the canonical audit store and maps each one to an . /// The maximum number of entries to return. /// Token to observe for cancellation. diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/CanonicalAuditStoreAndAdapterTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/CanonicalAuditStoreAndAdapterTests.cs index 761d6451..6fa5dc61 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/CanonicalAuditStoreAndAdapterTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Audit/CanonicalAuditStoreAndAdapterTests.cs @@ -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.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"); + + /// The dashboard path (HTTP request, no activity) stamps a correlation id from TraceIdentifier (#213). + /// A task that represents the asynchronous operation. + [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 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); + } + + /// A GUID-shaped TraceIdentifier is used verbatim. + /// A task that represents the asynchronous operation. + [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); + } + + /// An ambient activity's trace id wins over the HTTP trace identifier. + /// A task that represents the asynchronous operation. + [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); + } + + /// The CLI path (no accessor, no activity, no request) leaves the correlation id null (#213). + /// A task that represents the asynchronous operation. + [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()