feat(api): audit context middleware + scoped impl (UDT-010 B4)
Wires the request-scoped audit context per design #D-2:
Middleware pipeline in Program.cs:
app.UseCors()
app.UseMiddleware<CorrelationIdMiddleware>() // PRE-AUTH
app.UseAuthentication()
app.UseMiddleware<AuditActorMiddleware>() // POST-AUTH
app.UseAuthorization()
app.MapControllers()
SIGCM2.Api/Middleware/CorrelationIdMiddleware.cs:
- Preserves client-sent X-Correlation-Id header when a valid GUID, otherwise
generates Guid.NewGuid(). Stores in HttpContext.Items (audit:correlationId).
- Captures Ip (Connection.RemoteIpAddress) + UserAgent header into Items.
- Echoes the correlation id back via response header (OnStarting + immediate
set — immediate set makes unit testing against DefaultHttpContext reliable).
SIGCM2.Api/Middleware/AuditActorMiddleware.cs:
- Reads JWT 'sub' claim from authenticated HttpContext.User, parses to int,
stores as audit:actorUserId. Anonymous / non-numeric sub leaves it unset.
SIGCM2.Infrastructure/Audit/AuditContext.cs (IAuditContext scoped impl):
- Reads Items entries via IHttpContextAccessor. Returns null / Guid.Empty
when no HttpContext is available (jobs, tests without middleware).
- ActorRoleId intentionally null for now — rol code → id resolution is
deferred; the logger may resolve it at persist time in a later batch.
DI registration (Infrastructure/DependencyInjection.cs):
- services.AddScoped<IAuditContext, AuditContext>()
Tests (Strict TDD):
- CorrelationIdMiddlewareTests (6): generates/preserves/handles-malformed
correlation id, sets response header, captures ip/ua, calls next.
- AuditActorMiddlewareTests (5): authenticated/anonymous/no-sub/non-numeric/
calls-next.
- AuditContextTests (7): reads from Items, null-http-context defaults,
ActorRoleId currently null.
Suite: 355/355 Application.Tests + 141/141 Api.Tests = 496/496 passing.
Refs: sdd/udt-010-auditoria-trazabilidad/{spec#REQ-AUD-3/9, design#D-2, tasks#B4}
This commit is contained in:
32
src/api/SIGCM2.Api/Middleware/AuditActorMiddleware.cs
Normal file
32
src/api/SIGCM2.Api/Middleware/AuditActorMiddleware.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace SIGCM2.Api.Middleware;
|
||||
|
||||
/// UDT-010 — post-auth middleware that reads the JWT "sub" claim and stores the
|
||||
/// resolved ActorUserId in HttpContext.Items. Anonymous requests leave it unset.
|
||||
/// ActorRoleId is reserved for a future batch (rol code → id resolution).
|
||||
public sealed class AuditActorMiddleware
|
||||
{
|
||||
public const string ItemActorUserId = "audit:actorUserId";
|
||||
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
public AuditActorMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext ctx)
|
||||
{
|
||||
if (ctx.User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
var sub = ctx.User.FindFirst("sub")?.Value;
|
||||
if (int.TryParse(sub, out var userId))
|
||||
{
|
||||
ctx.Items[ItemActorUserId] = userId;
|
||||
}
|
||||
}
|
||||
|
||||
await _next(ctx);
|
||||
}
|
||||
}
|
||||
51
src/api/SIGCM2.Api/Middleware/CorrelationIdMiddleware.cs
Normal file
51
src/api/SIGCM2.Api/Middleware/CorrelationIdMiddleware.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace SIGCM2.Api.Middleware;
|
||||
|
||||
/// UDT-010 — pre-auth middleware that stamps every request with a correlation ID,
|
||||
/// preserves one sent by the client via X-Correlation-Id, and exposes it on the response.
|
||||
/// Also captures Ip + UserAgent for downstream IAuditContext consumers.
|
||||
public sealed class CorrelationIdMiddleware
|
||||
{
|
||||
public const string HeaderName = "X-Correlation-Id";
|
||||
public const string ItemCorrelationId = "audit:correlationId";
|
||||
public const string ItemIp = "audit:ip";
|
||||
public const string ItemUserAgent = "audit:userAgent";
|
||||
|
||||
private readonly RequestDelegate _next;
|
||||
|
||||
public CorrelationIdMiddleware(RequestDelegate next)
|
||||
{
|
||||
_next = next;
|
||||
}
|
||||
|
||||
public async Task InvokeAsync(HttpContext ctx)
|
||||
{
|
||||
Guid correlationId;
|
||||
if (ctx.Request.Headers.TryGetValue(HeaderName, out var incoming)
|
||||
&& Guid.TryParse(incoming.ToString(), out var parsed))
|
||||
{
|
||||
correlationId = parsed;
|
||||
}
|
||||
else
|
||||
{
|
||||
correlationId = Guid.NewGuid();
|
||||
}
|
||||
|
||||
ctx.Items[ItemCorrelationId] = correlationId;
|
||||
ctx.Items[ItemIp] = ctx.Connection.RemoteIpAddress?.ToString();
|
||||
ctx.Items[ItemUserAgent] = ctx.Request.Headers.UserAgent.ToString();
|
||||
|
||||
ctx.Response.OnStarting(() =>
|
||||
{
|
||||
ctx.Response.Headers[HeaderName] = correlationId.ToString("D");
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
// Also set immediately for testability — DefaultHttpContext does not trigger OnStarting
|
||||
// in unit tests because no body is written through the pipeline.
|
||||
ctx.Response.Headers[HeaderName] = correlationId.ToString("D");
|
||||
|
||||
await _next(ctx);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authorization;
|
||||
using Serilog;
|
||||
using Scalar.AspNetCore;
|
||||
using SIGCM2.Api.Authorization;
|
||||
using SIGCM2.Api.Middleware;
|
||||
using SIGCM2.Application;
|
||||
using SIGCM2.Infrastructure;
|
||||
using SIGCM2.Api.Filters;
|
||||
@@ -66,7 +67,12 @@ if (app.Environment.IsDevelopment() || app.Environment.IsEnvironment("Testing"))
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseCors();
|
||||
// UDT-010: correlation id + ip/ua capture runs BEFORE auth so anonymous requests
|
||||
// still get a correlation id and so logs can tie pre-auth events to the request.
|
||||
app.UseMiddleware<CorrelationIdMiddleware>();
|
||||
app.UseAuthentication();
|
||||
// UDT-010: actor extraction runs AFTER auth to read the JWT sub claim.
|
||||
app.UseMiddleware<AuditActorMiddleware>();
|
||||
app.UseAuthorization();
|
||||
app.MapControllers();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user