From 9fe713fc10d626c8051cfb5f80a4691e0cbc23de Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Sat, 5 Dec 2026 01:00:00 +0100 Subject: [PATCH] backend: Enforce UTF-8 password byte limits --- .../src/Helpdesk.Application/Auth/AuthDtos.cs | 16 +++++++------ .../Helpdesk.Application/Users/UserDtos.cs | 7 +----- .../AdminAccountLifecycleTests.cs | 9 ++++++- .../Helpdesk.IntegrationTests/AuthTests.cs | 24 ++++++++++++++----- .../EmailConfirmationTests.cs | 11 +++++---- docs/navrh-aplikace.md | 2 +- 6 files changed, 44 insertions(+), 25 deletions(-) diff --git a/backend/src/Helpdesk.Application/Auth/AuthDtos.cs b/backend/src/Helpdesk.Application/Auth/AuthDtos.cs index 73ef51f..9c9efc6 100644 --- a/backend/src/Helpdesk.Application/Auth/AuthDtos.cs +++ b/backend/src/Helpdesk.Application/Auth/AuthDtos.cs @@ -26,11 +26,15 @@ public sealed record AuthResponse( internal static class PasswordRules { - public const int MinLength = 8; - public const int MaxLength = 64; // BCrypt zpracuje nejvýše 72 bajtů + private const int MinLength = 8; + private const int MaxLength = 64; + private const int MaxUtf8Bytes = 72; - public static IRuleBuilderOptions ValidPassword(this IRuleBuilder rule) => - rule.NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength); + public static IRuleBuilderOptions ValidPassword(this IRuleBuilderInitial rule) => + rule.Cascade(CascadeMode.Stop) + .NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength) + .Must(password => Encoding.UTF8.GetByteCount(password!) <= MaxUtf8Bytes) + .WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8."); } public sealed class RegisterRequestValidator : AbstractValidator @@ -48,9 +52,7 @@ public sealed class ConfirmEmailRequestValidator : AbstractValidator x.Token).NotEmpty(); - RuleFor(x => x.NewPassword).Cascade(CascadeMode.Stop).ValidPassword() - .Must(password => Encoding.UTF8.GetByteCount(password) <= 72) - .WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8."); + RuleFor(x => x.NewPassword).ValidPassword(); } } diff --git a/backend/src/Helpdesk.Application/Users/UserDtos.cs b/backend/src/Helpdesk.Application/Users/UserDtos.cs index 2406423..bccc54e 100644 --- a/backend/src/Helpdesk.Application/Users/UserDtos.cs +++ b/backend/src/Helpdesk.Application/Users/UserDtos.cs @@ -1,4 +1,3 @@ -using System.Text; using FluentValidation; using Helpdesk.Application.Auth; using Helpdesk.Domain; @@ -77,11 +76,7 @@ public sealed class SaveAdminUserRequestValidator : AbstractValidator x.IsActive).NotNull().WithMessage("Uveďte, zda má být účet aktivní."); RuleFor(x => x.EmailConfirmed).NotNull().WithMessage("Uveďte, zda má být e-mail ověřený."); RuleFor(x => x.EmailNotificationsEnabled).NotNull().WithMessage("Uveďte, zda mají být e-mailové notifikace zapnuté."); - RuleFor(x => x.Password) - .NotEmpty().MinimumLength(PasswordRules.MinLength).MaximumLength(PasswordRules.MaxLength) - .Must(password => password is null || Encoding.UTF8.GetByteCount(password) <= 72) - .WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8.") - .When(x => x.Password is not null); + RuleFor(x => x.Password).ValidPassword().When(x => x.Password is not null); } } diff --git a/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs b/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs index 008aebb..542edf3 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AdminAccountLifecycleTests.cs @@ -212,6 +212,11 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF using var admin = fixture.CreateClient(administrator.AccessToken); var request = new SaveAdminUserRequest("password-reset@example.test", "Test", "Účet", null, "STUDENT", true, true, false, Password); + var newPassword = new string('č', 36); + var tooLong = newPassword + "a"; + var creationError = await ReadAsync(admin.PostAsJsonAsync(Users, + request with { Password = tooLong }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("72 bajtů", Assert.Single(creationError.Errors["password"])); var created = await ReadAsync(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created); var originalSession = await LoginAsync(anonymous, created.Email); using var member = fixture.CreateClient(originalSession.AccessToken); @@ -220,8 +225,10 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF 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 }; + var editError = await ReadAsync(admin.PutAsJsonAsync($"{Users}/{created.Id}", + edit with { Password = tooLong }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("72 bajtů", Assert.Single(editError.Errors["password"])); 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), diff --git a/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs index 7ea15d3..1be2be0 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs @@ -1,6 +1,7 @@ using System.Net; using System.Net.Http.Json; using Helpdesk.Api.Controllers; +using Helpdesk.Application.Abstractions; using Helpdesk.Application.Auth; using Helpdesk.Domain.Auth; using Helpdesk.Infrastructure.Persistence; @@ -41,28 +42,39 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture(); + var hasher = scope.ServiceProvider.GetRequiredService(); + var legacyPassword = new string('ž', 37); + var account = await db.Users.SingleAsync(u => u.Id == user.Id, Cancellation); + account.ChangePasswordHash(hasher.Hash(legacyPassword)); + await db.SaveChangesAsync(Cancellation); + + var oldLogin = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", + new LoginRequest(user.Email, legacyPassword), Cancellation)); + using var oldSession = fixture.CreateClient(oldLogin.AccessToken); await ExpectAsync(oldSession.PostAsJsonAsync("/api/v1/devices", new RegisterDeviceRequest("password-reset-device"), Cancellation), HttpStatusCode.NoContent); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password", new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent); - const string newPassword = "New-integration-password"; + var newPassword = new string('č', 36); var reset = new ResetPasswordRequest(await fixture.TakeResetTokenAsync(user.Email), newPassword); + var validation = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", + reset with { NewPassword = newPassword + "a" }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("72 bajtů", Assert.Single(validation.Errors["newPassword"])); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.NoContent); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.BadRequest); await ExpectAsync(oldSession.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", - new LoginRequest(user.Email, Password), Cancellation), HttpStatusCode.Unauthorized); + new LoginRequest(user.Email, legacyPassword), Cancellation), HttpStatusCode.Unauthorized); var session = await ReadAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, newPassword), Cancellation)); Assert.Equal(user.Id, session.User.Id); - await using var scope = fixture.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation)); } diff --git a/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs b/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs index c77d3b9..bd697c9 100644 --- a/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/EmailConfirmationTests.cs @@ -6,6 +6,7 @@ using Helpdesk.Application.Users; using Helpdesk.Domain.Auth; using Helpdesk.Domain.Users; using Helpdesk.Infrastructure.Persistence; +using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using static Helpdesk.IntegrationTests.BackendFixture; @@ -62,15 +63,17 @@ public sealed class EmailConfirmationTests(BackendFixture fixture) : IClassFixtu var otherToken = await fixture.TakeConfirmationTokenAsync(address); await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new { token = original.Token }, Cancellation), HttpStatusCode.BadRequest); - await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(original.Token, new string('č', 37)), Cancellation), - HttpStatusCode.BadRequest); - await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(original.Token, Password), Cancellation), + var newPassword = new string('č', 36); + var validation = await ReadAsync(anonymous.PostAsJsonAsync(Confirm, + new ConfirmEmailRequest(original.Token, newPassword + "a"), Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("72 bajtů", Assert.Single(validation.Errors["newPassword"])); + await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(original.Token, newPassword), Cancellation), HttpStatusCode.NoContent); await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(otherToken, oldPassword), Cancellation), HttpStatusCode.BadRequest); await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, oldPassword), Cancellation), HttpStatusCode.Unauthorized); - var session = await LoginAsync(anonymous, address); + var session = await ReadAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, newPassword), Cancellation)); Assert.Equal((pending.Id, pending.FirstName, pending.LastName), (session.User.Id, session.User.FirstName, session.User.LastName)); } } diff --git a/docs/navrh-aplikace.md b/docs/navrh-aplikace.md index 278457d..60365d9 100644 --- a/docs/navrh-aplikace.md +++ b/docs/navrh-aplikace.md @@ -511,7 +511,7 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/`, merg | Oblast | Řešení | |---|---| -| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Min. délka hesla 8 znaků. | +| Hesla | Hash BCrypt (knihovna BCrypt.Net-Next, work factor 12; sůl je součástí hashe). Nové heslo má 8–64 znaků a nejvýše 72 bajtů v UTF-8. | | Přihlášení | Neúspěšné ověření vrací jednotnou odpověď, BCrypt se provádí i pro neznámý účet. Každá instance API omezuje přihlášení na 5 pokusů za minutu pro dvojici klientská IP a normalizovaný e-mail. Pro `/api/v1/auth/*` platí také limit 20 požadavků za minutu na klientskou IP. | | Tokeny | Všechny tokeny jsou podepsané JWT podle RFC 7519 s unikátním `jti` a typem v hlavičce. V databázi není žádný token ani jeho hash (kap. 10.1). | | Šifrování citlivých údajů | Telefonní číslo uživatele šifrováno AES-256-GCM (EF Core value converter), klíč mimo DB – v proměnné prostředí / Docker secret. Přenos výhradně HTTPS (TLS 1.2+), HSTS. |