backend: Add concurrency checks to admin user edits

This commit is contained in:
GonnaHetzMe committed 2026-12-04 18:25:30 +01:00
1 parent 91d0c06c83
commit bd8eb65e56
18 files changed
+216 -23

No files matched your search

@@ -36,6 +36,7 @@ public sealed class AdminUsersController(UserService users, ICurrentUser current
[HttpPut("{id:int}")]
[ProducesResponseType<AdminUserDetailsDto>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Update(int id, SaveAdminUserRequest request, CancellationToken ct)
{
var result = await users.UpdateAsync(currentUser, id, request, ct);
@@ -20,7 +20,7 @@ internal sealed class AppExceptionHandler(IProblemDetailsService problemDetails)
Status = StatusCodes.Status400BadRequest,
Title = "Neplatná vstupní data.",
},
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message },
AppException app => new ProblemDetails { Status = app.StatusCode, Title = app.Message, Type = app.ProblemType },
BadHttpRequestException request => new ProblemDetails { Status = request.StatusCode },
_ => null,
};
@@ -1,9 +1,10 @@
namespace Helpdesk.Application.Common;
/// <summary>Chyba aplikační vrstvy; API ji převádí na ProblemDetails s odpovídajícím HTTP stavem.</summary>
public abstract class AppException(string message) : Exception(message)
public abstract class AppException(string message, string? problemType = null) : Exception(message)
{
public abstract int StatusCode { get; }
public string? ProblemType { get; } = problemType;
}
public sealed class NotFoundException(string message) : AppException(message)
@@ -16,6 +17,12 @@ public sealed class ConflictException(string message) : AppException(message)
public override int StatusCode => 409;
}
public sealed class AccountVersionConflictException()
: AppException("Účet se mezitím změnil. Načtěte jeho aktuální údaje a změny zadejte znovu.", "urn:ntbug:account-version-conflict")
{
public override int StatusCode => 409;
}
public sealed class ForbiddenException(string message) : AppException(message)
{
public override int StatusCode => 403;
@@ -1,5 +1,6 @@
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Domain.Auth;
using Microsoft.EntityFrameworkCore;
namespace Helpdesk.Application.Notifications;
@@ -14,6 +15,11 @@ public sealed class PushDeviceService(IAppDbContext db, ICurrentUser currentUser
if (user is not { IsActive: true, IsDeleted: false })
throw new UnauthorizedException("Účet není aktivní.");
// Po čekání na zámek mohl správce relaci odhlásit a odstranit všechna její zařízení.
if (!await db.AuthTokens.AnyAsync(t => t.Jti == currentUser.TokenId && t.UserId == user.Id &&
t.TokenType == TokenType.Access && t.RevokedAt == null, ct))
throw new UnauthorizedException("Přihlášení vypršelo. Přihlaste se znovu.");
await db.RegisterPushDeviceAsync(user.Id, token, ct);
await transaction.CommitAsync(ct);
}
@@ -49,14 +49,15 @@ public sealed record ChangeRoleRequest(string Role);
public sealed record SetActiveRequest(bool IsActive);
public sealed record AdminUserDetailsDto(int Id, string Email, string FirstName, string LastName, string? Phone,
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, bool? VerificationEmailSent = null)
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, int RowVersion,
bool? VerificationEmailSent = null)
{
public static AdminUserDetailsDto From(User user) => new(user.Id, user.Email, user.FirstName, user.LastName, user.Phone,
user.Role.ToCode(), user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled);
user.Role.ToCode(), user.IsActive, user.EmailConfirmed, user.EmailNotificationsEnabled, user.RowVersion);
}
public sealed record SaveAdminUserRequest(string Email, string FirstName, string LastName, string? Phone,
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password);
string Role, bool IsActive, bool EmailConfirmed, bool EmailNotificationsEnabled, string? Password, int? RowVersion = null);
public sealed class SaveAdminUserRequestValidator : AbstractValidator<SaveAdminUserRequest>
{
@@ -105,12 +105,18 @@ public sealed class UserService(
public async Task<AdminUserDetailsDto?> UpdateAsync(ICurrentUser admin, int userId, SaveAdminUserRequest request, CancellationToken ct)
{
if (request.RowVersion is null or < 0)
throw new BadRequestException("Zadejte platnou verzi účtu (rowVersion).");
await ValidateAsync(request, ct);
var role = ParseRole(request.Role);
var passwordHash = request.Password is null ? null : passwordHasher.Hash(request.Password);
var sendLink = false;
var updated = await UpdateAccountsAsync(admin, [userId], user =>
{
if (user.RowVersion != request.RowVersion)
throw new AccountVersionConflictException();
var emailChanged = user.EmailNormalized != User.NormalizeEmail(request.Email);
var confirmed = !emailChanged && request.EmailConfirmed;
var confirmationChanged = user.EmailConfirmed != confirmed;
@@ -119,12 +125,13 @@ public sealed class UserService(
ApplyProfile(user, request with { EmailConfirmed = confirmed });
sendLink = emailChanged && user.IsActive;
if (passwordHash is not null)
{
user.ChangePasswordHash(passwordHash);
return RevokeReason.PasswordChanged;
}
if (emailChanged || confirmationChanged)
return RevokeReason.LogoutAll;
if (passwordHash is not null)
return RevokeReason.PasswordChanged;
return roleChanged ?? activeChanged;
}, ct);
return sendLink ? await AccountSavedAsync(updated.Single(), ct) : null;
@@ -186,9 +193,11 @@ public sealed class UserService(
var revoked = new List<TokenRevocationService.RevokedAccessToken>();
foreach (var group in changes.GroupBy(change => change.Reason))
revoked.AddRange(await revocation.StageRevokeAllAsync(group.Select(change => change.Id).ToArray(), group.Key, ct));
var deletedIds = users.Where(user => user.IsDeleted).Select(user => user.Id).ToArray();
if (deletedIds.Length > 0)
await db.PushDevices.Where(device => deletedIds.Contains(device.UserId)).ExecuteDeleteAsync(ct);
var disconnectedIds = users.Where(user => user.IsDeleted).Select(user => user.Id)
.Concat(changes.Where(change => change.Reason == RevokeReason.PasswordChanged).Select(change => change.Id))
.ToArray();
if (disconnectedIds.Length > 0)
await db.PushDevices.Where(device => disconnectedIds.Contains(device.UserId)).ExecuteDeleteAsync(ct);
await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct);
@@ -26,6 +26,7 @@ public sealed class User : IHasCreatedAt
public bool EmailNotificationsEnabled { get; private set; } = true;
public int FailedLoginCount { get; private set; }
public DateTime? LockoutUntil { get; private set; }
public int RowVersion { get; private set; }
public DateTime CreatedAt { get; set; }
public string FullName => $"{FirstName} {LastName}";
@@ -16,6 +16,7 @@ internal sealed class UserConfiguration(FieldEncryptor encryptor) : IEntityTypeC
b.Property(u => u.Email).HasMaxLength(254);
b.Property(u => u.EmailNormalized).HasMaxLength(254);
b.HasIndex(u => u.EmailNormalized).IsUnique();
b.Property(u => u.RowVersion).IsConcurrencyToken();
b.Property(u => u.Role).HasConversion<EnumCodeConverter<UserRole>>().HasMaxLength(30);
b.Property(u => u.Phone)
.HasColumnName("phone_encrypted")
@@ -42,6 +42,17 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
foreach (var entry in ChangeTracker.Entries<User>())
{
if (entry.State == EntityState.Modified && entry.Properties.Any(property =>
property.IsModified && property.Metadata.Name is not (
nameof(User.FailedLoginCount) or nameof(User.LockoutUntil) or nameof(User.RowVersion))))
{
var version = entry.Property(user => user.RowVersion);
version.CurrentValue = checked(version.OriginalValue + 1);
}
}
try
{
return await base.SaveChangesAsync(cancellationToken);
@@ -58,6 +69,10 @@ public sealed class HelpdeskDbContext(DbContextOptions<HelpdeskDbContext> option
{
throw new ConflictException("Účet s tímto e-mailem už existuje.");
}
catch (DbUpdateConcurrencyException exception) when (exception.Entries is [var entry] && entry.Entity is User)
{
throw new AccountVersionConflictException();
}
}
public Task<IDbContextTransaction> BeginWriteAsync(CancellationToken ct) =>
@@ -1,13 +1,17 @@
using System.Net;
using System.Net.Http.Json;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Auth;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Common;
using Helpdesk.Application.Issues;
using Helpdesk.Application.Notifications;
using Helpdesk.Application.Users;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.JsonWebTokens;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
@@ -39,7 +43,11 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF
var issue = await ReadAsync<IssueDetail>(student.PostAsJsonAsync("/api/v1/issues",
new CreateIssueRequest("Rozbitý zámek", "Učebnu nelze otevřít.", category.Id, null, null), Cancellation), HttpStatusCode.Created);
var edit = request with { Email = "[email protected]", FirstName = "Jana", Role = "TEACHER", Password = "New-password-for-test" };
var edit = request with
{
Email = "[email protected]", FirstName = "Jana", Role = "TEACHER",
Password = "New-password-for-test", RowVersion = created.RowVersion,
};
var saved = await ReadAsync<AdminUserDetailsDto>(admin.PutAsJsonAsync(path, edit, Cancellation));
Assert.False(saved.EmailConfirmed);
Assert.True(saved.VerificationEmailSent);
@@ -95,7 +103,7 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF
Assert.False(created.EmailConfirmed);
var originalToken = await fixture.TakeConfirmationTokenAsync(request.Email);
var moved = request with { Email = "[email protected]", Password = null };
var moved = request with { Email = "[email protected]", Password = null, RowVersion = created.RowVersion };
var updated = await ReadAsync<AdminUserDetailsDto>(admin.PutAsJsonAsync($"{Users}/{created.Id}", moved, Cancellation));
Assert.True(updated.VerificationEmailSent);
await ConfirmEmailAsync(anonymous, originalToken, HttpStatusCode.BadRequest);
@@ -112,6 +120,80 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF
Assert.Equal(saved.Id, (await LoginAsync(anonymous, retry.Email)).User.Id);
}
[Fact]
public async Task StaleAccountEditCannotRestoreAnOldRoleOrReactivateAnAccount()
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var request = new SaveAdminUserRequest("[email protected]", "Test", "Uživatel", null,
"FACILITY_MANAGER", true, true, false, Password);
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
var path = $"{Users}/{created.Id}";
var edit = request with { Password = null, Phone = "+420 123 456 789" };
await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.BadRequest);
await ExpectAsync(admin.PutAsJsonAsync(path + "/role", new ChangeRoleRequest("STUDENT"), Cancellation), HttpStatusCode.NoContent);
var conflict = await ReadAsync<ProblemDetails>(
admin.PutAsJsonAsync(path, edit with { RowVersion = created.RowVersion }, Cancellation), HttpStatusCode.Conflict);
Assert.Equal("urn:ntbug:account-version-conflict", conflict.Type);
var current = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
Assert.Equal("STUDENT", current.Role);
Assert.Null(current.Phone);
Assert.True(current.RowVersion > created.RowVersion);
edit = edit with { Role = current.Role, RowVersion = current.RowVersion };
await ExpectAsync(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.NoContent);
var refreshed = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
Assert.Equal(edit.Phone, refreshed.Phone);
await ExpectAsync(admin.PostAsJsonAsync(Users + "/bulk",
new BulkAdminUsersRequest([created.Id], "deactivate", null), Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(admin.PutAsJsonAsync(path, edit with
{
RowVersion = refreshed.RowVersion, Phone = "+420 987 654 321",
}, Cancellation), HttpStatusCode.Conflict);
var deactivated = await ReadAsync<AdminUserDetailsDto>(admin.GetAsync(path, Cancellation));
Assert.False(deactivated.IsActive);
Assert.Equal(edit.Phone, deactivated.Phone);
}
[Fact]
public async Task AdminPasswordResetDisconnectsDevicesAndRejectsLateRegistrationsFromTheOldSession()
{
using var anonymous = fixture.CreateClient();
var administrator = await LoginAsync(anonymous, AdminEmail);
using var admin = fixture.CreateClient(administrator.AccessToken);
var request = new SaveAdminUserRequest("[email protected]", "Test", "Účet", null,
"STUDENT", true, true, false, Password);
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
var originalSession = await LoginAsync(anonymous, created.Email);
using var member = fixture.CreateClient(originalSession.AccessToken);
const string devices = "/api/v1/devices";
await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-tablet" }, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(admin.PostAsJsonAsync(devices, new { token = "admin-device" }, Cancellation), HttpStatusCode.NoContent);
const string newPassword = "Admin-reset-password";
var edit = request with { Password = newPassword, RowVersion = created.RowVersion };
await ExpectAsync(admin.PutAsJsonAsync($"{Users}/{created.Id}", edit, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.Unauthorized);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/refresh", new RefreshTokenRequest(originalSession.RefreshToken),
Cancellation), HttpStatusCode.Unauthorized);
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var oldSession = new CurrentSession(created.Id, new JsonWebToken(originalSession.AccessToken).Id);
await Assert.ThrowsAsync<UnauthorizedException>(() =>
new PushDeviceService(db, oldSession).RegisterAsync("late-registration", Cancellation));
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == created.Id, Cancellation));
Assert.True(await db.PushDevices.AnyAsync(device => device.UserId == administrator.User.Id && device.FcmToken == "admin-device", Cancellation));
var newSession = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
new LoginRequest(created.Email, newPassword), Cancellation));
using var signedIn = fixture.CreateClient(newSession.AccessToken);
await ExpectAsync(signedIn.PostAsJsonAsync(devices, new { token = "new-phone" }, Cancellation), HttpStatusCode.NoContent);
}
[Fact]
public async Task BulkActionsUpdateAllSelectedAccountsAndRejectTheEntireInvalidSelection()
{
@@ -150,4 +232,6 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF
private static Task ConfirmEmailAsync(HttpClient client, string token, HttpStatusCode expected = HttpStatusCode.NoContent) =>
ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", new EmailTokenRequest(token), Cancellation), expected);
private sealed record CurrentSession(int Id, string TokenId) : ICurrentUser;
}