diff --git a/docs/technical/api/library/written-content-library/book-library/Api.Books.md b/docs/technical/api/library/written-content-library/book-library/Api.Books.md
index 8d386d2e..1be6da45 100644
--- a/docs/technical/api/library/written-content-library/book-library/Api.Books.md
+++ b/docs/technical/api/library/written-content-library/book-library/Api.Books.md
@@ -32,6 +32,7 @@
- [Get Reading Section](#get-reading-section)
- [Get Reading Section Request](#get-reading-section-request)
- [Get Reading Section Response](#get-reading-section-response)
+ - [Delete Book](#delete-book)
## Book
@@ -870,3 +871,15 @@ Returns the binary resource identified by `resourceKey` of the book identified b
```
The response is the raw bytes of the resource, served with the `Content-Type` of the resource and with `X-Content-Type-Options: nosniff`. A resource whose declared media type could be rendered as an active document (for example an SVG) is served as an opaque binary download instead.
+
+### Delete Book
+
+```js
+DELETE api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{bookId}
+```
+
+```js
+200 Ok
+```
+
+Deletes the book identified by the route, together with its stored artwork.
diff --git a/docs/technical/requests/library/written-content-library/book-library/books/DeleteBook.http b/docs/technical/requests/library/written-content-library/book-library/books/DeleteBook.http
new file mode 100644
index 00000000..23bb7629
--- /dev/null
+++ b/docs/technical/requests/library/written-content-library/book-library/books/DeleteBook.http
@@ -0,0 +1,2 @@
+DELETE {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/books/{{$guid}}
+Authorization: Bearer {{ACCESS_TOKEN}}
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommand.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommand.cs
new file mode 100644
index 00000000..7c03bb2d
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommand.cs
@@ -0,0 +1,17 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+
+///
+/// Command for deleting a book by its Id.
+///
+/// The unique identifier of the media library this book belongs to, taken from the route.
+/// The unique identifier of the book to delete, taken from the route.
+[DebuggerDisplay("BookId: {BookId}")]
+public record DeleteBookCommand(
+ string? LibraryId,
+ string? BookId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandler.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandler.cs
new file mode 100644
index 00000000..e4cdaef2
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandler.cs
@@ -0,0 +1,133 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
+using Lumina.Domain.Common.Primitives;
+using Microsoft.Extensions.Logging;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+
+///
+/// Handler for the command to delete a book by its Id.
+///
+public class DeleteBookCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly IBookArtworkService _bookArtworkService;
+ private readonly ILogger _logger;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service for removing the artwork of a book.
+ /// Injected logger used to report the issues encountered while removing the stored artwork.
+ /// Injected service for authorization related functionality.
+ /// Injected service to retrieve the current user information.
+ /// Injected validator for application validation rules.
+ public DeleteBookCommandHandler(
+ IUnitOfWork unitOfWork,
+ IBookArtworkService bookArtworkService,
+ ILogger logger,
+ IAuthorizationService authorizationService,
+ ICurrentUserService currentUserService,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _bookArtworkService = bookArtworkService;
+ _logger = logger;
+ _authorizationService = authorizationService;
+ _currentUserService = currentUserService;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to delete a book by its Id.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ public async Task> HandleAsync(DeleteBookCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // The validator guarantees that the route identifiers are non-empty Guids before this point.
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid bookId = Guid.Parse(command.BookId!);
+
+ // Only the library of the book is needed to scope the delete, so the book row is read without its aggregate graph and without tracking.
+ Result getBookResult = await _unitOfWork.BookRepository
+ .GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getBookResult.IsFailure)
+ return getBookResult.Errors;
+ if (getBookResult.Value is null)
+ return DomainErrors.WrittenContent.BookNotFound;
+ BookEntity existingBook = getBookResult.Value;
+
+ // Resource scoping: the book must belong to the library named by the route, so that a book can never be deleted through another
+ // library's route; the mismatch is reported as not found, without disclosing that the book exists in another library.
+ if (existingBook.LibraryId != libraryId)
+ return DomainErrors.WrittenContent.BookNotFound;
+
+ // Admins can delete the books of all libraries; for everyone else, only the books of the libraries they own.
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(existingBook.LibraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // A book can only belong to a library that exists, so a client can never delete a book of a library of the host that is not there.
+ Result getLibraryResult = await _unitOfWork.LibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure)
+ return getLibraryResult.Errors;
+ if (getLibraryResult.Value is null)
+ return DomainErrors.Library.LibraryNotFound;
+ LibraryEntity library = getLibraryResult.Value;
+
+ // The artwork is stored under the library and author segments, so the author is resolved before the book is removed.
+ Result> getAuthorsResult = await _unitOfWork.BookRepository
+ .GetAuthorsDisplayNamesByBookIdsAsync([existingBook.Id], cancellationToken).ConfigureAwait(false);
+ if (getAuthorsResult.IsFailure)
+ return getAuthorsResult.Errors;
+ string authorName = getAuthorsResult.Value.TryGetValue(existingBook.Id, out string? authorDisplayName) && authorDisplayName is not null ? authorDisplayName : string.Empty;
+
+ // Delete the stored artwork of the book, best-effort, since a stale cover must not prevent the book from being removed.
+ Result deleteArtworkResult = _bookArtworkService.DeleteBookArtwork(libraryId, existingBook.Id, library.Title, authorName, existingBook.Title);
+ if (deleteArtworkResult.IsFailure)
+ _logger.LogWarning("Failed to delete the stored artwork of the book with Id '{BookId}' at path '{BookPath}', the artwork might remain orphaned.", existingBook.Id, existingBook.Path);
+
+ // Delete the book, whose stored artwork rows and participations are removed by the database cascade.
+ Result deleteBookResult = await _unitOfWork.BookRepository.DeleteByIdAsync(existingBook.Id, cancellationToken).ConfigureAwait(false);
+ if (deleteBookResult.IsFailure)
+ return deleteBookResult.Errors;
+
+ Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ if (saveChangesResult.IsFailure)
+ return saveChangesResult.Errors;
+
+ return Result.Deleted;
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandValidator.cs b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandValidator.cs
new file mode 100644
index 00000000..643b21af
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandValidator.cs
@@ -0,0 +1,40 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+
+///
+/// Validates the needed validation rules for .
+///
+public class DeleteBookCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public DeleteBookCommandValidator()
+ {
+ // Validates the identifier of the media library that owns the book, taken from the route.
+ RuleFor(command => command.LibraryId)
+ .NotEmpty()
+ .WithError(Errors.Library.LibraryIdCannotBeEmpty);
+
+ RuleFor(command => command.LibraryId)
+ .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
+ .When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
+ .WithError(Errors.Library.LibraryIdCannotBeEmpty);
+
+ // Validates the identifier of the book, taken from the route.
+ RuleFor(command => command.BookId)
+ .NotEmpty()
+ .WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
+
+ RuleFor(command => command.BookId)
+ .Must(bookId => Guid.TryParse(bookId, out Guid parsedBookId) && parsedBookId != Guid.Empty)
+ .When(command => command.BookId is not null && command.BookId.Length > 0)
+ .WithError(Errors.WrittenContent.BookIdCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs
index 9d231f16..64b98635 100644
--- a/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs
+++ b/src/Lumina.Presentation.Api/Common/Routes/Library/WrittenContentLibrary/BookLibrary/ApiRoutes.Books.cs
@@ -15,6 +15,7 @@ public static partial class ApiRoutes
public const string GET_BOOKS_LITE = "/libraries/{libraryId}/books/lite";
public const string ADD_BOOK = "/libraries/{libraryId}/books";
public const string UPDATE_BOOK = "/libraries/{libraryId}/books/{bookId}";
+ public const string DELETE_BOOK = "/libraries/{libraryId}/books/{bookId}";
public const string UPDATE_BOOK_COVER = "/libraries/{libraryId}/books/{bookId}/cover";
public const string GET_BOOK_READING_MANIFEST = "/libraries/{libraryId}/books/{bookId}/reading/manifest";
public const string GET_BOOK_READING_AVAILABILITY = "/libraries/{libraryId}/books/{bookId}/reading/availability";
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpoint.cs
new file mode 100644
index 00000000..3295b379
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpoint.cs
@@ -0,0 +1,54 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.WrittenContentLibrary.BookLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Http;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
+
+///
+/// API endpoint for the /libraries/{libraryId}/books/{bookId} route.
+///
+public class DeleteBookEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _deleteBookCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling delete book commands.
+ public DeleteBookEndpoint(ICommandHandler> deleteBookCommandHandler)
+ {
+ _deleteBookCommandHandler = deleteBookCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.DELETE);
+ Routes(ApiRoutes.Books.DELETE_BOOK);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Deletes a book by Id.
+ ///
+ /// The request object.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
+ {
+ // Take unique identifiers from the route.
+ string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
+ string? bookId = HttpContext.Request.RouteValues["bookId"]?.ToString();
+ Result result = await _deleteBookCommandHandler.HandleAsync(new DeleteBookCommand(libraryId, bookId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointSummary.cs
new file mode 100644
index 00000000..f9773595
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointSummary.cs
@@ -0,0 +1,114 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteBookEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public DeleteBookEndpointSummary()
+ {
+ Summary = "Deletes an existing book.";
+ Description = "Deletes the book identified by the route, together with its stored artwork. The book is deleted by an Admin, who can delete the books of all libraries, or by the owner of the library of the book.";
+
+ Response(200, "The book was successfully deleted.");
+
+ Response(401, "Authentication required.", "application/problem+json",
+ example: new[]
+ {
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "Authentication failed",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token is invalid",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(404, "The request failed because the requested book or its media library does not exist.", "application/problem+json",
+ example: new[]
+ {
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
+ title = "General.NotFound",
+ status = 404,
+ detail = "BookNotFound",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
+ traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
+ title = "General.NotFound",
+ status = 404,
+ detail = "LibraryNotFound",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
+ traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
+ }
+ }
+ );
+
+ Response(422, "The request did not pass validation checks.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc4918#section-11.2",
+ title = "General.Validation",
+ status = 422,
+ detail = "OneOrMoreValidationErrorsOccurred",
+ instance = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "LibraryIdCannotBeEmpty",
+ "BookIdCannotBeEmpty"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.slnx b/src/Lumina.slnx
index c023a76b..0def3ed3 100644
--- a/src/Lumina.slnx
+++ b/src/Lumina.slnx
@@ -245,6 +245,7 @@
+
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandFixture.cs
new file mode 100644
index 00000000..bd685e59
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandFixture.cs
@@ -0,0 +1,45 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteBookCommandFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the book belongs to, taken from the route.
+ /// Optional. The Id of the book to delete, taken from the route.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the book Id should be included, or forced to .
+ /// The created .
+ public DeleteBookCommand Create(
+ string? libraryId = null,
+ string? bookId = null,
+ bool includeLibraryId = true,
+ bool includeBookId = true)
+ {
+ return new DeleteBookCommand(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ includeBookId ? (bookId ?? Guid.NewGuid().ToString()) : null);
+ }
+
+ ///
+ /// Creates a list of .
+ ///
+ /// 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/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs
new file mode 100644
index 00000000..cdf76a2f
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs
@@ -0,0 +1,380 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.SharedKernel.Common.Enums.BookLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteBookEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly BookEntityFixture _bookEntityFixture = new();
+ private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public DeleteBookEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenBookBelongsToAnOwnedLibrary_ShouldDeleteTheBook()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Null(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId));
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenBookHasStoredArtwork_ShouldRemoveTheArtworkAndTheStoredCoverFile()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid libraryId, Guid bookId, string storedCoverPath) = await SeedLibraryBookAndCoverAsync(userId);
+ string fullCoverPath = Path.Combine(AppContext.BaseDirectory, storedCoverPath.TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
+ Assert.True(File.Exists(fullCoverPath));
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Null(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId));
+ Assert.Null(await dbContext.Books.SelectMany(book => book.Artwork).FirstOrDefaultAsync(artwork => artwork.BookId == bookId));
+ Assert.False(File.Exists(fullCoverPath));
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenBookDoesNotExist_ShouldReturnBookNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId);
+ string url = $"/api/v1/libraries/{libraryId}/books/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertNotFoundAsync(response, "BookNotFound", url);
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenBookRequestedThroughDifferentLibrary_ShouldReturnBookNotFoundProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, Guid bookId) = await SeedLibraryAndBookAsync(userId);
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{bookId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ // The route library id is enforced, so a book can never be deleted through another library's route, and the mismatch is
+ // reported as not found, without disclosing that the book exists in another library.
+ await AssertNotFoundAsync(response, "BookNotFound", url);
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenProblem()
+ {
+ // Arrange
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid otherLibraryId, Guid otherBookId) = await SeedLibraryAndBookAsync(otherUserId);
+ string url = $"/api/v1/libraries/{otherLibraryId}/books/{otherBookId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertProblemDetails(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url, "https://tools.ietf.org/html/rfc9110#section-15.5.4");
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenLibraryIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/not-a-guid/books/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "LibraryIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenBookIdIsNotParseable_ShouldReturnUnprocessableEntity()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/not-a-guid";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityWithValidationErrors(response, url, "BookIdCannotBeEmpty");
+ }
+
+ ///
+ /// Seeds an ebook library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds an ebook library owned by and a book belonging to it.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library and book.
+ private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid bookId = Guid.NewGuid();
+ LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false);
+ dbContext.Libraries.Add(library);
+ dbContext.Books.Add(book);
+ await dbContext.SaveChangesAsync();
+ return (libraryId, bookId);
+ }
+
+ ///
+ /// Seeds an ebook library owned by , a book belonging to it, and a stored cover file of that book together with its artwork row.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library and book, and the relative path of the stored cover file.
+ private async Task<(Guid libraryId, Guid bookId, string storedCoverPath)> SeedLibraryBookAndCoverAsync(Guid userId)
+ {
+ (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(userId);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ LibraryEntity library = await dbContext.Libraries.SingleAsync(library => library.Id == libraryId);
+ BookEntity book = await dbContext.Books.Include(book => book.Artwork).SingleAsync(book => book.Id == bookId);
+ IBookArtworkService bookArtworkService = scope.ServiceProvider.GetRequiredService();
+
+ // Store a minimal PNG-like payload through the same artwork service that the API uses, so that the stored path matches the one the deletion resolves.
+ byte[] payload = new byte[100];
+ payload[0] = 137;
+ payload[1] = 80;
+ payload[2] = 78;
+ payload[3] = 71;
+ payload[4] = 13;
+ payload[5] = 10;
+ payload[6] = 26;
+ payload[7] = 10;
+ Result saveArtworkResult;
+ using (MemoryStream artworkStream = new(payload))
+ saveArtworkResult = await bookArtworkService.SaveBookArtworkAsync(libraryId, bookId, library.Title, string.Empty, book.Title, artworkStream, "cover.png", CancellationToken.None);
+ Assert.False(saveArtworkResult.IsFailure);
+
+ book.Artwork.Add(_bookArtworkEntityFixture.Create(bookId: bookId, fileName: saveArtworkResult.Value));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, bookId, saveArtworkResult.Value);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the response is a not found problem details carrying the expected detail and request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ private async Task AssertNotFoundAsync(HttpResponseMessage response, string expectedDetail, string expectedInstance)
+ {
+ await AssertProblemDetails(response, HttpStatusCode.NotFound, "General.NotFound", expectedDetail, expectedInstance, "https://tools.ietf.org/html/rfc9110#section-15.5.5");
+ }
+
+ ///
+ /// Asserts the shape of a problem details response with the provided status, title, detail, instance and type.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected HTTP status code.
+ /// The expected problem title.
+ /// The expected problem detail.
+ /// The expected request instance path.
+ /// The expected problem type URI.
+ private async Task AssertProblemDetails(HttpResponseMessage response, HttpStatusCode statusCode, string expectedTitle, string expectedDetail, string expectedInstance, string expectedType)
+ {
+ Assert.Equal(statusCode, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)statusCode, problemDetails!["status"].GetInt32());
+ Assert.Equal(expectedType, problemDetails["type"].GetString());
+ Assert.Equal(expectedTitle, problemDetails["title"].GetString());
+ Assert.Equal(expectedDetail, problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityWithValidationErrors(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ Assert.All(expectedErrorCodes, code => Assert.Contains(code, errors["General.Validation"]));
+ }
+
+ ///
+ /// Disposes API factory resources.
+ ///
+ public async Task DisposeAsync()
+ {
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs
new file mode 100644
index 00000000..75a3f1de
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs
@@ -0,0 +1,225 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteBookEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly BookEntityFixture _bookEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public DeleteBookEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Books; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task DeleteBook_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/{Guid.NewGuid()}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Books; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task DeleteBook_WithSQLInjectionInBookId_ShouldNotCorruptOrLeakData(string maliciousBookId)
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{Guid.NewGuid()}/books/{Uri.EscapeDataString(maliciousBookId)}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenBookBelongsToAnotherUserLibrary_ShouldReturnForbiddenResult()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ Guid otherUserId = await SeedOtherUserAsync();
+ (Guid libraryId, Guid bookId) = await SeedLibraryAndBookAsync(otherUserId);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{libraryId}/books/{bookId}");
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task DeleteBook_WhenBookBelongsToAnotherUsersLibrary_ShouldReturnNotFoundWithoutDeletingIt()
+ {
+ // Arrange
+ HttpClient client = _apiFactory.CreateClient();
+ (Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(actingUsername);
+ (Guid ownLibraryId, _) = await SeedLibraryAndBookAsync(actingUserId);
+
+ // The book lives in a library owned by another user, and is referenced through the acting user's own library route.
+ HttpClient victimClient = _apiFactory.CreateClient();
+ (Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
+ _seededUsernames.Add(victimUsername);
+ (_, Guid victimBookId) = await SeedLibraryAndBookAsync(victimUserId);
+
+ // Act
+ HttpResponseMessage response = await client.DeleteAsync($"/api/v1/libraries/{ownLibraryId}/books/{victimBookId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.NotFound", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Equal("BookNotFound", problemDetails.RootElement.GetProperty("detail").GetString());
+
+ // The other user's book is untouched.
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.NotNull(await dbContext.Books.FirstOrDefaultAsync(book => book.Id == victimBookId));
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded other user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return userId;
+ }
+
+ ///
+ /// Seeds an ebook library owned by , together with a book of that library.
+ ///
+ /// The Id of the user that owns the library.
+ /// The Ids of the seeded library and book.
+ private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndBookAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ Guid bookId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Test Library", libraryType: LibraryType.EBook, contentLocations: []));
+ dbContext.Books.Add(_bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: "Test Book", includeMetadata: false));
+ await dbContext.SaveChangesAsync();
+ return (libraryId, bookId);
+ }
+
+ ///
+ /// Disposes the API factory resources.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandlerTests.cs
new file mode 100644
index 00000000..7fff63c6
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandHandlerTests.cs
@@ -0,0 +1,398 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
+using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+using Lumina.Domain.Common.Primitives;
+using Microsoft.Extensions.Logging;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteBookCommandHandlerTests
+{
+ private readonly IUnitOfWork _mockUnitOfWork;
+ private readonly IBookRepository _mockBookRepository;
+ private readonly ILibraryRepository _mockLibraryRepository;
+ private readonly IBookArtworkService _mockBookArtworkService;
+ private readonly ILogger _mockLogger;
+ private readonly IAuthorizationService _mockAuthorizationService;
+ private readonly ICurrentUserService _mockCurrentUserService;
+ private readonly IValidator _mockValidator;
+ private readonly DeleteBookCommandHandler _sut;
+ private readonly Guid _userId;
+ private readonly DeleteBookCommandFixture _deleteBookCommandFixture = new();
+ private readonly BookEntityFixture _bookEntityFixture = new();
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public DeleteBookCommandHandlerTests()
+ {
+ _mockUnitOfWork = Substitute.For();
+ _mockBookRepository = Substitute.For();
+ _mockLibraryRepository = Substitute.For();
+ _mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
+ _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository);
+ _mockBookArtworkService = Substitute.For();
+ _mockLogger = Substitute.For>();
+ _mockAuthorizationService = Substitute.For();
+ _mockCurrentUserService = Substitute.For();
+ _mockValidator = Substitute.For>();
+ _userId = Guid.NewGuid();
+
+ // Default stubs: the command is valid, the current user is authenticated, the ownership policy allows the deletion, the book has no author, the library exists, the artwork deletion succeeds, the book deletion succeeds and saving changes succeeds.
+ _mockValidator.Validate(Arg.Any()).Returns([]);
+ _mockCurrentUserService.UserId.Returns(_userId);
+ _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any())
+ .Returns(true);
+ _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(_ => Result.From(_libraryEntityFixture.Create()));
+ _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any())
+ .Returns(Result.From>(new Dictionary()));
+ _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(Result.Deleted);
+ _mockBookRepository.DeleteByIdAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.Deleted);
+ _mockUnitOfWork.SaveChangesAsync(Arg.Any())
+ .Returns(Result.Success);
+
+ _sut = new DeleteBookCommandHandler(_mockUnitOfWork, _mockBookArtworkService, _mockLogger, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenBookExists_ShouldDeleteBookAndReturnDeleted()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid bookId = Guid.Parse(command.BookId!);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
+ _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(book));
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(Result.Deleted, result.Value);
+ // The stored artwork of the book is removed before the book row, so that no artwork file is orphaned.
+ Received.InOrder(() =>
+ {
+ _mockBookArtworkService.DeleteBookArtwork(libraryId, bookId, Arg.Any(), Arg.Any(), book.Title);
+ _mockBookRepository.DeleteByIdAsync(bookId, Arg.Any());
+ });
+ await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any());
+ await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any());
+ await _mockAuthorizationService.Received(1).EvaluatePolicyAsync(
+ _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenBookHasAnAuthor_ShouldDeleteTheArtworkUnderTheAuthorSegments()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid bookId = Guid.Parse(command.BookId!);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
+ LibraryEntity library = _libraryEntityFixture.Create(id: libraryId);
+ _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(book));
+ _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(library));
+ _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any())
+ .Returns(Result.From>(new Dictionary { [bookId] = "J.R.R. Tolkien" }));
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ _mockBookArtworkService.Received(1).DeleteBookArtwork(libraryId, bookId, library.Title, "J.R.R. Tolkien", book.Title);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutTouchingAnyRepository()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ _mockValidator.Validate(Arg.Any())
+ .Returns([DomainErrors.WrittenContent.BookIdCannotBeEmpty]);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(DomainErrors.WrittenContent.BookIdCannotBeEmpty, result.FirstError);
+ await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ _mockCurrentUserService.UserId.Returns((Guid?)null);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
+ await _mockBookRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenBookRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
+ await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenBookDoesNotExist_ShouldReturnBookNotFoundError()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ _mockBookRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(_ => Result.From(null));
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(DomainErrors.WrittenContent.BookNotFound, result.FirstError);
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenBookBelongsToAnotherLibrary_ShouldReturnBookNotFoundWithoutEvaluatingThePolicy()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ Guid bookId = Guid.Parse(command.BookId!);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: Guid.NewGuid(), includeMetadata: false);
+ _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(book));
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ // Resource scoping is enforced before authorization, and the mismatch is reported as not found, without disclosing that the book exists in another library.
+ Assert.True(result.IsFailure);
+ Assert.Equal(DomainErrors.WrittenContent.BookNotFound, result.FirstError);
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid bookId = Guid.Parse(command.BookId!);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
+ _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(book));
+ _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any())
+ .Returns(false);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
+ await _mockAuthorizationService.Received(1).EvaluatePolicyAsync(
+ _userId, Arg.Is(context => context.LibraryId == libraryId), Arg.Any());
+ await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenLibraryRepositoryFails_ShouldReturnFailureResultWithoutDeleting()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid bookId = Guid.Parse(command.BookId!);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
+ _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(book));
+ _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
+ _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenLibraryDoesNotExist_ShouldReturnLibraryNotFoundError()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid bookId = Guid.Parse(command.BookId!);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
+ _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(book));
+ _mockLibraryRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(_ => Result.From(null));
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(DomainErrors.Library.LibraryNotFound, result.FirstError);
+ _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenAuthorLookupFails_ShouldReturnErrorWithoutDeleting()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid bookId = Guid.Parse(command.BookId!);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
+ _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(book));
+ _mockBookRepository.GetAuthorsDisplayNamesByBookIdsAsync(Arg.Any>(), Arg.Any())
+ .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
+ _mockBookArtworkService.DidNotReceive().DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockBookRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenArtworkDeletionFails_ShouldStillDeleteTheBook()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid bookId = Guid.Parse(command.BookId!);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
+ _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(book));
+ _mockBookArtworkService.DeleteBookArtwork(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any())
+ .Returns(Error.Failure(description: "Failed to delete the artwork"));
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ // A stale cover file must not prevent the book from being removed.
+ Assert.False(result.IsFailure);
+ Assert.Equal(Result.Deleted, result.Value);
+ await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any());
+ await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenDeleteBookFails_ShouldReturnErrorWithoutSaving()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid bookId = Guid.Parse(command.BookId!);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
+ _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(book));
+ _mockBookRepository.DeleteByIdAsync(Arg.Any(), Arg.Any())
+ .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
+ await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any());
+ await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnError()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid bookId = Guid.Parse(command.BookId!);
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
+ _mockBookRepository.GetByIdAsync(bookId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: Arg.Any())
+ .Returns(Result.From(book));
+ _mockUnitOfWork.SaveChangesAsync(Arg.Any())
+ .Returns(ApplicationErrors.Persistence.UniqueConstraintViolation);
+
+ // Act
+ Result result = await _sut.HandleAsync(command, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Persistence.UniqueConstraintViolation, result.FirstError);
+ await _mockBookRepository.Received(1).DeleteByIdAsync(bookId, Arg.Any());
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandValidatorTests.cs
new file mode 100644
index 00000000..6defc36d
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/WrittenContentLibrary/BookLibrary/Books/Commands/DeleteBook/DeleteBookCommandValidatorTests.cs
@@ -0,0 +1,97 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+using Lumina.Application.Fixtures.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+using Lumina.Application.UnitTests.Common.Setup;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Application.UnitTests.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteBookCommandValidatorTests
+{
+ private readonly DeleteBookCommandFixture _deleteBookCommandFixture = new();
+ private readonly DeleteBookCommandValidator _validator = new();
+
+ [Theory]
+ [InlineData(null)] // missing route value
+ [InlineData("")] // empty route value
+ [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
+ [InlineData("not-a-library-guid")] // non-Guid route value
+ [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
+ public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
+
+ // Act
+ List result = _validator.TestValidate(command);
+
+ // Assert
+ result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
+ }
+
+ [Theory]
+ [InlineData(null)] // missing route value
+ [InlineData("")] // empty route value
+ [InlineData(" ")] // whitespace route value, which both the not empty rule and the format rule reject
+ [InlineData("not-a-book-guid")] // non-Guid route value
+ [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
+ public void Validate_WhenBookIdIsEmptyOrInvalid_ShouldHaveValidationError(string? bookId)
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create(bookId: bookId, includeBookId: bookId is not null);
+
+ // Act
+ List result = _validator.TestValidate(command);
+
+ // Assert
+ result.ShouldHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
+ }
+
+ [Fact]
+ public void Validate_WhenLibraryIdIsValid_ShouldNotHaveValidationError()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create(libraryId: Guid.NewGuid().ToString());
+
+ // Act
+ List result = _validator.TestValidate(command);
+
+ // Assert
+ result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
+ }
+
+ [Fact]
+ public void Validate_WhenBookIdIsValid_ShouldNotHaveValidationError()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create(bookId: Guid.NewGuid().ToString());
+
+ // Act
+ List result = _validator.TestValidate(command);
+
+ // Assert
+ result.ShouldNotHaveValidationError(Errors.WrittenContent.BookIdCannotBeEmpty);
+ }
+
+ [Fact]
+ public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationErrors()
+ {
+ // Arrange
+ DeleteBookCommand command = _deleteBookCommandFixture.Create();
+
+ // Act
+ List result = _validator.TestValidate(command);
+
+ // Assert
+ result.ShouldNotHaveAnyValidationErrors();
+ }
+}
diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs
new file mode 100644
index 00000000..06cb0e9e
--- /dev/null
+++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/DeleteBook/DeleteBookEndpointTests.cs
@@ -0,0 +1,232 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Books.Commands.DeleteBook;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.HttpResults;
+using Microsoft.AspNetCore.Mvc;
+using NSubstitute;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteBookEndpointTests
+{
+ private readonly ICommandHandler> _mockHandler;
+ private readonly DeleteBookEndpoint _sut;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public DeleteBookEndpointTests()
+ {
+ _mockHandler = Substitute.For>>();
+ _sut = FastEndpoints.Factory.Create(_mockHandler);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
+ {
+ // Arrange
+ CancellationToken cancellationToken = CancellationToken.None;
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From(Result.Deleted));
+ ConfigureRouteValues();
+
+ // Act
+ IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
+
+ // Assert
+ Ok okResult = Assert.IsType>(result);
+ Assert.Equal(Result.Deleted, okResult.Value);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnProblemResult()
+ {
+ // Arrange
+ CancellationToken cancellationToken = CancellationToken.None;
+ Error expectedError = DomainErrors.WrittenContent.BookNotFound;
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(expectedError);
+ ConfigureRouteValues();
+
+ // Act
+ IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken);
+
+ // Assert
+ ProblemHttpResult problemDetails = Assert.IsType