backend + web: Improve validation and email retry handling

This commit is contained in:
GonnaHetzMe committed 2026-12-05 02:42:22 +01:00
1 parent e9782a1413
commit 722d318898
13 files changed
+195 -44

No files matched your search

@@ -41,6 +41,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
[RequestSizeLimit(AttachmentLimits.MaxRequestBytes)]
[RequestFormLimits(MultipartBodyLengthLimit = AttachmentLimits.MaxRequestBytes)]
[ProducesResponseType<IssueDetail>(StatusCodes.Status201Created)]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status413PayloadTooLarge)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status415UnsupportedMediaType)]
[ProducesResponseType<ProblemDetails>(StatusCodes.Status429TooManyRequests)]
@@ -55,7 +56,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
var form = await ReadFormAsync(ct);
request = new CreateIssueRequest(
form["title"].ToString(), form["description"].ToString(),
ReadId(form, "categoryId") ?? throw new BadRequestException("Kategorie je povinná."),
ReadId(form, "categoryId") ?? 0,
ReadId(form, "buildingId"), form["locationDetail"].ToString());
uploads = ReadUploads(form.Files);
}
@@ -87,6 +88,7 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
}
[HttpPut("{id:int}")]
[ProducesResponseType<ValidationProblemDetails>(StatusCodes.Status400BadRequest)]
public Task<IssueDetail> Edit(int id, EditIssueRequest request, CancellationToken ct) =>
issues.EditAsync(id, request, ct);
@@ -160,16 +162,16 @@ public sealed class IssuesController(IssueService issues) : ControllerBase
if (string.IsNullOrWhiteSpace(value))
return null;
if (!int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var id))
throw new BadRequestException($"Neplatná hodnota {key}.");
throw new FieldValidationException(key, "Zadejte platné ID.");
return id;
}
private static AttachmentUpload[] ReadUploads(IFormFileCollection files)
{
if (files.Count > AttachmentLimits.MaxFiles)
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
throw new FieldValidationException("files", "Najednou lze přiložit nejvýše pět souborů.");
if (files.Any(file => file.Name != "files"))
throw new BadRequestException("Přílohy patří do pole files.");
throw new FieldValidationException("files", "Přílohy patří do pole files.");
return files.Select(file => new AttachmentUpload(file.FileName, file.Length, file.OpenReadStream)).ToArray();
}
@@ -29,7 +29,7 @@ public sealed class AuthService(
await registerValidator.ValidateAndThrowAsync(request, ct);
var role = _registration.ResolveRole(request.Email)
?? throw new BadRequestException("Registrace je možná jen s univerzitním e-mailem.");
?? throw new FieldValidationException(nameof(request.Email), "Registrace je možná jen s univerzitním e-mailem.");
var normalized = User.NormalizeEmail(request.Email);
var user = await db.Users.SingleOrDefaultAsync(u => u.EmailNormalized == normalized, ct);
@@ -1,3 +1,6 @@
using FluentValidation;
using FluentValidation.Results;
namespace Helpdesk.Application.Common;
/// <summary>Chyba aplikační vrstvy; API ji převádí na ProblemDetails s odpovídajícím HTTP stavem.</summary>
@@ -12,7 +15,7 @@ public sealed class NotFoundException(string message) : AppException(message)
public override int StatusCode => 404;
}
public sealed class ConflictException(string message) : AppException(message)
public sealed class ConflictException(string message, string? problemType = null) : AppException(message, problemType)
{
public override int StatusCode => 409;
}
@@ -38,8 +41,13 @@ public sealed class BadRequestException(string message) : AppException(message)
public override int StatusCode => 400;
}
public sealed class FieldValidationException(string field, string message)
: ValidationException([new ValidationFailure(field, message)])
{
}
public sealed class EmailDeliveryException(string reason, bool retryable)
: AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.")
: AppException("E-mail se nepodařilo odeslat. Zkuste požadavek později.", "urn:ntbug:email-delivery-failed")
{
public string Reason { get; } = reason;
public bool Retryable { get; } = retryable;
@@ -1,4 +1,6 @@
using System.Text;
using FluentValidation;
using FluentValidation.Results;
using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Common;
using Helpdesk.Application.Notifications;
@@ -44,11 +46,17 @@ public sealed partial class IssueService(
CheckVersion(issue, request.RowVersion);
var assignee = await db.Users.AsNoTracking().SingleOrDefaultAsync(u => u.Id == request.AssigneeId && u.IsActive, ct);
if (assignee is null || !Issue.CanBeAssigned(assignee.Role))
throw new BadRequestException("Vyberte aktivního správce budov, člena vedení nebo administrátora.");
throw new FieldValidationException(nameof(request.AssigneeId), "Vyberte aktivního správce budov, člena vedení nebo administrátora.");
if (issue.AssigneeId == assignee.Id)
throw new ConflictException("Závada je již přiřazena tomuto řešiteli.");
IssuePriority? priority = request.Priority is null ? null : ParseCode<IssuePriority>(request.Priority);
IssuePriority? priority = null;
if (request.Priority is { } code)
{
if (!EnumCode.TryParse<IssuePriority>(code, out var selected))
throw new FieldValidationException(nameof(request.Priority), "Vyberte platnou prioritu.");
priority = selected;
}
var from = issue.Status;
issue.Assign(actor.Id, actor.Role, assignee.Id, assignee.Role, priority);
AddEvent(issue, IssueEventType.Assigned, from, actor, assignee.FullName);
@@ -65,8 +73,8 @@ public sealed partial class IssueService(
var (issue, actor) = await LoadActionAsync(id, action, ct);
CheckVersion(issue, version);
note = action is IssueAction.Reopen or IssueAction.Reject
? RequiredText(note, "Důvod", MaxTextBytes)
: OptionalText(note, "Poznámka", MaxTextBytes);
? RequiredText(note, nameof(IssueReasonRequest.Reason), "Důvod")
: OptionalText(note, nameof(VerifyIssueRequest.Note), "Poznámka");
var from = issue.Status;
issue.Transition(action, actor.Id, actor.Role, note);
@@ -87,7 +95,7 @@ public sealed partial class IssueService(
public async Task<IssueEventDto> CommentAsync(int id, CommentRequest request, CancellationToken ct)
{
var (issue, actor) = await LoadActionAsync(id, IssueAction.Comment, ct);
var text = RequiredText(request.Text, "Komentář", MaxTextBytes);
var text = RequiredText(request.Text, nameof(request.Text), "Komentář");
issue.RecordParticipation(IssueAction.Comment, actor.Id, actor.Role);
var entry = AddEvent(issue, IssueEventType.Commented, null, actor, text);
int[] recipients = issue.AssigneeId is int assignee ? [issue.ReporterId, assignee] : [issue.ReporterId];
@@ -102,7 +110,7 @@ public sealed partial class IssueService(
var (issue, actor) = await LoadActionAsync(id, IssueAction.AddAttachments, ct);
var uploads = await readUploads(ct);
if (uploads.Length == 0)
throw new BadRequestException("Vyberte alespoň jeden soubor.");
throw new FieldValidationException("files", "Vyberte alespoň jeden soubor.");
issue.RecordParticipation(IssueAction.AddAttachments, actor.Id, actor.Role);
var attachments = await SaveWithAttachmentsAsync(issue, uploads, ct);
@@ -113,7 +121,7 @@ public sealed partial class IssueService(
Issue issue, IReadOnlyList<AttachmentUpload> uploads, CancellationToken ct)
{
if (uploads.Count > AttachmentLimits.MaxFiles)
throw new BadRequestException("Najednou lze přiložit nejvýše pět souborů.");
throw new FieldValidationException("files", "Najednou lze přiložit nejvýše pět souborů.");
var attachments = new List<Attachment>(uploads.Count);
var saving = false;
@@ -172,18 +180,31 @@ public sealed partial class IssueService(
private async Task ValidateDetailsAsync(CreateIssueRequest request, Issue? original, CancellationToken ct)
{
var title = RequiredText(request.Title, "Název", MaxTextBytes);
RequiredText(request.Description, "Popis", MaxTextBytes);
if (title.Length > 200 || request.LocationDetail?.Trim().Length > 255)
throw new BadRequestException("Název smí mít nejvýše 200 znaků a upřesnění místa 255 znaků.");
var errors = new List<ValidationFailure>();
var title = request.Title?.Trim();
if (string.IsNullOrEmpty(title))
errors.Add(new(nameof(request.Title), "Zadejte název."));
else if (title.Length > 200)
errors.Add(new(nameof(request.Title), "Název může mít nejvýše 200 znaků."));
var description = request.Description?.Trim();
if (string.IsNullOrEmpty(description))
errors.Add(new(nameof(request.Description), "Popište závadu."));
else if (Encoding.UTF8.GetByteCount(description) > MaxTextBytes)
errors.Add(new(nameof(request.Description), "Popis je příliš dlouhý."));
if (request.LocationDetail?.Trim().Length > 255)
errors.Add(new(nameof(request.LocationDetail), "Upřesnění místa může mít nejvýše 255 znaků."));
if (original?.CategoryId != request.CategoryId &&
!await db.IssueCategories.AnyAsync(c => c.Id == request.CategoryId && c.IsActive, ct))
throw new BadRequestException("Vyberte aktivní kategorii závady.");
errors.Add(new(nameof(request.CategoryId), "Vyberte aktivní kategorii závady."));
if (request.BuildingId is int buildingId && original?.BuildingId != buildingId &&
!await db.Buildings.AnyAsync(b => b.Id == buildingId && b.IsActive, ct))
throw new BadRequestException("Vyberte aktivní budovu.");
errors.Add(new(nameof(request.BuildingId), "Vyberte aktivní budovu."));
if (errors.Count > 0)
throw new ValidationException(errors);
}
private IssueEvent AddEvent(Issue issue, IssueEventType type, IssueStatus? fromStatus, User actor, string? note)
@@ -201,30 +222,33 @@ public sealed partial class IssueService(
}
catch (DbUpdateConcurrencyException)
{
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
throw IssueVersionConflict();
}
}
private static void CheckVersion(Issue issue, int? supplied)
{
if (supplied is null or < 0)
throw new BadRequestException("Zadejte platnou hodnotu rowVersion.");
throw new FieldValidationException(nameof(IssueVersionRequest.RowVersion), "Zadejte platnou verzi závady.");
if (issue.RowVersion != supplied)
throw new ConflictException("Závada se mezitím změnila. Načtěte aktuální stav.");
throw IssueVersionConflict();
}
private static ConflictException IssueVersionConflict() =>
new("Závada se mezitím změnila. Načtěte aktuální stav.", "urn:ntbug:issue-version-conflict");
private const int MaxTextBytes = 65_535;
private static string RequiredText(string? input, string name, int maxBytes) =>
OptionalText(input, name, maxBytes) ?? throw new BadRequestException($"{name}: hodnota je povinná.");
private static string RequiredText(string? input, string field, string label) =>
OptionalText(input, field, label) ?? throw new FieldValidationException(field, $"{label}: hodnota je povinná.");
private static string? OptionalText(string? input, string name, int maxBytes)
private static string? OptionalText(string? input, string field, string label)
{
var text = input?.Trim();
if (string.IsNullOrEmpty(text))
return null;
if (Encoding.UTF8.GetByteCount(text) > maxBytes)
throw new BadRequestException($"{name}: hodnota je příliš dlouhá.");
if (Encoding.UTF8.GetByteCount(text) > MaxTextBytes)
throw new FieldValidationException(field, $"{label}: hodnota je příliš dlouhá.");
return text;
}
@@ -13,11 +13,11 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
public async Task<StoredAttachment> SaveAsync(AttachmentUpload upload, CancellationToken ct)
{
if (upload.SizeBytes is <= 0 or > AttachmentLimits.MaxFileBytes)
throw new BadRequestException("Příloha musí mít velikost od 1 B do 10 MB.");
throw new FieldValidationException("files", "Příloha musí mít velikost od 1 B do 10 MB.");
var name = Path.GetFileName(upload.FileName.Replace('\\', '/')).Trim();
if (name.Length is 0 or > 255 || name.Any(char.IsControl))
throw new BadRequestException("Neplatný název přílohy.");
throw new FieldValidationException("files", "Neplatný název přílohy.");
var extension = Path.GetExtension(name).ToLowerInvariant();
var contentType = extension switch
@@ -27,7 +27,7 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
".heic" => "image/heic",
".pdf" => "application/pdf",
".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
_ => throw new BadRequestException("Tento typ přílohy není povolen."),
_ => throw new FieldValidationException("files", "Tento typ přílohy není povolen."),
};
Directory.CreateDirectory(UploadDirectory);
@@ -49,16 +49,16 @@ internal sealed class FileAttachmentStore(ILogger<FileAttachmentStore> logger) :
{
written += read;
if (written > upload.SizeBytes)
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
throw new FieldValidationException("files", "Velikost přílohy neodpovídá požadavku.");
await output.WriteAsync(buffer.AsMemory(0, read), ct);
}
if (written != upload.SizeBytes)
throw new BadRequestException("Velikost přílohy neodpovídá požadavku.");
throw new FieldValidationException("files", "Velikost přílohy neodpovídá požadavku.");
output.Position = 0;
if (!await HasExpectedFormatAsync(output, extension, ct))
throw new BadRequestException("Obsah přílohy neodpovídá její příponě.");
throw new FieldValidationException("files", "Obsah přílohy neodpovídá její příponě.");
return new StoredAttachment(name, key, contentType, written);
}
@@ -5,6 +5,7 @@ using System.Net.Http.Json;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Issues;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using static Helpdesk.IntegrationTests.BackendFixture;
@@ -49,7 +50,8 @@ public sealed class AttachmentTests(BackendFixture fixture) : IClassFixture<Back
using var mixed = new MultipartFormDataContent();
AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray());
await ExpectAsync(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest);
var validation = await ReadAsync<ValidationProblemDetails>(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest);
Assert.Equal("files", Assert.Single(validation.Errors.Keys));
using var wrongField = new MultipartFormDataContent();
wrongField.Add(new ByteArrayContent(png), "image", "zamek.png");
@@ -19,6 +19,32 @@ public sealed class EmailConfirmationTests(BackendFixture fixture) : IClassFixtu
private const string Confirm = "/api/v1/auth/confirm-email";
private const string Login = "/api/v1/auth/login";
[Fact]
public async Task FailedRegistrationEmailCanBeRetriedForTheSameAccount()
{
using var anonymous = fixture.CreateClient();
const string address = "[email protected]";
var request = new RegisterRequest(address, "Jan", "Novák");
fixture.FailNextEmail(address, "SMTP_UNAVAILABLE", retryable: true);
var failure = await ReadAsync<ProblemDetails>(anonymous.PostAsJsonAsync(Register, request, Cancellation),
HttpStatusCode.ServiceUnavailable);
Assert.Equal("urn:ntbug:email-delivery-failed", failure.Type);
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var pending = await db.Users.AsNoTracking().SingleAsync(user => user.Email == address, Cancellation);
Assert.False(pending.EmailConfirmed);
Assert.Empty(pending.PasswordHash);
var retried = await ReadAsync<UserDto>(anonymous.PostAsJsonAsync(Register, request, Cancellation), HttpStatusCode.Created);
Assert.Equal(pending.Id, retried.Id);
var token = await fixture.TakeConfirmationTokenAsync(address);
await ExpectAsync(anonymous.PostAsJsonAsync(Confirm, new ConfirmEmailRequest(token, Password), Cancellation),
HttpStatusCode.NoContent);
Assert.Equal(pending.Id, (await LoginAsync(anonymous, address)).User.Id);
}
[Fact]
public async Task RegistrationHasNoPasswordUntilTheMailboxOwnerSetsIt()
{
@@ -5,12 +5,46 @@ using Helpdesk.Application.Common;
using Helpdesk.Application.Issues;
using Helpdesk.Application.Notifications;
using Helpdesk.Application.Statistics;
using Microsoft.AspNetCore.Mvc;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task IssueValidationReturnsErrorsWithFieldNames()
{
using var anonymous = fixture.CreateClient();
var administrator = await LoginAsync(anonymous, AdminEmail);
using var admin = fixture.CreateClient(administrator.AccessToken);
const string issues = "/api/v1/issues";
var invalid = new CreateIssueRequest(new string('t', 201), " ", int.MaxValue, int.MaxValue, new string('l', 256));
var creationError = await ReadAsync<ValidationProblemDetails>(admin.PostAsJsonAsync(issues, invalid, Cancellation),
HttpStatusCode.BadRequest);
Assert.Equal(["buildingId", "categoryId", "description", "locationDetail", "title"], creationError.Errors.Keys.Order());
using var form = new MultipartFormDataContent { { new StringContent("invalid"), "categoryId" } };
var uploadError = await ReadAsync<ValidationProblemDetails>(admin.PostAsync(issues, form, Cancellation), HttpStatusCode.BadRequest);
Assert.Equal("categoryId", Assert.Single(uploadError.Errors.Keys));
var categories = await ReadAsync<CategoryDto[]>(admin.GetAsync("/api/v1/issue-categories", Cancellation));
var issue = await PostIssueAsync(admin, issues, new CreateIssueRequest("Projektor", "Bliká.", categories[0].Id, null, null),
HttpStatusCode.Created);
var path = $"{issues}/{issue.Id}";
var edit = new EditIssueRequest(issue.Title, issue.Description, int.MaxValue, null, null, issue.RowVersion);
var editError = await ReadAsync<ValidationProblemDetails>(admin.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.BadRequest);
Assert.Equal("categoryId", Assert.Single(editError.Errors.Keys));
var assign = new AssignIssueRequest(administrator.User.Id, "UNKNOWN", issue.RowVersion);
var priorityError = await ReadAsync<ValidationProblemDetails>(admin.PostAsJsonAsync(path + "/assign", assign, Cancellation),
HttpStatusCode.BadRequest);
Assert.Equal("priority", Assert.Single(priorityError.Errors.Keys));
var saved = await ReadAsync<IssueDetail>(admin.GetAsync(path, Cancellation));
Assert.Equal((issue.RowVersion, issue.CategoryId, issue.AssigneeId), (saved.RowVersion, saved.CategoryId, saved.AssigneeId));
}
[Fact]
public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt()
{
@@ -52,8 +86,9 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<B
var assignable = await ReadAsync<AssignableUserDto[]>(admin.GetAsync("/api/v1/users/assignable", Cancellation));
Assert.Contains(assignable, user => user.Id == firstAssignee.User.Id);
Assert.Contains(assignable, user => user.Id == administrator.User.Id);
await ExpectAsync(firstSolver.PostAsJsonAsync(path + "/start",
var conflict = await ReadAsync<ProblemDetails>(firstSolver.PostAsJsonAsync(path + "/start",
new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict);
Assert.Equal("urn:ntbug:issue-version-conflict", conflict.Type);
var reporterNotifications = await InboxAsync(reporter, issue.Id);
Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type);