diff --git a/docs/technical/theming/Theming.md b/docs/technical/theming/Theming.md index 8955e9f3..521d26bd 100644 --- a/docs/technical/theming/Theming.md +++ b/docs/technical/theming/Theming.md @@ -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. diff --git a/src/Nemera.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip b/src/Nemera.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip index a4dca3c6..80621fc5 100644 Binary files a/src/Nemera.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip and b/src/Nemera.Presentation.Api/Core/Themes/Bundled/editorial-paper.zip differ diff --git a/src/Nemera.Presentation.Api/Core/Themes/Bundled/nemera-default.zip b/src/Nemera.Presentation.Api/Core/Themes/Bundled/nemera-default.zip index 92edc598..e8105d15 100644 Binary files a/src/Nemera.Presentation.Api/Core/Themes/Bundled/nemera-default.zip and b/src/Nemera.Presentation.Api/Core/Themes/Bundled/nemera-default.zip differ diff --git a/src/Nemera.Presentation.Web/Common/DTO/MediaContributors/MediaContributorDto.cs b/src/Nemera.Presentation.Web/Common/DTO/MediaContributors/MediaContributorDto.cs deleted file mode 100644 index bc6a4507..00000000 --- a/src/Nemera.Presentation.Web/Common/DTO/MediaContributors/MediaContributorDto.cs +++ /dev/null @@ -1,23 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using Nemera.Presentation.Web.Common.Enums.MediaContributors; -using System.Diagnostics; -#endregion - -namespace Nemera.Presentation.Web.Common.DTO.MediaContributors; - -/// -/// Data transfer object for a media contributor. -/// -[DebuggerDisplay("Name: {Name}")] -public class MediaContributorDto -{ - /// - /// Gets the name of the contributor. - /// - public MediaContributorNameDto? Name { get; set; } - - /// - /// Gets the canonical role of the contributor, used as the key of its localized display string. - /// - public MediaContributorRole? Role { get; set; } -} diff --git a/src/Nemera.Presentation.Web/Common/DTO/MediaContributors/MediaContributorNameDto.cs b/src/Nemera.Presentation.Web/Common/DTO/MediaContributors/MediaContributorNameDto.cs deleted file mode 100644 index 3eae83f3..00000000 --- a/src/Nemera.Presentation.Web/Common/DTO/MediaContributors/MediaContributorNameDto.cs +++ /dev/null @@ -1,22 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using System.Diagnostics; -#endregion - -namespace Nemera.Presentation.Web.Common.DTO.MediaContributors; - -/// -/// Data transfer object for a media contributor name. -/// -[DebuggerDisplay("DisplayName: {DisplayName}")] -public class MediaContributorNameDto -{ - /// - /// Gets the name by which the contributor is popularly known. - /// - public string? DisplayName { get; set; } - - /// - /// Gets the legal name of the contributor. - /// - public string? LegalName { get; set; } -} diff --git a/src/Nemera.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDto.cs b/src/Nemera.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDto.cs index 610daf1c..5be632ac 100644 --- a/src/Nemera.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDto.cs +++ b/src/Nemera.Presentation.Web/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDto.cs @@ -102,9 +102,9 @@ public class BookDetailsDto public List? ISBNs { get; set; } /// - /// 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. /// - public List? Contributors { get; set; } + public List? Contributors { get; set; } /// /// Gets or sets the list of ratings of the book. diff --git a/src/Nemera.Presentation.Web/Common/Http/HttpContextItemKeys.cs b/src/Nemera.Presentation.Web/Common/Http/HttpContextItemKeys.cs index b794f3b0..5f3af176 100644 --- a/src/Nemera.Presentation.Web/Common/Http/HttpContextItemKeys.cs +++ b/src/Nemera.Presentation.Web/Common/Http/HttpContextItemKeys.cs @@ -29,4 +29,9 @@ public static class HttpContextItemKeys /// The Cache-Control value chosen by the endpoint, restored when the response starts. /// public const string CACHE_CONTROL = "CacheControl"; + + /// + /// The key under which the flag indicating that the endpoint bound its request and started executing is stored. + /// + public const string ENDPOINT_STARTED = "EndpointStarted"; } diff --git a/src/Nemera.Presentation.Web/Common/Http/JsonBindingFailureClientErrorMetadata.cs b/src/Nemera.Presentation.Web/Common/Http/JsonBindingFailureClientErrorMetadata.cs new file mode 100644 index 00000000..6762b105 --- /dev/null +++ b/src/Nemera.Presentation.Web/Common/Http/JsonBindingFailureClientErrorMetadata.cs @@ -0,0 +1,8 @@ +namespace Nemera.Presentation.Web.Common.Http; + +/// +/// Marks an endpoint whose malformed JSON request bodies are answered with a client error ProblemDetails instead of the default JSON error envelope. +/// +public sealed class JsonBindingFailureClientErrorMetadata +{ +} diff --git a/src/Nemera.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Nemera.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs index e3929f49..77b85bbc 100644 --- a/src/Nemera.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs +++ b/src/Nemera.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs @@ -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 } } + /// + /// Determines whether a JSON exception is a request body binding failure of an endpoint that opted into client error responses. + /// + /// The for the current request. + /// The JSON exception thrown while processing the request. + /// when the exception is a JSON body binding failure that should be reported as a client error. + private static bool IsOptedInJsonBindingFailure(HttpContext context, JsonException jsonException) + { + return jsonException is not FastEndpoints.JsonBindException + && !context.Items.ContainsKey(HttpContextItemKeys.ENDPOINT_STARTED) + && context.GetEndpoint()?.Metadata.GetMetadata() is not null; + } + + /// + /// Handles a JSON request body that could not be deserialized into the request contract. + /// + /// The for the current request. + /// The exception thrown while binding the request body. + 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 { [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); + } + /// /// Handles exceptions specific to the API, including problem details. /// diff --git a/src/Nemera.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs b/src/Nemera.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs index 873fc017..e2de40b0 100644 --- a/src/Nemera.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs +++ b/src/Nemera.Presentation.Web/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequest.cs @@ -30,7 +30,7 @@ namespace Nemera.Presentation.Web.Common.Requests.Library.WrittenContentLibrary. /// The Barnes & Noble Id of the book. Optional. /// The Apple Books Id of the book. Optional. /// The list of ISBN (International Standard Book Number) of the book. Required. -/// The list of media contributors of the book. Required. +/// The list of references to the media contributors of the book, each with the role they played. Required. /// The list of ratings of the book. Required. [DebuggerDisplay("Title: {Metadata?.Title}")] public record UpdateBookRequest( @@ -51,6 +51,6 @@ public record UpdateBookRequest( string? BarnesAndNobleId, string? AppleBooksId, List? ISBNs, - List? Contributors, + List? Contributors, List? Ratings ); diff --git a/src/Nemera.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs b/src/Nemera.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs index 413638a5..8947363a 100644 --- a/src/Nemera.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs +++ b/src/Nemera.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs @@ -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 : Endpoint + /// Marks the endpoint so that malformed JSON request bodies are answered with a client error ProblemDetails instead of the default JSON error envelope. + /// + protected void ReportJsonBindingFailuresAsClientErrors() + { + Metadata(new JsonBindingFailureClientErrorMetadata()); + } + + /// + /// Marks the request as past request binding, so that JSON binding failures can be told apart from JSON failures thrown while the endpoint runs. + /// + /// The request bound from the incoming request. + /// Cancellation token that can be used to stop the execution. + public override Task OnBeforeHandleAsync(TRequest request, CancellationToken cancellationToken) + { + HttpContext.Items[HttpContextItemKeys.ENDPOINT_STARTED] = true; + return Task.CompletedTask; + } + /// /// Sets the Cache-Control header, and remembers the chosen value so that it can be restored after later components overwrite it. /// diff --git a/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs b/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs index 25c79ed0..05fa33c4 100644 --- a/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs +++ b/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs @@ -41,6 +41,7 @@ public class SaveBookEndpoint : BaseEndpoint DontAutoTag(); Options(options => options.WithTags("Books")); EnableAntiforgery(); + ReportJsonBindingFailuresAsClientErrors(); } /// diff --git a/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs b/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs index 8347dd54..1ba53d0f 100644 --- a/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs +++ b/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointSummary.cs @@ -69,7 +69,7 @@ public class SaveBookEndpointSummary : Summary 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 تغيير الغلاف - - الاسم - الأشخاص الذين ساهموا في الكتاب، مثل مؤلفيه. diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx index 9d77b677..5a6d356f 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.de-DE.resx @@ -51,9 +51,6 @@ Titelbild ändern - - Name - Die Personen, die zum Buch beigetragen haben, wie seine Autoren. diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx index 5dcdd2e5..8fb933eb 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.en-US.resx @@ -150,9 +150,6 @@ Contributors - - Name - Role diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx index 38c6d124..d1ac1572 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.es-ES.resx @@ -51,9 +51,6 @@ Cambiar portada - - Nombre - Las personas que contribuyeron al libro, como sus autores. diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx index c736b831..02ef6d95 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.fr-FR.resx @@ -51,9 +51,6 @@ Changer la couverture - - Nom - Les personnes ayant contribué au livre, comme ses auteurs. diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx index da54e758..cabf50e4 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.it-IT.resx @@ -51,9 +51,6 @@ Cambia copertina - - Nome - Le persone che hanno contribuito al libro, come i suoi autori. diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx index 392a94a4..9a8a5f2d 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ja-JP.resx @@ -51,9 +51,6 @@ 表紙を変更 - - 名前 - 著者など、本に貢献した人々。 diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx index cd50688c..c753047a 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.resx @@ -150,9 +150,6 @@ Contributors - - Name - Role diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx index d4ad4a1e..eea515ca 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.ro-RO.resx @@ -51,9 +51,6 @@ Schimbă coperta - - Nume - Persoanele care au contribuit la carte, precum autorii ei. diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx index ac11ec59..677de677 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.uk-UA.resx @@ -51,9 +51,6 @@ Змінити обкладинку - - Ім'я - Люди, які долучилися до створення книги, як-от її автори. diff --git a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx index 720a9569..a478c6ea 100644 --- a/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx +++ b/src/Nemera.Presentation.Web/Core/Resources/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.zh-CN.resx @@ -51,9 +51,6 @@ 更换封面 - - 姓名 - 为图书作出贡献的人,例如其作者。 diff --git a/src/Nemera.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml b/src/Nemera.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml index 86242c5e..4a22935b 100644 --- a/src/Nemera.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml +++ b/src/Nemera.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Item.cshtml @@ -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 roleLabel = role => role switch @@ -441,7 +441,7 @@ - + @@ -451,7 +451,7 @@ @foreach (var contributor in contributors) { - + - + `); } @@ -854,8 +852,8 @@ function addContributorRow() { contributorsBody.insertAdjacentHTML('beforeend', ` - - + + `); } @@ -866,7 +864,7 @@ - + `); diff --git a/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorDtoFixture.cs b/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorDtoFixture.cs deleted file mode 100644 index 0cdb12a3..00000000 --- a/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorDtoFixture.cs +++ /dev/null @@ -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; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class MediaContributorDtoFixture -{ - private readonly MediaContributorNameDtoFixture _mediaContributorNameDtoFixture = new(); - - /// - /// Creates a new instance with randomized test data. - /// - /// Optional. The name by which the contributor is popularly known. - /// Optional. The legal name of the contributor. - /// Optional. The canonical role of the contributor. - /// A configured instance. - public MediaContributorDto Create( - string? displayName = null, - string? legalName = null, - MediaContributorRole? role = null) - { - return new MediaContributorDto - { - Name = _mediaContributorNameDtoFixture.Create(displayName, legalName), - Role = role ?? MediaContributorRole.Author - }; - } - - /// - /// Creates multiple instances with randomized test data. - /// - /// Number of instances to create. - /// List of configured instances. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorNameDtoFixture.cs b/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorNameDtoFixture.cs deleted file mode 100644 index e4e31195..00000000 --- a/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/MediaContributors/MediaContributorNameDtoFixture.cs +++ /dev/null @@ -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; - -/// -/// Fixture class for the class. -/// -[ExcludeFromCodeCoverage] -public class MediaContributorNameDtoFixture -{ - private readonly Faker _faker = new(); - - /// - /// Creates a new instance with randomized test data. - /// - /// Optional. The name by which the contributor is popularly known. - /// Optional. The legal name of the contributor. - /// A configured instance. - public MediaContributorNameDto Create( - string? displayName = null, - string? legalName = null) - { - return new MediaContributorNameDto - { - DisplayName = displayName ?? _faker.Name.FullName(), - LegalName = legalName ?? _faker.Name.FullName() - }; - } - - /// - /// Creates multiple instances with randomized test data. - /// - /// Number of instances to create. - /// List of configured instances. - public List CreateMany(int count = 3) - { - return [.. Enumerable.Range(0, count).Select(_ => Create())]; - } -} diff --git a/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs b/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs index 65cb6bd5..ddb50b5c 100644 --- a/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs +++ b/tests/Common/Nemera.Presentation.Web.Fixtures/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoFixture.cs @@ -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(); /// @@ -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(), diff --git a/tests/Common/Nemera.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs b/tests/Common/Nemera.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs index 9af5f793..e37b59e6 100644 --- a/tests/Common/Nemera.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs +++ b/tests/Common/Nemera.Presentation.Web.Fixtures/Common/Requests/Library/WrittenContentLibrary/BookLibrary/Books/UpdateBookRequestFixture.cs @@ -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(); /// @@ -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 ); } diff --git a/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs b/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs index 33a82518..cba3e89b 100644 --- a/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs +++ b/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/EditBook/EditBookViewEndpointTests.cs @@ -50,5 +50,8 @@ public class EditBookViewEndpointTests : IClassFixture 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); } } diff --git a/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs index 476475fa..e61dd826 100644 --- a/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs +++ b/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -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 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); + } + /// /// Builds the save request that PUTs the given to the book identified by . /// diff --git a/tests/SecurityTests/Nemera.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/SecurityTests/Nemera.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs index 90a818e2..87bd9f15 100644 --- a/tests/SecurityTests/Nemera.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs +++ b/tests/SecurityTests/Nemera.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -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 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 saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return saveRequest; } + + /// + /// Builds a save request that sends the given raw JSON body to the book identified by . + /// + /// The route Id of the book to save. + /// The raw JSON body to send. + /// The configured save request. + 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; + } } diff --git a/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoTests.cs b/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoTests.cs new file mode 100644 index 00000000..3c56ee6a --- /dev/null +++ b/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/DTO/WrittenContentLibrary/BookLibrary/BookDetailsDtoTests.cs @@ -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; + +/// +/// Contains unit tests for the class. +/// +[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(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); + } +} diff --git a/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs index d777786f..ee583f6c 100644 --- a/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs +++ b/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs @@ -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(lifetimeFeature); + httpContext.Features.Set(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; } + /// + /// Marks the endpoint of the provided HTTP context as one that reports JSON binding failures as client errors. + /// + /// The HTTP context whose endpoint is marked. + private static void ConfigureJsonBindingFailureEndpoint(DefaultHttpContext httpContext) + { + httpContext.SetEndpoint(new Endpoint( + requestDelegate: null, + new EndpointMetadataCollection(new JsonBindingFailureClientErrorMetadata()), + displayName: "TestEndpoint")); + } + /// /// Creates a service provider that resolves the mocked . /// @@ -527,4 +706,79 @@ public class ExceptionHandlingMiddlewareTests """; return JsonSerializer.Deserialize(problemDetailsJson)!; } + + /// + /// Response feature that reports the response as already started, so tests can exercise the abort branch of the middleware. + /// + [ExcludeFromCodeCoverage] + private sealed class StartedHttpResponseFeature : IHttpResponseFeature + { + /// + /// Gets or sets the status code of the response. + /// + public int StatusCode { get; set; } = StatusCodes.Status200OK; + + /// + /// Gets or sets the reason phrase of the response. + /// + public string? ReasonPhrase { get; set; } + + /// + /// Gets or sets the response headers. + /// + public IHeaderDictionary Headers { get; set; } = new HeaderDictionary(); + + /// + /// Gets or sets the response body. + /// + public Stream Body { get; set; } = new MemoryStream(); + + /// + /// Gets a value indicating whether the response has started. + /// + public bool HasStarted => true; + + /// + /// Registers a callback invoked before the response starts. + /// + /// The callback to invoke. + /// The state passed to the callback. + public void OnStarting(Func callback, object state) + { + } + + /// + /// Registers a callback invoked when the response completes. + /// + /// The callback to invoke. + /// The state passed to the callback. + public void OnCompleted(Func callback, object state) + { + } + } + + /// + /// Records whether the lifetime of a test request was aborted, so tests can assert the abort branch of the middleware. + /// + [ExcludeFromCodeCoverage] + private sealed class RecordingRequestLifetimeFeature : IHttpRequestLifetimeFeature + { + /// + /// Gets or sets the token that is signaled when the request is aborted. + /// + public CancellationToken RequestAborted { get; set; } + + /// + /// Gets a value indicating whether the request was aborted. + /// + public bool WasAborted { get; private set; } + + /// + /// Marks the request as aborted. + /// + public void Abort() + { + WasAborted = true; + } + } } diff --git a/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs index 3bbab2b8..348eab59 100644 --- a/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs +++ b/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs @@ -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(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedBook); + ConfigureRequest(routeId); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Any(), + Arg.Is(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()); + } + [Fact] public async Task ExecuteAsync_WhenRouteIdDiffersFromBodyId_ShouldForwardTheRouteIdToApi() {
@_localizer["ContributorName"]@_localizer["ContributorId"] @_localizer["Role"]
@@ -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 `
${option.label}
`; - }).join(''); + const options = optionValues.map(option => + `
${option.label}
`).join(''); return ` -
+
${buildRowCombobox(isbnOptions, '')}${buildRowCombobox(isbnOptions, '', 'isbn-format-combobox')} ${jsLocalizedStrings.remove}
${buildRowCombobox(contributorRoleOptions, 'Author')}${buildRowCombobox(contributorRoleOptions, 'Author', 'contributor-role-combobox')} ${jsLocalizedStrings.remove}
${buildRowCombobox(ratingSourceOptions, '')}${buildRowCombobox(ratingSourceOptions, '', 'rating-source-combobox')} ${jsLocalizedStrings.remove}