2026-04-15 17:50:54 -03:00
|
|
|
using NSubstitute;
|
|
|
|
|
using SIGCM2.Application.Abstractions.Persistence;
|
feat(audit): enchufar audit en handlers de Usuario — Closes #6
7 command handlers del módulo Usuarios ahora auditan via IAuditLogger:
| Handler | Action |
|-----------------------------------------|-------------------------|
| CreateUsuarioCommandHandler | usuario.create |
| UpdateUsuarioCommandHandler | usuario.update |
| DeactivateUsuarioCommandHandler | usuario.deactivate |
| ReactivateUsuarioCommandHandler | usuario.reactivate |
| ChangeMyPasswordCommandHandler | usuario.password_change |
| ResetUsuarioPasswordCommandHandler | usuario.password_reset |
| UpdateUsuarioPermisosOverridesHandler | usuario.permisos_update |
Patrón por handler (per design #D-1):
using (var tx = new TransactionScope(Required, ReadCommitted, AsyncFlowEnabled))
{
await repo.UpdateAsync(...);
await audit.LogAsync(...);
tx.Complete();
}
// post-commit reads OUTSIDE the using block
var updated = await repo.GetDetailAsync(...);
Metadata captured:
- usuario.create: after={username, nombre, apellido, email, rol} — NO password.
- usuario.update: {before, after} diff of editable fields.
- usuario.password_reset: {targetId} only — tempPassword is NEVER persisted to
audit (returned to caller once, never stored).
- usuario.permisos_update: {before, after} of grant/deny override lists.
Key fix during implementation: initially used 'using var tx = ...' (bare
declaration). This kept the TransactionScope active for the rest of the method,
causing 'The current TransactionScope is already complete' when post-commit
reads (GetDetailAsync) tried to enlist. Solution: explicit 'using (var tx = ...)
{ ... }' block that disposes the scope before post-commit reads.
AuditContextMissingException surfaces from AuditLogger when IAuditContext
lacks ActorUserId — fail-closed per #REQ-AUD-4. In integration tests, the
middleware populates ActorUserId from the JWT sub of the authenticated admin.
Test updates: 6 existing unit test classes now inject IAuditLogger mock:
- CreateUsuarioCommandHandlerTests
- UpdateUsuarioCommandHandlerTests
- DeactivateUsuarioCommandHandlerTests
- ReactivateUsuarioCommandHandlerTests
- ChangeMyPasswordCommandHandlerTests
- ResetUsuarioPasswordCommandHandlerTests
Follow-up #6 ([Auditoría] Registrar admin creador en alta de usuarios) is
closed: CreateUsuarioCommandHandler now records ActorUserId = admin JWT sub
on every user creation. TODO comment removed.
Suite: 378/378 Application.Tests + 141/141 Api.Tests = 519/519 passing.
Closes #6
Refs: sdd/udt-010-auditoria-trazabilidad/{spec#REQ-UM-AUD, design, tasks#B7}
2026-04-16 13:49:44 -03:00
|
|
|
using SIGCM2.Application.Audit;
|
2026-04-15 17:50:54 -03:00
|
|
|
using SIGCM2.Application.Common;
|
|
|
|
|
using SIGCM2.Application.Usuarios.Deactivate;
|
|
|
|
|
using SIGCM2.Domain.Entities;
|
|
|
|
|
using SIGCM2.Domain.Exceptions;
|
|
|
|
|
|
|
|
|
|
namespace SIGCM2.Application.Tests.Usuarios;
|
|
|
|
|
|
|
|
|
|
public class DeactivateUsuarioCommandHandlerTests
|
|
|
|
|
{
|
|
|
|
|
private readonly IUsuarioRepository _repo = Substitute.For<IUsuarioRepository>();
|
|
|
|
|
private readonly IRefreshTokenRepository _refreshRepo = Substitute.For<IRefreshTokenRepository>();
|
feat(audit): enchufar audit en handlers de Usuario — Closes #6
7 command handlers del módulo Usuarios ahora auditan via IAuditLogger:
| Handler | Action |
|-----------------------------------------|-------------------------|
| CreateUsuarioCommandHandler | usuario.create |
| UpdateUsuarioCommandHandler | usuario.update |
| DeactivateUsuarioCommandHandler | usuario.deactivate |
| ReactivateUsuarioCommandHandler | usuario.reactivate |
| ChangeMyPasswordCommandHandler | usuario.password_change |
| ResetUsuarioPasswordCommandHandler | usuario.password_reset |
| UpdateUsuarioPermisosOverridesHandler | usuario.permisos_update |
Patrón por handler (per design #D-1):
using (var tx = new TransactionScope(Required, ReadCommitted, AsyncFlowEnabled))
{
await repo.UpdateAsync(...);
await audit.LogAsync(...);
tx.Complete();
}
// post-commit reads OUTSIDE the using block
var updated = await repo.GetDetailAsync(...);
Metadata captured:
- usuario.create: after={username, nombre, apellido, email, rol} — NO password.
- usuario.update: {before, after} diff of editable fields.
- usuario.password_reset: {targetId} only — tempPassword is NEVER persisted to
audit (returned to caller once, never stored).
- usuario.permisos_update: {before, after} of grant/deny override lists.
Key fix during implementation: initially used 'using var tx = ...' (bare
declaration). This kept the TransactionScope active for the rest of the method,
causing 'The current TransactionScope is already complete' when post-commit
reads (GetDetailAsync) tried to enlist. Solution: explicit 'using (var tx = ...)
{ ... }' block that disposes the scope before post-commit reads.
AuditContextMissingException surfaces from AuditLogger when IAuditContext
lacks ActorUserId — fail-closed per #REQ-AUD-4. In integration tests, the
middleware populates ActorUserId from the JWT sub of the authenticated admin.
Test updates: 6 existing unit test classes now inject IAuditLogger mock:
- CreateUsuarioCommandHandlerTests
- UpdateUsuarioCommandHandlerTests
- DeactivateUsuarioCommandHandlerTests
- ReactivateUsuarioCommandHandlerTests
- ChangeMyPasswordCommandHandlerTests
- ResetUsuarioPasswordCommandHandlerTests
Follow-up #6 ([Auditoría] Registrar admin creador en alta de usuarios) is
closed: CreateUsuarioCommandHandler now records ActorUserId = admin JWT sub
on every user creation. TODO comment removed.
Suite: 378/378 Application.Tests + 141/141 Api.Tests = 519/519 passing.
Closes #6
Refs: sdd/udt-010-auditoria-trazabilidad/{spec#REQ-UM-AUD, design, tasks#B7}
2026-04-16 13:49:44 -03:00
|
|
|
private readonly IAuditLogger _audit = Substitute.For<IAuditLogger>();
|
2026-04-15 17:50:54 -03:00
|
|
|
private readonly DeactivateUsuarioCommandHandler _handler;
|
|
|
|
|
|
|
|
|
|
public DeactivateUsuarioCommandHandlerTests()
|
|
|
|
|
{
|
feat(audit): enchufar audit en handlers de Usuario — Closes #6
7 command handlers del módulo Usuarios ahora auditan via IAuditLogger:
| Handler | Action |
|-----------------------------------------|-------------------------|
| CreateUsuarioCommandHandler | usuario.create |
| UpdateUsuarioCommandHandler | usuario.update |
| DeactivateUsuarioCommandHandler | usuario.deactivate |
| ReactivateUsuarioCommandHandler | usuario.reactivate |
| ChangeMyPasswordCommandHandler | usuario.password_change |
| ResetUsuarioPasswordCommandHandler | usuario.password_reset |
| UpdateUsuarioPermisosOverridesHandler | usuario.permisos_update |
Patrón por handler (per design #D-1):
using (var tx = new TransactionScope(Required, ReadCommitted, AsyncFlowEnabled))
{
await repo.UpdateAsync(...);
await audit.LogAsync(...);
tx.Complete();
}
// post-commit reads OUTSIDE the using block
var updated = await repo.GetDetailAsync(...);
Metadata captured:
- usuario.create: after={username, nombre, apellido, email, rol} — NO password.
- usuario.update: {before, after} diff of editable fields.
- usuario.password_reset: {targetId} only — tempPassword is NEVER persisted to
audit (returned to caller once, never stored).
- usuario.permisos_update: {before, after} of grant/deny override lists.
Key fix during implementation: initially used 'using var tx = ...' (bare
declaration). This kept the TransactionScope active for the rest of the method,
causing 'The current TransactionScope is already complete' when post-commit
reads (GetDetailAsync) tried to enlist. Solution: explicit 'using (var tx = ...)
{ ... }' block that disposes the scope before post-commit reads.
AuditContextMissingException surfaces from AuditLogger when IAuditContext
lacks ActorUserId — fail-closed per #REQ-AUD-4. In integration tests, the
middleware populates ActorUserId from the JWT sub of the authenticated admin.
Test updates: 6 existing unit test classes now inject IAuditLogger mock:
- CreateUsuarioCommandHandlerTests
- UpdateUsuarioCommandHandlerTests
- DeactivateUsuarioCommandHandlerTests
- ReactivateUsuarioCommandHandlerTests
- ChangeMyPasswordCommandHandlerTests
- ResetUsuarioPasswordCommandHandlerTests
Follow-up #6 ([Auditoría] Registrar admin creador en alta de usuarios) is
closed: CreateUsuarioCommandHandler now records ActorUserId = admin JWT sub
on every user creation. TODO comment removed.
Suite: 378/378 Application.Tests + 141/141 Api.Tests = 519/519 passing.
Closes #6
Refs: sdd/udt-010-auditoria-trazabilidad/{spec#REQ-UM-AUD, design, tasks#B7}
2026-04-16 13:49:44 -03:00
|
|
|
_handler = new DeactivateUsuarioCommandHandler(_repo, _refreshRepo, _audit);
|
2026-04-15 17:50:54 -03:00
|
|
|
_repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(2);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static Usuario MakeUser(int id = 5, string rol = "cajero", bool activo = true)
|
|
|
|
|
=> new(id, "user" + id, "$2a$12$hash", "Test", "User", null, rol, "[]", activo);
|
|
|
|
|
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task Handle_Deactivates_Active_User_Returns_Activo_False()
|
|
|
|
|
{
|
|
|
|
|
var target = MakeUser(5, "cajero", true);
|
|
|
|
|
var deactivated = MakeUser(5, "cajero", false);
|
|
|
|
|
|
|
|
|
|
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
|
|
|
|
|
_repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(deactivated);
|
|
|
|
|
|
|
|
|
|
var result = await _handler.Handle(new DeactivateUsuarioCommand(5));
|
|
|
|
|
|
|
|
|
|
Assert.False(result.Activo);
|
|
|
|
|
await _repo.Received(1).UpdateAsync(5, Arg.Any<UpdateUsuarioFields>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task Handle_Idempotent_When_Already_Inactive_No_FechaModificacion_Change()
|
|
|
|
|
{
|
|
|
|
|
var target = MakeUser(5, "cajero", false); // already inactive
|
|
|
|
|
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
|
|
|
|
|
|
|
|
|
|
var result = await _handler.Handle(new DeactivateUsuarioCommand(5));
|
|
|
|
|
|
|
|
|
|
// Idempotent: should NOT call UpdateAsync
|
|
|
|
|
await _repo.DidNotReceive().UpdateAsync(Arg.Any<int>(), Arg.Any<UpdateUsuarioFields>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
|
|
|
|
|
Assert.False(result.Activo);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task Handle_Throws_LastAdminLockoutException_When_Last_Admin()
|
|
|
|
|
{
|
|
|
|
|
var lastAdmin = MakeUser(1, "admin", true);
|
|
|
|
|
_repo.GetByIdAsync(1, Arg.Any<CancellationToken>()).Returns(lastAdmin);
|
|
|
|
|
_repo.CountActiveAdminsAsync(Arg.Any<CancellationToken>()).Returns(1);
|
|
|
|
|
|
|
|
|
|
await Assert.ThrowsAsync<LastAdminLockoutException>(
|
|
|
|
|
() => _handler.Handle(new DeactivateUsuarioCommand(1)));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task Handle_Revokes_Refresh_Tokens_When_Deactivating_Active_User()
|
|
|
|
|
{
|
|
|
|
|
var target = MakeUser(5, "cajero", true);
|
|
|
|
|
var deactivated = MakeUser(5, "cajero", false);
|
|
|
|
|
|
|
|
|
|
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
|
|
|
|
|
_repo.GetDetailAsync(5, Arg.Any<CancellationToken>()).Returns(deactivated);
|
|
|
|
|
|
|
|
|
|
await _handler.Handle(new DeactivateUsuarioCommand(5));
|
|
|
|
|
|
|
|
|
|
await _refreshRepo.Received(1).RevokeAllActiveForUserAsync(5, Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task Handle_Does_NOT_Revoke_Tokens_When_Already_Inactive_Idempotent()
|
|
|
|
|
{
|
|
|
|
|
var target = MakeUser(5, "cajero", false); // already inactive
|
|
|
|
|
_repo.GetByIdAsync(5, Arg.Any<CancellationToken>()).Returns(target);
|
|
|
|
|
|
|
|
|
|
await _handler.Handle(new DeactivateUsuarioCommand(5));
|
|
|
|
|
|
|
|
|
|
await _refreshRepo.DidNotReceive().RevokeAllActiveForUserAsync(Arg.Any<int>(), Arg.Any<DateTime>(), Arg.Any<CancellationToken>());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
[Fact]
|
|
|
|
|
public async Task Handle_Throws_UsuarioNotFoundException_When_Not_Found()
|
|
|
|
|
{
|
|
|
|
|
_repo.GetByIdAsync(9999, Arg.Any<CancellationToken>()).Returns((Usuario?)null);
|
|
|
|
|
|
|
|
|
|
await Assert.ThrowsAsync<UsuarioNotFoundException>(
|
|
|
|
|
() => _handler.Handle(new DeactivateUsuarioCommand(9999)));
|
|
|
|
|
}
|
|
|
|
|
}
|