backend: Enforce UTF-8 password byte limits
This commit is contained in:
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
|
||||
{
|
||||
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<T, string> ValidPassword<T>(this IRuleBuilder<T, string> rule) =>
|
||||
rule.NotEmpty().MinimumLength(MinLength).MaximumLength(MaxLength);
|
||||
public static IRuleBuilderOptions<T, string?> ValidPassword<T>(this IRuleBuilderInitial<T, string?> 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<RegisterRequest>
|
||||
@@ -48,9 +52,7 @@ public sealed class ConfirmEmailRequestValidator : AbstractValidator<ConfirmEmai
|
||||
public ConfirmEmailRequestValidator()
|
||||
{
|
||||
RuleFor(x => 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();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<SaveAdminU
|
||||
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.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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -212,6 +212,11 @@ public sealed class AdminAccountLifecycleTests(BackendFixture fixture) : IClassF
|
||||
using var admin = fixture.CreateClient(administrator.AccessToken);
|
||||
var request = new SaveAdminUserRequest("[email protected]", "Test", "Účet", null,
|
||||
"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 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<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(member.PostAsJsonAsync(devices, new { token = "old-phone" }, Cancellation), HttpStatusCode.Unauthorized);
|
||||
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/refresh", new RefreshTokenRequest(originalSession.RefreshToken),
|
||||
|
||||
@@ -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<BackendFix
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSessionAndRemovesItsDevice()
|
||||
public async Task ResetReplacesALegacyPasswordAndRevokesTheOldSessionAndDevice()
|
||||
{
|
||||
using var anonymous = fixture.CreateClient();
|
||||
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",
|
||||
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<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.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<AuthResponse>(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<HelpdeskDbContext>();
|
||||
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.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<ValidationProblemDetails>(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<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));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user