feat: improve operational audit reliability
This commit is contained in:
1 parent
acbe64df00
commit
b7d9e6a4d9
10 files changed
+11601
-28
No files matched your search
@@ -120,6 +120,7 @@ public sealed class OperationsController(
|
||||
[FromQuery] int? statusCode = null,
|
||||
[FromQuery] string? userName = null,
|
||||
[FromQuery] string? path = null,
|
||||
[FromQuery] string? requestId = null,
|
||||
[FromQuery] DateTime? from = null,
|
||||
[FromQuery] DateTime? to = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
@@ -148,6 +149,11 @@ public sealed class OperationsController(
|
||||
var normalizedPath = path.Trim();
|
||||
query = query.Where(x => x.Path.Contains(normalizedPath));
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(requestId))
|
||||
{
|
||||
var normalizedRequestId = requestId.Trim();
|
||||
query = query.Where(x => x.RequestId == normalizedRequestId);
|
||||
}
|
||||
query = query.Where(x =>
|
||||
x.CreatedAt >= (from ?? DateTime.UtcNow.AddDays(-1)));
|
||||
if (to.HasValue)
|
||||
@@ -165,6 +171,10 @@ public sealed class OperationsController(
|
||||
x.Path,
|
||||
x.StatusCode,
|
||||
x.IpAddress,
|
||||
x.RequestId,
|
||||
x.DurationMilliseconds,
|
||||
x.UserAgent,
|
||||
x.ErrorType,
|
||||
x.CreatedAt))
|
||||
.ToListAsync(cancellationToken);
|
||||
return Ok(new PagedResult<AuditLogItem>(items, total, page, pageSize));
|
||||
@@ -606,6 +616,10 @@ public sealed record AuditLogItem(
|
||||
string Path,
|
||||
int StatusCode,
|
||||
string? IpAddress,
|
||||
string? RequestId,
|
||||
long DurationMilliseconds,
|
||||
string? UserAgent,
|
||||
string? ErrorType,
|
||||
DateTime CreatedAt);
|
||||
|
||||
public sealed record FailedBackgroundJobItem(
|
||||
|
||||
@@ -10,4 +10,8 @@ public sealed class AuditLog : EntityBase
|
||||
public required string Path { get; set; }
|
||||
public int StatusCode { get; set; }
|
||||
public string? IpAddress { get; set; }
|
||||
public string? RequestId { get; set; }
|
||||
public long DurationMilliseconds { get; set; }
|
||||
public string? UserAgent { get; set; }
|
||||
public string? ErrorType { get; set; }
|
||||
}
|
||||
@@ -1,38 +1,100 @@
|
||||
using System.Diagnostics;
|
||||
using System.Security.Claims;
|
||||
using Jiaowu.Api.Domain.System;
|
||||
using Jiaowu.Api.Infrastructure.Persistence;
|
||||
|
||||
namespace Jiaowu.Api.Infrastructure.Middleware;
|
||||
|
||||
public sealed class AuditMiddleware(RequestDelegate next)
|
||||
public sealed class AuditMiddleware(
|
||||
RequestDelegate next,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<AuditMiddleware> logger)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context, AppDbContext db)
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
await next(context);
|
||||
|
||||
if (HttpMethods.IsGet(context.Request.Method) ||
|
||||
context.Request.Path.StartsWithSegments("/swagger"))
|
||||
if (!context.Request.Path.StartsWithSegments("/api"))
|
||||
{
|
||||
await next(context);
|
||||
return;
|
||||
}
|
||||
|
||||
// A failed business write can leave invalid tracked entities in this request scope.
|
||||
// Audit persistence must not retry those entities and replace the original response.
|
||||
db.ChangeTracker.Clear();
|
||||
db.AuditLogs.Add(new AuditLog
|
||||
var startedAt = Stopwatch.GetTimestamp();
|
||||
Exception? requestException = null;
|
||||
try
|
||||
{
|
||||
UserId = Guid.TryParse(
|
||||
context.User.FindFirstValue(ClaimTypes.NameIdentifier),
|
||||
out var userId)
|
||||
? userId
|
||||
: null,
|
||||
UserName = context.User.Identity?.Name,
|
||||
Method = context.Request.Method,
|
||||
Path = context.Request.Path,
|
||||
StatusCode = context.Response.StatusCode,
|
||||
IpAddress = context.Connection.RemoteIpAddress?.ToString()
|
||||
});
|
||||
await next(context);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
requestException = exception;
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
var statusCode = requestException switch
|
||||
{
|
||||
OperationCanceledException when context.RequestAborted.IsCancellationRequested => 499,
|
||||
null => context.Response.StatusCode,
|
||||
_ => StatusCodes.Status500InternalServerError
|
||||
};
|
||||
if (ShouldPersist(context.Request.Method, statusCode, requestException))
|
||||
{
|
||||
var entry = new AuditLog
|
||||
{
|
||||
UserId = Guid.TryParse(
|
||||
context.User.FindFirstValue(ClaimTypes.NameIdentifier),
|
||||
out var userId)
|
||||
? userId
|
||||
: null,
|
||||
UserName = context.User.Identity?.Name,
|
||||
Method = context.Request.Method,
|
||||
Path = context.Request.Path,
|
||||
StatusCode = statusCode,
|
||||
IpAddress = context.Connection.RemoteIpAddress?.ToString(),
|
||||
RequestId = context.TraceIdentifier,
|
||||
DurationMilliseconds = (long)Math.Ceiling(
|
||||
Stopwatch.GetElapsedTime(startedAt).TotalMilliseconds),
|
||||
UserAgent = Normalize(context.Request.Headers.UserAgent.ToString(), 500),
|
||||
ErrorType = requestException?.GetType().Name
|
||||
};
|
||||
|
||||
await db.SaveChangesAsync(context.RequestAborted);
|
||||
await PersistAsync(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PersistAsync(AuditLog entry)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
await using var scope = scopeFactory.CreateAsyncScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
|
||||
db.AuditLogs.Add(entry);
|
||||
await db.SaveChangesAsync(timeout.Token);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// Audit persistence must never replace or abort the business response.
|
||||
logger.LogError(
|
||||
exception,
|
||||
"Unable to persist API audit event for request {RequestId}.",
|
||||
entry.RequestId);
|
||||
}
|
||||
}
|
||||
|
||||
private static string? Normalize(string? value, int maximumLength) =>
|
||||
string.IsNullOrWhiteSpace(value)
|
||||
? null
|
||||
: value.Length <= maximumLength
|
||||
? value
|
||||
: value[..maximumLength];
|
||||
|
||||
private static bool ShouldPersist(
|
||||
string method,
|
||||
int statusCode,
|
||||
Exception? exception) =>
|
||||
exception is not null ||
|
||||
statusCode >= StatusCodes.Status400BadRequest ||
|
||||
!(HttpMethods.IsGet(method) || HttpMethods.IsHead(method));
|
||||
}
|
||||
Loaded 3 of 10 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user