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
@@ -0,0 +1,173 @@
|
||||
using System.Security.Claims;
|
||||
using Jiaowu.Api.Infrastructure.Middleware;
|
||||
using Jiaowu.Api.Infrastructure.Persistence;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace Jiaowu.Api.Tests;
|
||||
|
||||
public sealed class AuditMiddlewareTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Records_authenticated_write_requests_with_correlation_data()
|
||||
{
|
||||
await using var fixture = await AuditFixture.CreateAsync();
|
||||
var userId = Guid.NewGuid();
|
||||
var middleware = fixture.CreateMiddleware(context =>
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status200OK;
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
var context = CreateContext(userId, "operator");
|
||||
context.Request.Method = HttpMethods.Post;
|
||||
context.Request.Path = "/api/students";
|
||||
context.Request.Headers.UserAgent = "audit-test-agent";
|
||||
|
||||
await middleware.InvokeAsync(context);
|
||||
|
||||
var entry = await fixture.ReadSingleAsync();
|
||||
Assert.Equal(userId, entry.UserId);
|
||||
Assert.Equal("operator", entry.UserName);
|
||||
Assert.Equal("POST", entry.Method);
|
||||
Assert.Equal("/api/students", entry.Path);
|
||||
Assert.Equal(200, entry.StatusCode);
|
||||
Assert.Equal(context.TraceIdentifier, entry.RequestId);
|
||||
Assert.Equal("audit-test-agent", entry.UserAgent);
|
||||
Assert.Null(entry.ErrorType);
|
||||
Assert.True(entry.DurationMilliseconds >= 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Records_failed_get_requests()
|
||||
{
|
||||
await using var fixture = await AuditFixture.CreateAsync();
|
||||
var middleware = fixture.CreateMiddleware(context =>
|
||||
{
|
||||
context.Response.StatusCode = StatusCodes.Status403Forbidden;
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
var context = CreateContext(null, null);
|
||||
context.Request.Method = HttpMethods.Get;
|
||||
context.Request.Path = "/api/restricted";
|
||||
|
||||
await middleware.InvokeAsync(context);
|
||||
|
||||
var entry = await fixture.ReadSingleAsync();
|
||||
Assert.Equal("GET", entry.Method);
|
||||
Assert.Equal(403, entry.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Ignores_successful_get_requests()
|
||||
{
|
||||
await using var fixture = await AuditFixture.CreateAsync();
|
||||
var middleware = fixture.CreateMiddleware(_ => Task.CompletedTask);
|
||||
var context = CreateContext(null, null);
|
||||
context.Request.Method = HttpMethods.Get;
|
||||
context.Request.Path = "/api/students";
|
||||
|
||||
await middleware.InvokeAsync(context);
|
||||
|
||||
Assert.Equal(0, await fixture.CountAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Records_unhandled_exceptions_and_preserves_the_original_exception()
|
||||
{
|
||||
await using var fixture = await AuditFixture.CreateAsync();
|
||||
var middleware = fixture.CreateMiddleware(_ =>
|
||||
throw new InvalidOperationException("business failure"));
|
||||
var context = CreateContext(null, null);
|
||||
context.Request.Method = HttpMethods.Get;
|
||||
context.Request.Path = "/api/failing-query";
|
||||
|
||||
var exception = await Assert.ThrowsAsync<InvalidOperationException>(
|
||||
() => middleware.InvokeAsync(context));
|
||||
|
||||
Assert.Equal("business failure", exception.Message);
|
||||
var entry = await fixture.ReadSingleAsync();
|
||||
Assert.Equal(500, entry.StatusCode);
|
||||
Assert.Equal(nameof(InvalidOperationException), entry.ErrorType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Ignores_non_api_requests()
|
||||
{
|
||||
await using var fixture = await AuditFixture.CreateAsync();
|
||||
var middleware = fixture.CreateMiddleware(_ => Task.CompletedTask);
|
||||
var context = CreateContext(null, null);
|
||||
context.Request.Path = "/assets/app.js";
|
||||
|
||||
await middleware.InvokeAsync(context);
|
||||
|
||||
Assert.Equal(0, await fixture.CountAsync());
|
||||
}
|
||||
|
||||
private static DefaultHttpContext CreateContext(Guid? userId, string? userName)
|
||||
{
|
||||
var context = new DefaultHttpContext();
|
||||
context.TraceIdentifier = $"audit-{Guid.NewGuid():N}";
|
||||
if (userId.HasValue)
|
||||
{
|
||||
context.User = new ClaimsPrincipal(new ClaimsIdentity(
|
||||
[
|
||||
new Claim(ClaimTypes.NameIdentifier, userId.Value.ToString()),
|
||||
new Claim(ClaimTypes.Name, userName!)
|
||||
], "test"));
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
private sealed class AuditFixture : IAsyncDisposable
|
||||
{
|
||||
private readonly string databasePath;
|
||||
private readonly ServiceProvider provider;
|
||||
|
||||
private AuditFixture(string databasePath, ServiceProvider provider)
|
||||
{
|
||||
this.databasePath = databasePath;
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
public static async Task<AuditFixture> CreateAsync()
|
||||
{
|
||||
var databasePath = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
$"jiaowu-audit-{Guid.NewGuid():N}.sqlite");
|
||||
var services = new ServiceCollection();
|
||||
services.AddDbContext<AppDbContext>(options =>
|
||||
options.UseSqlite($"Data Source={databasePath};Pooling=False"));
|
||||
var provider = services.BuildServiceProvider();
|
||||
await using var scope = provider.CreateAsyncScope();
|
||||
await scope.ServiceProvider.GetRequiredService<AppDbContext>()
|
||||
.Database.EnsureCreatedAsync();
|
||||
return new AuditFixture(databasePath, provider);
|
||||
}
|
||||
|
||||
public AuditMiddleware CreateMiddleware(RequestDelegate next) =>
|
||||
new(next, provider.GetRequiredService<IServiceScopeFactory>(),
|
||||
NullLogger<AuditMiddleware>.Instance);
|
||||
|
||||
public async Task<Domain.System.AuditLog> ReadSingleAsync()
|
||||
{
|
||||
await using var scope = provider.CreateAsyncScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<AppDbContext>()
|
||||
.AuditLogs.AsNoTracking().SingleAsync();
|
||||
}
|
||||
|
||||
public async Task<int> CountAsync()
|
||||
{
|
||||
await using var scope = provider.CreateAsyncScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<AppDbContext>()
|
||||
.AuditLogs.CountAsync();
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await provider.DisposeAsync();
|
||||
if (File.Exists(databasePath)) File.Delete(databasePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user