backend: Enforce UTF-8 password byte limits

This commit is contained in:
GonnaHetzMe committed 2026-12-05 01:00:00 +01:00
1 parent 0215af0749
commit 9fe713fc10
6 files changed
+44 -25

No files matched your search

@@ -26,11 +26,15 @@ public sealed record AuthResponse(
internal static class PasswordRules internal static class PasswordRules
{ {
public const int MinLength = 8; private const int MinLength = 8;
public const int MaxLength = 64; // BCrypt zpracuje nejvýše 72 bajtů private const int MaxLength = 64;
private const int MaxUtf8Bytes = 72;
public static IRuleBuilderOptions<T, string> ValidPassword<T>(this IRuleBuilder<T, string> rule) => public static IRuleBuilderOptions<T, string?> ValidPassword<T>(this IRuleBuilderInitial<T, string?> rule) =>
rule.NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength); 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<RegisterRequest> public sealed class RegisterRequestValidator : AbstractValidator<RegisterRequest>
@@ -48,9 +52,7 @@ public sealed class ConfirmEmailRequestValidator : AbstractValidator<ConfirmEmai
public ConfirmEmailRequestValidator() public ConfirmEmailRequestValidator()
{ {
RuleFor(x => x.Token).NotEmpty(); RuleFor(x => x.Token).NotEmpty();
RuleFor(x => x.NewPassword).Cascade(CascadeMode.Stop).ValidPassword() RuleFor(x => x.NewPassword).ValidPassword();
.Must(password => Encoding.UTF8.GetByteCount(password) <= 72)
.WithMessage("Heslo může mít nejvýše 72 bajtů v UTF-8.");
} }
} }
@@ -1,4 +1,3 @@
using System.Text;
using FluentValidation; using FluentValidation;
using Helpdesk.Application.Auth; using Helpdesk.Application.Auth;
using Helpdesk.Domain; using Helpdesk.Domain;
@@ -77,11 +76,7 @@ public sealed class SaveAdminUserRequestValidator : AbstractValidator<SaveAdminU
RuleFor(x => x.IsActive).NotNull().WithMessage("Uveďte, zda má být účet aktivní."); RuleFor(x => 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.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.EmailNotificationsEnabled).NotNull().WithMessage("Uveďte, zda mají být e-mailové notifikace zapnuté.");
RuleFor(x => x.Password) RuleFor(x => x.Password).ValidPassword().When(x => x.Password is not null);
.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);
} }
} }
@@ -212,6 +212,11 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF
using var admin = fixture.CreateClient(administrator.AccessToken); using var admin = fixture.CreateClient(administrator.AccessToken);
var request = new SaveAdminUserRequest("[email protected]", "Test", "Účet", null, var request = new SaveAdminUserRequest("[email protected]", "Test", "Účet", null,
"STUDENT", true, true, false, Password); "STUDENT", true, true, false, Password);
var newPassword = new string('č', 36);
var tooLong = newPassword + "a";
var creationError = await ReadAsync<ValidationProblemDetails>(admin.PostAsJsonAsync(Users,
request with { Password = tooLong }, Cancellation), HttpStatusCode.BadRequest);
Assert.Contains("72 bajtů", Assert.Single(creationError.Errors["password"]));
var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created); var created = await ReadAsync<AdminUserDetailsDto>(admin.PostAsJsonAsync(Users, request, Cancellation), HttpStatusCode.Created);
var originalSession = await LoginAsync(anonymous, created.Email); var originalSession = await LoginAsync(anonymous, created.Email);
using var member = fixture.CreateClient(originalSession.AccessToken); 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(member.PostAsJsonAsync(devices, new { token = "old-tablet" }, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(admin.PostAsJsonAsync(devices, new { token = "admin-device" }, 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 edit = request with { Password = newPassword, RowVersion = created.RowVersion };
var editError = await ReadAsync<ValidationProblemDetails>(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(admin.PutAsJsonAsync($"{Users}/{created.Id}", edit, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.Unauthorized);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/refresh", new RefreshTokenRequest(originalSession.RefreshToken), await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/refresh", new RefreshTokenRequest(originalSession.RefreshToken),
@@ -1,6 +1,7 @@
using System.Net; using System.Net;
using System.Net.Http.Json; using System.Net.Http.Json;
using Helpdesk.Api.Controllers; using Helpdesk.Api.Controllers;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Auth; using Helpdesk.Application.Auth;
using Helpdesk.Domain.Auth; using Helpdesk.Domain.Auth;
using Helpdesk.Infrastructure.Persistence; using Helpdesk.Infrastructure.Persistence;
@@ -41,28 +42,39 @@ public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFix
} }
[Fact] [Fact]
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSessionAndRemovesItsDevice() public async Task ResetReplacesALegacyPasswordAndRevokesTheOldSessionAndDevice()
{ {
using var anonymous = fixture.CreateClient(); using var anonymous = fixture.CreateClient();
var user = await fixture.RegisterAsync(anonymous); var user = await fixture.RegisterAsync(anonymous);
using var oldSession = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken); await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var hasher = scope.ServiceProvider.GetRequiredService<IPasswordHasher>();
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<AuthResponse>(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", await ExpectAsync(oldSession.PostAsJsonAsync("/api/v1/devices",
new RegisterDeviceRequest("password-reset-device"), Cancellation), HttpStatusCode.NoContent); new RegisterDeviceRequest("password-reset-device"), Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password", await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password",
new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent); 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 reset = new ResetPasswordRequest(await fixture.TakeResetTokenAsync(user.Email), newPassword);
var validation = await ReadAsync<ValidationProblemDetails>(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.NoContent);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.BadRequest); 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(oldSession.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", 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<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login", var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
new LoginRequest(user.Email, newPassword), Cancellation)); new LoginRequest(user.Email, newPassword), Cancellation));
Assert.Equal(user.Id, session.User.Id); Assert.Equal(user.Id, session.User.Id);
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation)); Assert.False(await db.PushDevices.AnyAsync(device => device.UserId == user.Id, Cancellation));
} }
@@ -6,6 +6,7 @@ using Helpdesk.Application.Users;
using Helpdesk.Domain.Auth; using Helpdesk.Domain.Auth;
using Helpdesk.Domain.Users; using Helpdesk.Domain.Users;
using Helpdesk.Infrastructure.Persistence; using Helpdesk.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using static Helpdesk.IntegrationTests.BackendFixture; using static Helpdesk.IntegrationTests.BackendFixture;
@@ -62,15 +63,17 @@ public sealed class EmailConfirmationTests(BackendFixture fixture) : IClassFixtu
var otherToken = await fixture.TakeConfirmationTokenAsync(address); var otherToken = await fixture.TakeConfirmationTokenAsync(address);
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new { token = original.Token }, Cancellation), await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new { token = original.Token }, Cancellation),
HttpStatusCode.BadRequest); HttpStatusCode.BadRequest);
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(original.Token, new string('č', 37)), Cancellation), var newPassword = new string('č', 36);
HttpStatusCode.BadRequest); var validation = await ReadAsync<ValidationProblemDetails>(anonymous.PostAsJsonAsync(Confirm,
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(original.Token, Password), Cancellation), 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); HttpStatusCode.NoContent);
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(otherToken, oldPassword), Cancellation), await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(otherToken, oldPassword), Cancellation),
HttpStatusCode.BadRequest); HttpStatusCode.BadRequest);
await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, oldPassword), Cancellation), await ExpectAsync(anonymous.PostAsJsonAsync(Login, new LoginRequest(address, oldPassword), Cancellation),
HttpStatusCode.Unauthorized); HttpStatusCode.Unauthorized);
var session = await LoginAsync(anonymous, address); var session = await ReadAsync<AuthResponse>(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)); Assert.Equal((pending.Id, pending.FirstName, pending.LastName), (session.User.Id, session.User.FirstName, session.User.LastName));
} }
} }
+1 -1
View File
@@ -511,7 +511,7 @@ Větvení: `main` (stabilní), `develop`, feature větve `feature/<nazev>`, merg
| Oblast | Řešení | | 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. | | 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). | | 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. | | Š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. |