Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<PackageVersion Include="coverlet.msbuild" Version="10.0.1" />
<PackageVersion Include="Ductus.FluentDocker" Version="2.85.0" />
<PackageVersion Include="EventStoreProjections" Version="2023.12.3" />
<PackageVersion Include="KurrentDB.Client" Version="1.4.0" />
<PackageVersion Include="Lamar" Version="16.0.0" />
<PackageVersion Include="Lamar.Microsoft.DependencyInjection" Version="16.0.0" />
<PackageVersion Include="MediatR" Version="14.1.0" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Http;

namespace TransactionProcessorACL.Common;

public sealed class AuditPipelineBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IRequestAuditRecorder _requestAuditRecorder;

public AuditPipelineBehavior(IHttpContextAccessor httpContextAccessor,
IRequestAuditRecorder requestAuditRecorder)
{
_httpContextAccessor = httpContextAccessor;
_requestAuditRecorder = requestAuditRecorder;
}

public async Task<TResponse> Handle(TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
HttpContext? httpContext = _httpContextAccessor.HttpContext;
if (httpContext is null)
{
return await next().ConfigureAwait(false);
}

Boolean failed = false;
String? errorMessage = null;

try
{
TResponse? response = await next(cancellationToken).ConfigureAwait(false);
return response;
}
catch (Exception ex)
{
failed = true;
errorMessage = ex.Message;
throw;
}
finally
{
await RecordAuditAsync(httpContext, request, failed, errorMessage, cancellationToken).ConfigureAwait(false);
}
}

private async Task RecordAuditAsync(HttpContext httpContext,
TRequest request,
Boolean failed,
String? errorMessage,
CancellationToken cancellationToken)
{
RequestAuditEvent auditEvent = RequestAuditContextBuilder.Build(
httpContext,
request,
failed ? "Failed" : "Succeeded",
errorMessage);

try
{
await _requestAuditRecorder.RecordAsync(auditEvent, cancellationToken).ConfigureAwait(false);
}
catch
{
// Audit must not interfere with the request path.
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using System.Threading;
using System.Threading.Tasks;

namespace TransactionProcessorACL.Common;

public interface IRequestAuditRecorder
{
Task RecordAsync(RequestAuditEvent auditEvent, CancellationToken cancellationToken);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using KurrentDB.Client;
using Microsoft.AspNetCore.Http;
using Shared.Logger;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace TransactionProcessorACL.Common;

public sealed class LoggingRequestAuditRecorder : IRequestAuditRecorder
{
public Task RecordAsync(RequestAuditEvent auditEvent, CancellationToken cancellationToken)
{
string payload = JsonSerializer.Serialize(auditEvent);
Logger.LogWarning($"AUDIT {payload}");
return Task.CompletedTask;
}

public class KurrentDbRequestAuditRecorder : IRequestAuditRecorder
{
private readonly KurrentDBClient KurrentDbClient;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly RequestAuditStreamOptions _streamOptions;

public KurrentDbRequestAuditRecorder(KurrentDBClient KurrentDBClient,
IHttpContextAccessor httpContextAccessor,
RequestAuditStreamOptions streamOptions) {
this.KurrentDbClient = KurrentDBClient;
_httpContextAccessor = httpContextAccessor;
_streamOptions = streamOptions;
}

public async Task RecordAsync(RequestAuditEvent auditEvent, CancellationToken cancellationToken) {
String requestId = GetRequestId(auditEvent);
String streamName = $"RequestAudit-{requestId}";

StreamMetadata streamMetadata = new(
maxCount: null,
maxAge: _streamOptions.RequestAuditStreamLifetime,
truncateBefore: null,
cacheControl: null,
acl: null,
customMetadata: null);

await this.KurrentDbClient.SetStreamMetadataAsync(
streamName,
StreamState.Any,
streamMetadata,
cancellationToken: cancellationToken);

List<EventData> events = [CreateEventData(Guid.NewGuid(), "RequestAuditEvent", JsonSerializer.Serialize(auditEvent), "")];

await this.KurrentDbClient.AppendToStreamAsync(streamName, StreamState.Any, events, cancellationToken: cancellationToken);
}

private String GetRequestId(RequestAuditEvent auditEvent)
{
HttpContext? httpContext = _httpContextAccessor.HttpContext;
if (httpContext is not null)
{
return RequestIdProvider.GetOrCreateRequestId(httpContext);
}

return auditEvent.Context.RequestId;
}

private static EventData CreateEventData(Guid eventId,
String eventType,
String data,
String metadata)
{
Byte[] eventData = Encoding.Default.GetBytes(data);
Byte[] eventMetadata = Encoding.Default.GetBytes(metadata);

EventData @event = new(Uuid.FromGuid(eventId), eventType, eventData, eventMetadata);

return @event;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;

namespace TransactionProcessorACL.Common;

public sealed record RequestAuditContext(
string RequestId,
string TraceId,
DateTimeOffset TimestampUtc,
string Method,
string Route,
string SourceIp,
string UserAgent,
Guid? EstateId,
Guid? MerchantId,
string TransactionType,
string? TransactionNumber,
IReadOnlyDictionary<string, string> BusinessContext);
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;
using System.Threading;

namespace TransactionProcessorACL.Common;

public sealed class RequestAuditContextAccessor
{
private static readonly AsyncLocal<RequestAuditContext?> CurrentContext = new();

public RequestAuditContext? Current
{
get => CurrentContext.Value;
set => CurrentContext.Value = value;
}
}
Loading
Loading