Merge pull request #307 from BinaryAlley/refactor/use-contributor-references-on-book-page

Uses contributor references on the book page
This commit is contained in:
BinaryAlley authored and GitHub committed 2026-11-27 18:58:28 +02:00
commit 3fb8912c7f
35 files changed
+737 -199

No files matched your search

+22
View File
@@ -179,6 +179,7 @@ Known page keys:
| `shared/audio-player/queue-item` | The queue item of the audio player bar. |
| `shared/audio-player/playlist-item` | The playlist item of the audio player bar. |
| `library/written-content-library/book-library/books/index` | The books browsing page. |
| `library/written-content-library/book-library/books/item` | The details and editing page of a book. |
| `library/written-content-library/book-library/books/deleted-items` | The deleted items page of a book library, which restores deleted books. |
| `library/audio-library/music-library/deleted-items` | The deleted items page of a music library, which restores deleted artists, albums and tracks. |
| `playlists/index` | The page that lists and deletes the playlists of the current user. |
@@ -590,6 +591,27 @@ The page script renders the cards into `books-container` and drives these hooks:
| `.media-card`, `.card-actions-trigger` and `.card-actions-menu` | Render a book card and its actions menu. |
| `.card-action-delete` | Deletes the book of the card. |
#### The Book Details and Editing Page
`library/written-content-library/book-library/books/item` renders the details and editing page of a book. Its fallback is `Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml`. Both bundled themes ship `templates/library/written-content-library/book-library/books/item.html`.
Page data:
| Field | Content |
| --- | --- |
| `bookId` | The Id of the book shown. |
| `libraryId` | The Id of the library the book belongs to. |
| `antiforgeryToken` | The anti-forgery request token for the save, delete and cover upload requests. |
| `saveUrl` | The route that saves the book. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book. |
| `deleteUrl` | The route that deletes the book. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book, and `libraryId` is appended as a query parameter. |
| `coverUrl` | The route that uploads the cover of the book. The trailing `00000000-0000-0000-0000-000000000000` is replaced by the Id of the book. |
| `backUrl` | The route of the books page of the library. |
| `bookJson` | The full details of the book, serialized as JSON. It carries the same fields as the book details response, including `metadata`, identifiers, ISBNs, `contributors`, `ratings` and `coverPath`. |
| `strings` | The localized strings of the page, keyed by their resource names. |
| `stringsJson` | The same localized strings serialized as JSON, with camel case keys, for the page script. |
The `contributors` of `bookJson` are references to the contributors table, each with the shape `{ contributorId, role }`, where `contributorId` is the Id of the contributor. A theme that needs a contributor's name resolves it from the contributors table using that Id.
#### The Deleted Items Page
`library/written-content-library/book-library/books/deleted-items` lists the books that were deleted from a book library and lets the user restore them. Its fallback is `Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/DeletedItems.cshtml`. The bundled themes ship their own `templates/library/written-content-library/book-library/books/deleted-items.html`; when a theme has no template for the page, the application renders the fallback view.
@@ -1,23 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.Enums.MediaContributors;
using System.Diagnostics;
#endregion
namespace Nemera.Presentation.Web.Common.DTO.MediaContributors;
/// <summary>
/// Data transfer object for a media contributor.
/// </summary>
[DebuggerDisplay("Name: {Name}")]
public class MediaContributorDto
{
/// <summary>
/// Gets the name of the contributor.
/// </summary>
public MediaContributorNameDto? Name { get; set; }
/// <summary>
/// Gets the canonical role of the contributor, used as the key of its localized display string.
/// </summary>
public MediaContributorRole? Role { get; set; }
}
@@ -1,22 +0,0 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Nemera.Presentation.Web.Common.DTO.MediaContributors;
/// <summary>
/// Data transfer object for a media contributor name.
/// </summary>
[DebuggerDisplay("DisplayName: {DisplayName}")]
public class MediaContributorNameDto
{
/// <summary>
/// Gets the name by which the contributor is popularly known.
/// </summary>
public string? DisplayName { get; set; }
/// <summary>
/// Gets the legal name of the contributor.
/// </summary>
public string? LegalName { get; set; }
}
@@ -102,9 +102,9 @@ public class BookDetailsDto
public List<IsbnDto>? ISBNs { get; set; }
/// <summary>
/// Gets or sets the list of media contributors of the book.
/// Gets or sets the list of references to the media contributors of the book, each with the role they played.
/// </summary>
public List<MediaContributorDto>? Contributors { get; set; }
public List<MediaContributorReferenceDto>? Contributors { get; set; }
/// <summary>
/// Gets or sets the list of ratings of the book.
@@ -29,4 +29,9 @@ public static class HttpContextItemKeys
/// The <c>Cache-Control</c> value chosen by the endpoint, restored when the response starts.
/// </summary>
public const string CACHE_CONTROL = "CacheControl";
/// <summary>
/// The key under which the flag indicating that the endpoint bound its request and started executing is stored.
/// </summary>
public const string ENDPOINT_STARTED = "EndpointStarted";
}
@@ -0,0 +1,8 @@
namespace Nemera.Presentation.Web.Common.Http;
/// <summary>
/// Marks an endpoint whose malformed JSON request bodies are answered with a client error ProblemDetails instead of the default JSON error envelope.
/// </summary>
public sealed class JsonBindingFailureClientErrorMetadata
{
}
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.Exceptions;
using Nemera.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
@@ -61,6 +63,11 @@ public class ExceptionHandlingMiddleware
{
await HandleApiExceptionAsync(context, apiException);
}
catch (JsonException jsonException) when (IsOptedInJsonBindingFailure(context, jsonException))
{
// The JSON request body failed to bind before the endpoint ran, so the caller sent a body that does not match the request contract.
await HandleJsonBindingExceptionAsync(context, jsonException);
}
catch (Exception ex) // Other cases.
{
if (_logger.IsEnabled(LogLevel.Error))
@@ -100,6 +107,63 @@ public class ExceptionHandlingMiddleware
}
}
/// <summary>
/// Determines whether a JSON exception is a request body binding failure of an endpoint that opted into client error responses.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
/// <param name="jsonException">The JSON exception thrown while processing the request.</param>
/// <returns><see langword="true"/> when the exception is a JSON body binding failure that should be reported as a client error.</returns>
private static bool IsOptedInJsonBindingFailure(HttpContext context, JsonException jsonException)
{
return jsonException is not FastEndpoints.JsonBindException
&& !context.Items.ContainsKey(HttpContextItemKeys.ENDPOINT_STARTED)
&& context.GetEndpoint()?.Metadata.GetMetadata<JsonBindingFailureClientErrorMetadata>() is not null;
}
/// <summary>
/// Handles a JSON request body that could not be deserialized into the request contract.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> for the current request.</param>
/// <param name="jsonException">The exception thrown while binding the request body.</param>
private async Task HandleJsonBindingExceptionAsync(HttpContext context, JsonException jsonException)
{
if (_logger.IsEnabled(LogLevel.Warning))
_logger.LogWarning(jsonException, "The JSON request body could not be deserialized: {Message}", jsonException.Message);
// Once the response has started, its status and headers are already on the wire, so they can no longer be replaced.
if (context.Response.HasStarted)
{
context.Abort();
return;
}
string errorMessage = _stringLocalizer["OneOrMoreValidationErrorsOccurred"].Value;
string? trimmedPath = jsonException.Path?.TrimStart('$', '.');
string fieldName = string.IsNullOrWhiteSpace(trimmedPath) ? "request" : trimmedPath;
if (IsJsonRequest(context))
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsJsonAsync(
new
{
type = "https://tools.ietf.org/html/rfc9110#section-15.5.1",
title = "General.Validation",
status = StatusCodes.Status400BadRequest,
detail = "OneOrMoreValidationErrorsOccurred",
instance = context.Request.Path.ToString(),
errors = new Dictionary<string, string[]> { [fieldName] = [errorMessage] },
errorMessage
},
options: null,
contentType: "application/problem+json",
cancellationToken: context.RequestAborted).ConfigureAwait(false);
}
else if (IsNavigationRequest(context))
await WriteHtmlErrorResponseAsync(context, StatusCodes.Status400BadRequest, errorMessage).ConfigureAwait(false);
else
await WriteStatusOnlyResponseAsync(context, StatusCodes.Status400BadRequest).ConfigureAwait(false);
}
/// <summary>
/// Handles exceptions specific to the API, including problem details.
/// </summary>
@@ -30,7 +30,7 @@ namespace Nemera.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.
/// <param name="BarnesAndNobleId">The Barnes &amp; Noble Id of the book. Optional.</param>
/// <param name="AppleBooksId">The Apple Books Id of the book. Optional.</param>
/// <param name="ISBNs">The list of ISBN (International Standard Book Number) of the book. Required.</param>
/// <param name="Contributors">The list of media contributors of the book. Required.</param>
/// <param name="Contributors">The list of references to the media contributors of the book, each with the role they played. Required.</param>
/// <param name="Ratings">The list of ratings of the book. Required.</param>
[DebuggerDisplay("Title: {Metadata?.Title}")]
public record UpdateBookRequest(
@@ -51,6 +51,6 @@ public record UpdateBookRequest(
string? BarnesAndNobleId,
string? AppleBooksId,
List<IsbnDto>? ISBNs,
List<MediaContributorDto>? Contributors,
List<MediaContributorReferenceDto>? Contributors,
List<BookRatingDto>? Ratings
);
@@ -3,6 +3,8 @@ using FastEndpoints;
using Nemera.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Nemera.Presentation.Web.Core.Endpoints.Common;
@@ -31,6 +33,25 @@ public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TRe
DontCatchExceptions();
}
/// <summary>
/// Marks the endpoint so that malformed JSON request bodies are answered with a client error ProblemDetails instead of the default JSON error envelope.
/// </summary>
protected void ReportJsonBindingFailuresAsClientErrors()
{
Metadata(new JsonBindingFailureClientErrorMetadata());
}
/// <summary>
/// Marks the request as past request binding, so that JSON binding failures can be told apart from JSON failures thrown while the endpoint runs.
/// </summary>
/// <param name="request">The request bound from the incoming request.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override Task OnBeforeHandleAsync(TRequest request, CancellationToken cancellationToken)
{
HttpContext.Items[HttpContextItemKeys.ENDPOINT_STARTED] = true;
return Task.CompletedTask;
}
/// <summary>
/// Sets the <c>Cache-Control</c> header, and remembers the chosen value so that it can be restored after later components overwrite it.
/// </summary>
@@ -41,6 +41,7 @@ public class SaveBookEndpoint : BaseEndpoint<UpdateBookRequest, IResult>
DontAutoTag();
Options(options => options.WithTags("Books"));
EnableAntiforgery();
ReportJsonBindingFailuresAsClientErrors();
}
/// <summary>
@@ -69,7 +69,7 @@ public class SaveBookEndpointSummary : Summary<SaveBookEndpoint, UpdateBookReque
RequestParam(r => r.BarnesAndNobleId, "The Barnes & Noble Id of the book. Optional.");
RequestParam(r => r.AppleBooksId, "The Apple Books Id of the book. Optional.");
RequestParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book. Required.");
RequestParam(r => r.Contributors, "The list of media contributors of the book. Required.");
RequestParam(r => r.Contributors, "The list of references to the media contributors of the book, each with the role they played. Required.");
RequestParam(r => r.Ratings, "The list of ratings of the book. Required.");
ExampleRequest = new UpdateBookRequest(
@@ -139,14 +139,14 @@ public class SaveBookEndpointSummary : Summary<SaveBookEndpoint, UpdateBookReque
],
Contributors:
[
new MediaContributorDto
new MediaContributorReferenceDto
{
Name = new MediaContributorNameDto { DisplayName = "J.R.R. Tolkien", LegalName = "John Ronald Reuel Tolkien" },
ContributorId = Guid.NewGuid(),
Role = MediaContributorRole.Author
},
new MediaContributorDto
new MediaContributorReferenceDto
{
Name = new MediaContributorNameDto { DisplayName = "Alan Lee", LegalName = "Alan Lee" },
ContributorId = Guid.NewGuid(),
Role = MediaContributorRole.Illustrator
}
],
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>تغيير الغلاف</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>الاسم</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>الأشخاص الذين ساهموا في الكتاب، مثل مؤلفيه.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Titelbild ändern</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Name</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Die Personen, die zum Buch beigetragen haben, wie seine Autoren.</value>
</data>
@@ -150,9 +150,6 @@
<data name="Contributors" xml:space="preserve">
<value>Contributors</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Name</value>
</data>
<data name="RoleName" xml:space="preserve">
<value>Role</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Cambiar portada</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Nombre</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Las personas que contribuyeron al libro, como sus autores.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Changer la couverture</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Nom</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Les personnes ayant contribué au livre, comme ses auteurs.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Cambia copertina</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Nome</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Le persone che hanno contribuito al libro, come i suoi autori.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>表紙を変更</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>名前</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>著者など、本に貢献した人々。</value>
</data>
@@ -150,9 +150,6 @@
<data name="Contributors" xml:space="preserve">
<value>Contributors</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Name</value>
</data>
<data name="RoleName" xml:space="preserve">
<value>Role</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Schimbă coperta</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Nume</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Persoanele care au contribuit la carte, precum autorii ei.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>Змінити обкладинку</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>Ім'я</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>Люди, які долучилися до створення книги, як-от її автори.</value>
</data>
@@ -51,9 +51,6 @@
<data name="ChangeCover" xml:space="preserve">
<value>更换封面</value>
</data>
<data name="ContributorName" xml:space="preserve">
<value>姓名</value>
</data>
<data name="ContributorsDescription" xml:space="preserve">
<value>为图书作出贡献的人,例如其作者。</value>
</data>
@@ -34,7 +34,7 @@
var genres = metadata?.Genres ?? [];
var tags = metadata?.Tags ?? [];
var isbns = Model.ISBNs ?? [];
var contributors = Model.Contributors ?? [];
var contributors = Model.Contributors ?? [];
var ratings = Model.Ratings ?? [];
// The full set of canonical media contributor roles, mirroring the MediaContributorRole enum members, offered by the role combobox.
var contributorRoles = new[]
@@ -42,7 +42,7 @@
"Other", "Author", "Translator", "Illustrator", "Publisher", "Narrator", "Actor", "Director", "Screenwriter",
"Composer", "Lyricist", "Arranger", "Conductor", "Producer", "ExecutiveProducer", "Engineer", "Mixer", "Remixer",
"RecordLabel", "Vocals", "BackingVocals", "Guitar", "BassGuitar", "Drums", "Percussion", "Keyboards", "Piano",
"Synthesizer", "Strings", "Woodwinds", "Brass", "Choir", "Orchestrator"
"Synthesizer", "Strings", "Woodwinds", "Brass", "Choir", "Orchestrator", "Performer"
};
// Resolves the localized label of a contributor role, keyed by its canonical value.
Func<string?, string> roleLabel = role => role switch
@@ -441,7 +441,7 @@
<table class="w-100 form-table book-list-table">
<thead>
<tr>
<th>@_localizer["ContributorName"]</th>
<th>@_localizer["ContributorId"]</th>
<th>@_localizer["Role"]</th>
<th class="w-40px"></th>
</tr>
@@ -451,7 +451,7 @@
@foreach (var contributor in contributors)
{
<tr class="contributor-row">
<td><input type="text" class="enlightenment-input contributor-name w-100" value="@(contributor.Name?.DisplayName ?? string.Empty)" /></td>
<td><input type="text" class="enlightenment-input contributor-id w-100" value="@(contributor.ContributorId.ToString())" /></td>
<td>
<div class="enlightenment-combobox inline-block w-100 contributor-role-combobox">
<div class="shine-effect" style="top: 1px;"></div>
@@ -637,7 +637,7 @@
Format: readRowComboboxValue(row, '.isbn-format-combobox') || null
})),
Contributors: Array.from(contributorsBody.querySelectorAll('.contributor-row')).map(row => ({
Name: { DisplayName: row.querySelector('.contributor-name').value.trim() || null },
ContributorId: row.querySelector('.contributor-id').value.trim() || '00000000-0000-0000-0000-000000000000',
Role: readRowComboboxValue(row, '.contributor-role-combobox') || null
})),
Ratings: Array.from(ratingsBody.querySelectorAll('.rating-row')).map(row => ({
@@ -787,15 +787,13 @@
await updateContentAsync(`${libraryIndexUrl}?libraryId=${encodeURIComponent(libraryId)}`, true);
}
// Builds the HTML of an enlightenment combobox of a row, with the provided option values.
function buildRowCombobox(optionValues, selectedValue) {
// Builds the HTML of an enlightenment combobox of a row, with the provided option values and an optional wrapper class.
function buildRowCombobox(optionValues, selectedValue, wrapperClass) {
const id = `row-combobox-${generatedId++}`;
const options = optionValues.map(option => {
const selected = option.value === selectedValue ? ' selected' : '';
return `<div class="enlightenment-option" data-value="${option.value}">${option.label}</div>`;
}).join('');
const options = optionValues.map(option =>
`<div class="enlightenment-option" data-value="${option.value}">${option.label}</div>`).join('');
return `
<div class="enlightenment-combobox inline-block w-100">
<div class="enlightenment-combobox inline-block w-100 ${wrapperClass || ''}">
<div class="shine-effect" style="top: 1px;"></div>
<input type="checkbox" class="enlightenment-toggle-checkbox" id="${id}" />
<label class="enlightenment-toggle" for="${id}">
@@ -845,7 +843,7 @@
isbnsBody.insertAdjacentHTML('beforeend', `
<tr class="isbn-row">
<td><input type="text" class="enlightenment-input isbn-value" /></td>
<td>${buildRowCombobox(isbnOptions, '')}</td>
<td>${buildRowCombobox(isbnOptions, '', 'isbn-format-combobox')}</td>
<td><img src="/images/ui/delete.svg" alt="${jsLocalizedStrings.remove}" title="${jsLocalizedStrings.remove}" class="remove-form-table-row-icon" /></td>
</tr>`);
}
@@ -854,8 +852,8 @@
function addContributorRow() {
contributorsBody.insertAdjacentHTML('beforeend', `
<tr class="contributor-row">
<td><input type="text" class="enlightenment-input contributor-name w-100" /></td>
<td>${buildRowCombobox(contributorRoleOptions, 'Author')}</td>
<td><input type="text" class="enlightenment-input contributor-id w-100" /></td>
<td>${buildRowCombobox(contributorRoleOptions, 'Author', 'contributor-role-combobox')}</td>
<td><img src="/images/ui/delete.svg" alt="${jsLocalizedStrings.remove}" title="${jsLocalizedStrings.remove}" class="remove-form-table-row-icon" /></td>
</tr>`);
}
@@ -866,7 +864,7 @@
<tr class="rating-row">
<td><input type="number" step="any" min="0" class="enlightenment-input rating-value" /></td>
<td><input type="number" step="any" min="0" class="enlightenment-input rating-max-value" /></td>
<td>${buildRowCombobox(ratingSourceOptions, '')}</td>
<td>${buildRowCombobox(ratingSourceOptions, '', 'rating-source-combobox')}</td>
<td><input type="number" min="0" class="enlightenment-input rating-vote-count" /></td>
<td><img src="/images/ui/delete.svg" alt="${jsLocalizedStrings.remove}" title="${jsLocalizedStrings.remove}" class="remove-form-table-row-icon" /></td>
</tr>`);
@@ -1,47 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.DTO.MediaContributors;
using Nemera.Presentation.Web.Common.Enums.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Nemera.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
/// <summary>
/// Fixture class for the <see cref="MediaContributorDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorDtoFixture
{
private readonly MediaContributorNameDtoFixture _mediaContributorNameDtoFixture = new();
/// <summary>
/// Creates a new <see cref="MediaContributorDto"/> instance with randomized test data.
/// </summary>
/// <param name="displayName">Optional. The name by which the contributor is popularly known.</param>
/// <param name="legalName">Optional. The legal name of the contributor.</param>
/// <param name="role">Optional. The canonical role of the contributor.</param>
/// <returns>A configured <see cref="MediaContributorDto"/> instance.</returns>
public MediaContributorDto Create(
string? displayName = null,
string? legalName = null,
MediaContributorRole? role = null)
{
return new MediaContributorDto
{
Name = _mediaContributorNameDtoFixture.Create(displayName, legalName),
Role = role ?? MediaContributorRole.Author
};
}
/// <summary>
/// Creates multiple <see cref="MediaContributorDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MediaContributorDto"/> instances.</returns>
public List<MediaContributorDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -1,45 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Nemera.Presentation.Web.Common.DTO.MediaContributors;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Nemera.Presentation.Web.Fixtures.Common.DTO.MediaContributors;
/// <summary>
/// Fixture class for the <see cref="MediaContributorNameDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaContributorNameDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MediaContributorNameDto"/> instance with randomized test data.
/// </summary>
/// <param name="displayName">Optional. The name by which the contributor is popularly known.</param>
/// <param name="legalName">Optional. The legal name of the contributor.</param>
/// <returns>A configured <see cref="MediaContributorNameDto"/> instance.</returns>
public MediaContributorNameDto Create(
string? displayName = null,
string? legalName = null)
{
return new MediaContributorNameDto
{
DisplayName = displayName ?? _faker.Name.FullName(),
LegalName = legalName ?? _faker.Name.FullName()
};
}
/// <summary>
/// Creates multiple <see cref="MediaContributorNameDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MediaContributorNameDto"/> instances.</returns>
public List<MediaContributorNameDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -23,7 +23,7 @@ public class BookDetailsDtoFixture
private readonly Faker _faker = new();
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
/// <summary>
@@ -61,7 +61,7 @@ public class BookDetailsDtoFixture
BarnesAndNobleId = _faker.Random.String2(10, "0123456789"),
AppleBooksId = $"id{_faker.Random.Number(1, 999999)}",
ISBNs = [.. _isbnDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
Contributors = [.. _mediaContributorDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
Contributors = [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
Ratings = [.. _bookRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))],
MetadataStatus = _faker.Random.String2(_faker.Random.Number(1, 20)),
LastMetadataUpdateUtc = _faker.Date.Recent(),
@@ -24,7 +24,7 @@ public class UpdateBookRequestFixture
private readonly WrittenContentMetadataDtoFixture _writtenContentMetadataDtoFixture = new();
private readonly BookSeriesDtoFixture _bookSeriesDtoFixture = new();
private readonly IsbnDtoFixture _isbnDtoFixture = new();
private readonly MediaContributorDtoFixture _mediaContributorDtoFixture = new();
private readonly MediaContributorReferenceDtoFixture _mediaContributorReferenceDtoFixture = new();
private readonly BookRatingDtoFixture _bookRatingDtoFixture = new();
/// <summary>
@@ -91,7 +91,7 @@ public class UpdateBookRequestFixture
BarnesAndNobleId: includeBarnesAndNobleId ? _faker.Random.String2(10, "0123456789") : null,
AppleBooksId: includeAppleBooksId ? $"id{_faker.Random.Number(1, 999999)}" : null,
ISBNs: includeIsbns ? [.. _isbnDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null,
Contributors: includeContributors ? [.. _mediaContributorDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null,
Contributors: includeContributors ? [.. _mediaContributorReferenceDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null,
Ratings: includeRatings ? [.. _bookRatingDtoFixture.CreateMany(_faker.Random.Number(1, 3))] : null
);
}
@@ -50,5 +50,8 @@ public class EditBookViewEndpointTests : IClassFixture<NemeraWebFactory>
Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType);
Assert.Contains("A book", content);
Assert.Contains("btn-delete-book", content);
Assert.Contains("contributor-id", content);
Assert.DoesNotContain("contributor-name", content);
Assert.Contains(expectedBook.Contributors![0].ContributorId.ToString(), content);
}
}
@@ -6,9 +6,11 @@ using Nemera.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibr
using Nemera.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Nemera.Presentation.Web.Fixtures.Common.TestHelpers;
using Nemera.Presentation.Web.IntegrationTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
@@ -124,6 +126,80 @@ public class SaveBookEndpointTests : IClassFixture<NemeraWebFactory>
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
}
[Fact]
public async Task SaveBook_WhenLibraryIdIsNotAGuid_ShouldReturnClientError()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
string payload = JsonSerializer.Serialize(request, JsonSerializerOptions.Web);
payload = payload.Replace(libraryId.ToString(), "not-a-guid");
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book")
{
Content = new StringContent(payload, Encoding.UTF8, "application/json")
};
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType!.MediaType);
using JsonDocument json = JsonDocument.Parse(content);
JsonElement problemDetails = json.RootElement;
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.GetProperty("type").GetString());
Assert.Equal("General.Validation", problemDetails.GetProperty("title").GetString());
Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.GetProperty("status").GetInt32());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("detail").GetString());
Assert.Equal($"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book", problemDetails.GetProperty("instance").GetString());
Assert.Equal("One or more validation errors occurred", problemDetails.GetProperty("errorMessage").GetString());
Assert.True(problemDetails.GetProperty("errors").TryGetProperty("libraryId", out JsonElement fieldErrors));
Assert.Equal("One or more validation errors occurred", fieldErrors[0].GetString());
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
}
[Fact]
public async Task SaveBook_WhenBodyIsMalformedJson_ShouldReturnClientError()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
const string PAYLOAD = "{\"contributors\": [";
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book")
{
Content = new StringContent(PAYLOAD, Encoding.UTF8, "application/json")
};
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType!.MediaType);
using JsonDocument json = JsonDocument.Parse(content);
JsonElement problemDetails = json.RootElement;
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.GetProperty("type").GetString());
Assert.Equal("General.Validation", problemDetails.GetProperty("title").GetString());
Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.GetProperty("status").GetInt32());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("detail").GetString());
Assert.Equal($"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book", problemDetails.GetProperty("instance").GetString());
Assert.Equal("One or more validation errors occurred", problemDetails.GetProperty("errorMessage").GetString());
Assert.NotEmpty(problemDetails.GetProperty("errors").EnumerateObject());
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
Assert.DoesNotContain(PAYLOAD, content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Builds the save request that PUTs the given <paramref name="request"/> to the book identified by <paramref name="bookId"/>.
/// </summary>
@@ -1,17 +1,21 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.DTO.Common;
using Nemera.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Nemera.Presentation.Web.Common.Exceptions;
using Nemera.Presentation.Web.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Nemera.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.SaveBook;
using Nemera.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibrary;
using Nemera.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Nemera.Presentation.Web.Fixtures.Common.TestHelpers;
using Nemera.Presentation.Web.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
@@ -97,6 +101,163 @@ public class SaveBookEndpointTests : IClassFixture<NemeraWebFactory>
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Metadata!.Title == maliciousTitle);
}
[Fact]
public async Task SaveBook_WhenLibraryIdIsNotAGuid_ShouldReturnClientErrorWithoutLeakingInternals()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
string maliciousLibraryId = "'; DROP TABLE Libraries--";
string payload = JsonSerializer.Serialize(request, JsonSerializerOptions.Web);
payload = payload.Replace(libraryId.ToString(), maliciousLibraryId);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateRawSaveRequest(bookId.ToString(), payload);
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType!.MediaType);
using JsonDocument json = JsonDocument.Parse(content);
JsonElement problemDetails = json.RootElement;
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.GetProperty("type").GetString());
Assert.Equal("General.Validation", problemDetails.GetProperty("title").GetString());
Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.GetProperty("status").GetInt32());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("detail").GetString());
Assert.Equal($"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book", problemDetails.GetProperty("instance").GetString());
Assert.Equal("One or more validation errors occurred", problemDetails.GetProperty("errorMessage").GetString());
Assert.True(problemDetails.GetProperty("errors").TryGetProperty("libraryId", out JsonElement fieldErrors));
Assert.Equal("One or more validation errors occurred", fieldErrors[0].GetString());
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Nemera", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
}
[Fact]
public async Task SaveBook_WhenBodyIsMalformedJson_ShouldReturnClientErrorWithoutLeakingInternals()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
const string PAYLOAD = "{\"contributors\": [";
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateRawSaveRequest(bookId.ToString(), PAYLOAD);
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal("application/problem+json", response.Content.Headers.ContentType!.MediaType);
using JsonDocument json = JsonDocument.Parse(content);
JsonElement problemDetails = json.RootElement;
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.GetProperty("type").GetString());
Assert.Equal("General.Validation", problemDetails.GetProperty("title").GetString());
Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.GetProperty("status").GetInt32());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("detail").GetString());
Assert.Equal($"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book", problemDetails.GetProperty("instance").GetString());
Assert.Equal("One or more validation errors occurred", problemDetails.GetProperty("errorMessage").GetString());
Assert.NotEmpty(problemDetails.GetProperty("errors").EnumerateObject());
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
Assert.DoesNotContain(PAYLOAD, content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Nemera", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task SaveBook_WhenContributorIdIsEmpty_ShouldForwardItAndReturnASanitizedApiError()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
string endpoint = $"libraries/{libraryId}/books/{bookId}";
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
request.Contributors![0].ContributorId = Guid.Empty;
_apiFactory.ApiClientStub.RegisterPutException(endpoint, new ApiException(
new ProblemDetailsDto
{
Type = "https://tools.ietf.org/html/rfc4918#section-11.2",
Title = "General.Validation",
Status = 422,
Detail = "MediaContributorIdCannotBeEmpty"
},
(HttpStatusCode)422,
endpoint));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(bookId.ToString(), request);
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains("media contributor", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.OrdinalIgnoreCase);
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest =>
putRequest.Endpoint == endpoint &&
putRequest.Data is UpdateBookRequest forwardedRequest &&
forwardedRequest.Contributors![0].ContributorId == Guid.Empty);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Nemera", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task SaveBook_WhenContributorDoesNotExist_ShouldForwardItAndReturnASanitizedApiError()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
Guid libraryId = Guid.NewGuid();
Guid unknownContributorId = Guid.NewGuid();
string endpoint = $"libraries/{libraryId}/books/{bookId}";
UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
request.Contributors![0].ContributorId = unknownContributorId;
_apiFactory.ApiClientStub.RegisterPutException(endpoint, new ApiException(
new ProblemDetailsDto
{
Type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
Title = "General.NotFound",
Status = 404,
Detail = "MediaContributorNotFound"
},
HttpStatusCode.NotFound,
endpoint));
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage saveRequest = CreateSaveRequest(bookId.ToString(), request);
saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest =>
putRequest.Endpoint == endpoint &&
putRequest.Data is UpdateBookRequest forwardedRequest &&
forwardedRequest.Contributors![0].ContributorId == unknownContributorId);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Nemera", content, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task SaveBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
@@ -129,4 +290,20 @@ public class SaveBookEndpointTests : IClassFixture<NemeraWebFactory>
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return saveRequest;
}
/// <summary>
/// Builds a save request that sends the given raw JSON body to the book identified by <paramref name="bookId"/>.
/// </summary>
/// <param name="bookId">The route Id of the book to save.</param>
/// <param name="jsonBody">The raw JSON body to send.</param>
/// <returns>The configured save request.</returns>
private static HttpRequestMessage CreateRawSaveRequest(string bookId, string jsonBody)
{
HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-save-book")
{
Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
};
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return saveRequest;
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.DTO.WrittenContentLibrary.BookLibrary;
using Nemera.Presentation.Web.Common.Enums.MediaContributors;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;
#endregion
namespace Nemera.Presentation.Web.UnitTests.Common.DTO.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Contains unit tests for the <see cref="BookDetailsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookDetailsDtoTests
{
private static readonly JsonSerializerOptions s_jsonOptions = new()
{
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
};
[Fact]
public void Deserialize_WhenBookResponseHasContributorReferences_ShouldBindContributorIdAndRole()
{
// Arrange
Guid firstContributorId = Guid.NewGuid();
Guid secondContributorId = Guid.NewGuid();
string json = $$"""
{
"id": "{{Guid.NewGuid()}}",
"libraryId": "{{Guid.NewGuid()}}",
"path": "C:\\books\\book.epub",
"contributors": [
{ "contributorId": "{{firstContributorId}}", "role": "Author" },
{ "contributorId": "{{secondContributorId}}", "role": "Illustrator" }
]
}
""";
// Act
BookDetailsDto? result = JsonSerializer.Deserialize<BookDetailsDto>(json, s_jsonOptions);
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Contributors);
Assert.Equal(2, result.Contributors.Count);
Assert.Equal(firstContributorId, result.Contributors[0].ContributorId);
Assert.Equal(MediaContributorRole.Author, result.Contributors[0].Role);
Assert.Equal(secondContributorId, result.Contributors[1].ContributorId);
Assert.Equal(MediaContributorRole.Illustrator, result.Contributors[1].Role);
}
}
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.DTO.Common;
using Nemera.Presentation.Web.Common.Exceptions;
using Nemera.Presentation.Web.Common.Http;
using Nemera.Presentation.Web.Common.Middlewares;
using Nemera.Presentation.Web.Fixtures.Common.DTO.Common;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
@@ -17,6 +19,7 @@ using System.Net;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -172,6 +175,170 @@ public class ExceptionHandlingMiddlewareTests
Assert.Equal(0, httpContext.Response.Body.Length);
}
[Fact]
public async Task InvokeAsync_WhenRequestBindingThrowsJsonExceptionAndApiRequest_ShouldWriteBadRequestProblemDetails()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
httpContext.Request.Path = "/books/1";
ConfigureJsonBindingFailureEndpoint(httpContext);
_nextDelegate = _ => throw new JsonException("The JSON value could not be converted to System.Guid.", "$.contributors[0].contributorId", 0, 10);
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode);
Assert.Equal("application/problem+json", httpContext.Response.ContentType);
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
JsonElement problemDetails = jsonDocument.RootElement;
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.GetProperty("type").GetString());
Assert.Equal("General.Validation", problemDetails.GetProperty("title").GetString());
Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.GetProperty("status").GetInt32());
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("detail").GetString());
Assert.Equal("/books/1", problemDetails.GetProperty("instance").GetString());
Assert.Equal("localized:OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("errorMessage").GetString());
Assert.True(problemDetails.GetProperty("errors").TryGetProperty("contributors[0].contributorId", out JsonElement fieldErrors));
Assert.Equal("localized:OneOrMoreValidationErrorsOccurred", fieldErrors[0].GetString());
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
[InlineData("$")]
public async Task InvokeAsync_WhenJsonExceptionHasNoFieldPath_ShouldReportTheRequestAsTheErrorField(string? path)
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
ConfigureJsonBindingFailureEndpoint(httpContext);
_nextDelegate = _ => throw new JsonException("The JSON body is malformed.", path, 0, 10);
// Act
await _sut.InvokeAsync(httpContext);
// Assert
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.True(jsonDocument.RootElement.GetProperty("errors").TryGetProperty("request", out JsonElement fieldErrors));
Assert.Equal("localized:OneOrMoreValidationErrorsOccurred", fieldErrors[0].GetString());
}
[Fact]
public async Task InvokeAsync_WhenJsonBindExceptionOccursOnAnOptedInEndpoint_ShouldKeepTheJsonErrorEnvelope()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
ConfigureJsonBindingFailureEndpoint(httpContext);
_nextDelegate = _ => throw new FastEndpoints.JsonBindException(
"value",
"Value is not valid.",
new JsonException("The JSON value could not be converted.", "$.value", 0, 10));
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status200OK, httpContext.Response.StatusCode);
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
}
[Fact]
public async Task InvokeAsync_WhenJsonBindingExceptionOccursAfterResponseStarted_ShouldAbortWithoutWritingProblemDetails()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
ConfigureJsonBindingFailureEndpoint(httpContext);
RecordingRequestLifetimeFeature lifetimeFeature = new();
httpContext.Features.Set<IHttpRequestLifetimeFeature>(lifetimeFeature);
httpContext.Features.Set<IHttpResponseFeature>(new StartedHttpResponseFeature());
_nextDelegate = _ => throw new JsonException("The JSON body is malformed.", "$.contributors", 0, 10);
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.True(httpContext.Response.HasStarted);
Assert.True(lifetimeFeature.WasAborted);
Assert.Equal(0, httpContext.Response.Body.Length);
}
[Fact]
public async Task InvokeAsync_WhenRequestBindingThrowsJsonExceptionAndRawRequest_ShouldWriteBadRequestWithoutBody()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
httpContext.Request.Headers.Accept = "audio/mpeg";
ConfigureJsonBindingFailureEndpoint(httpContext);
_nextDelegate = _ => throw new JsonException("The JSON body is malformed.", "$.id", 0, 10);
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode);
Assert.Equal(0, httpContext.Response.Body.Length);
}
[Fact]
public async Task InvokeAsync_WhenRequestBindingThrowsJsonExceptionAndPageRequest_ShouldWriteBadRequestHtmlPage()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext();
httpContext.Request.Headers.Accept = "text/html";
ConfigureJsonBindingFailureEndpoint(httpContext);
_nextDelegate = _ => throw new JsonException("The JSON value could not be converted to System.Guid.", "$.contributors[0].contributorId", 0, 10);
// Act
await _sut.InvokeAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode);
Assert.Contains("text/html", httpContext.Response.ContentType);
Assert.Contains("localized:OneOrMoreValidationErrorsOccurred", await ReadResponseBodyAsync(httpContext));
}
[Fact]
public async Task InvokeAsync_WhenJsonExceptionOccursAfterEndpointStarted_ShouldTreatItAsAnUnexpectedError()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
ConfigureJsonBindingFailureEndpoint(httpContext);
httpContext.Items[HttpContextItemKeys.ENDPOINT_STARTED] = true;
_nextDelegate = _ => throw new JsonException("Malformed API response.", "$.id", 0, 10);
// Act
await _sut.InvokeAsync(httpContext);
// Assert
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
}
[Fact]
public async Task InvokeAsync_WhenJsonExceptionOccursOnAnEndpointThatDidNotOptIn_ShouldKeepTheJsonErrorEnvelope()
{
// Arrange
DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
httpContext.SetEndpoint(new Endpoint(requestDelegate: null, new EndpointMetadataCollection(), displayName: "TestEndpoint"));
_nextDelegate = _ => throw new JsonException("The JSON value could not be converted to System.Guid.", "$.contributors[0].contributorId", 0, 10);
// Act
await _sut.InvokeAsync(httpContext);
// Assert
string body = await ReadResponseBodyAsync(httpContext);
using JsonDocument jsonDocument = JsonDocument.Parse(body);
Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
}
[Fact]
public async Task InvokeAsync_WhenApiExceptionUnauthorizedAndApiRequest_ShouldSignOutAndWriteUnauthorizedJson()
{
@@ -464,6 +631,18 @@ public class ExceptionHandlingMiddlewareTests
return httpContext;
}
/// <summary>
/// Marks the endpoint of the provided HTTP context as one that reports JSON binding failures as client errors.
/// </summary>
/// <param name="httpContext">The HTTP context whose endpoint is marked.</param>
private static void ConfigureJsonBindingFailureEndpoint(DefaultHttpContext httpContext)
{
httpContext.SetEndpoint(new Endpoint(
requestDelegate: null,
new EndpointMetadataCollection(new JsonBindingFailureClientErrorMetadata()),
displayName: "TestEndpoint"));
}
/// <summary>
/// Creates a service provider that resolves the mocked <see cref="IAuthenticationService"/>.
/// </summary>
@@ -527,4 +706,79 @@ public class ExceptionHandlingMiddlewareTests
""";
return JsonSerializer.Deserialize<ProblemDetailsDto>(problemDetailsJson)!;
}
/// <summary>
/// Response feature that reports the response as already started, so tests can exercise the abort branch of the middleware.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class StartedHttpResponseFeature : IHttpResponseFeature
{
/// <summary>
/// Gets or sets the status code of the response.
/// </summary>
public int StatusCode { get; set; } = StatusCodes.Status200OK;
/// <summary>
/// Gets or sets the reason phrase of the response.
/// </summary>
public string? ReasonPhrase { get; set; }
/// <summary>
/// Gets or sets the response headers.
/// </summary>
public IHeaderDictionary Headers { get; set; } = new HeaderDictionary();
/// <summary>
/// Gets or sets the response body.
/// </summary>
public Stream Body { get; set; } = new MemoryStream();
/// <summary>
/// Gets a value indicating whether the response has started.
/// </summary>
public bool HasStarted => true;
/// <summary>
/// Registers a callback invoked before the response starts.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <param name="state">The state passed to the callback.</param>
public void OnStarting(Func<object, Task> callback, object state)
{
}
/// <summary>
/// Registers a callback invoked when the response completes.
/// </summary>
/// <param name="callback">The callback to invoke.</param>
/// <param name="state">The state passed to the callback.</param>
public void OnCompleted(Func<object, Task> callback, object state)
{
}
}
/// <summary>
/// Records whether the lifetime of a test request was aborted, so tests can assert the abort branch of the middleware.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class RecordingRequestLifetimeFeature : IHttpRequestLifetimeFeature
{
/// <summary>
/// Gets or sets the token that is signaled when the request is aborted.
/// </summary>
public CancellationToken RequestAborted { get; set; }
/// <summary>
/// Gets a value indicating whether the request was aborted.
/// </summary>
public bool WasAborted { get; private set; }
/// <summary>
/// Marks the request as aborted.
/// </summary>
public void Abort()
{
WasAborted = true;
}
}
}
@@ -62,6 +62,31 @@ public class SaveBookEndpointTests
Assert.Equal(originalBookId, request.BookId);
}
[Fact]
public async Task ExecuteAsync_WhenContributorsAreProvided_ShouldForwardContributorReferencesToApi()
{
// Arrange
string routeId = Guid.NewGuid().ToString();
UpdateBookRequest request = _updateBookRequestFixture.Create();
BookDetailsDto expectedBook = _bookDetailsDtoFixture.Create();
_mockApiHttpClient.PutAsync<BookDetailsDto, UpdateBookRequest>(Arg.Any<string>(), Arg.Any<UpdateBookRequest>(), Arg.Any<CancellationToken>())
.Returns(expectedBook);
ConfigureRequest(routeId);
// Act
await _sut.ExecuteAsync(request, CancellationToken.None);
// Assert
await _mockApiHttpClient.Received(1).PutAsync<BookDetailsDto, UpdateBookRequest>(
Arg.Any<string>(),
Arg.Is<UpdateBookRequest>(forwardedRequest =>
forwardedRequest.Contributors != null &&
forwardedRequest.Contributors.Count == request.Contributors!.Count &&
forwardedRequest.Contributors[0].ContributorId == request.Contributors[0].ContributorId &&
forwardedRequest.Contributors[0].Role == request.Contributors[0].Role),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldForwardTheRouteIdToApi()
{