Adds book deletion and restore to the web client.

Soft deletes books so the scan keeps their paths reserved, lists the deleted books on a themed page, and lets the user restore them. Updates the API, bundled themes, localization, documentation and tests.

Closes #213
This commit is contained in:
BinaryAlley committed 2026-11-13 18:00:00 +02:00
1 parent ef5ede6325
commit f26b07d4ff
125 files changed
+9856 -378

No files matched your search

@@ -0,0 +1,142 @@
#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.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.GetDeletedBooks;
/// <summary>
/// Contains security tests for the <see cref="GetDeletedBooksEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetDeletedBooksEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
private readonly BookArtworkEntityFixture _bookArtworkEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetDeletedBooksEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetDeletedBooksEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task GetDeletedBooks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/deleted-items";
// Act
HttpResponseMessage response = await _client.GetAsync(url);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["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 GetDeletedBooks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/books/deleted-items");
// 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 GetDeletedBooks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenAndNotLeakTheDeletedBook()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
const string TITLE = "Secret Deleted Book";
const string PATH = "/private/deleted-book.epub";
const string COVER_PATH = "/private/deleted-book-cover.jpg";
(Guid libraryId, _) = await SeedLibraryAndDeletedBookAsync(victimUserId, TITLE, PATH, COVER_PATH);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{libraryId}/books/deleted-items");
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain(TITLE, content, StringComparison.Ordinal);
Assert.DoesNotContain(PATH, content, StringComparison.Ordinal);
Assert.DoesNotContain(COVER_PATH, content, StringComparison.Ordinal);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/>, together with a deleted book and its cover.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="title">The title of the deleted book.</param>
/// <param name="path">The file system path of the deleted book.</param>
/// <param name="coverPath">The stored cover path of the deleted book.</param>
/// <returns>The Id of the seeded library and the seeded book.</returns>
private async Task<(Guid libraryId, BookEntity book)> SeedLibraryAndDeletedBookAsync(Guid userId, string title, string path, string coverPath)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: path, title: title, isDeleted: true, includeMetadata: false);
book.Artwork = [_bookArtworkEntityFixture.Create(bookId: book.Id, artworkType: ArtworkType.Cover, ordinal: 0, fileName: coverPath)];
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.EBook, contentLocations: []));
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return (libraryId, book);
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,165 @@
#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.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
/// <summary>
/// Contains security tests for the <see cref="RestoreBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private readonly LuminaApiFactory _apiFactory;
private readonly HttpClient _client;
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
private readonly List<string> _seededUsernames = [];
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly BookEntityFixture _bookEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RestoreBookEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
_client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
}
[Fact]
public async Task RestoreBook_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string url = $"/api/v1/libraries/{Guid.NewGuid()}/books/{Guid.NewGuid()}/restore";
// Act
HttpResponseMessage response = await _client.PostAsync(url, null);
// Assert
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
Assert.NotNull(problemDetails);
Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
Assert.Equal("Unauthorized", problemDetails["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 RestoreBook_WithSQLInjectionInRouteIds_ShouldNotCorruptOrLeakData(string maliciousId)
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/books/{Uri.EscapeDataString(maliciousId)}/restore", null);
// 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 RestoreBook_WhenBookBelongsToAnotherUser_ShouldReturnForbiddenAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(Guid libraryId, Guid bookId) = await SeedLibraryAndDeletedBookAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{libraryId}/books/{bookId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity? book = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == bookId);
Assert.NotNull(book);
Assert.True(book!.IsDeleted);
}
[Fact]
public async Task RestoreBook_WhenBookIsRestoredThroughAnotherLibrary_ShouldReturnNotFoundAndKeepItDeleted()
{
// Arrange
HttpClient client = _apiFactory.CreateClient();
(Guid actingUserId, string actingUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(actingUsername);
(Guid ownLibraryId, _) = await SeedLibraryAndDeletedBookAsync(actingUserId, isDeleted: false);
HttpClient victimClient = _apiFactory.CreateClient();
(Guid victimUserId, string victimUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(victimClient);
_seededUsernames.Add(victimUsername);
(_, Guid victimBookId) = await SeedLibraryAndDeletedBookAsync(victimUserId);
// Act
HttpResponseMessage response = await client.PostAsync($"/api/v1/libraries/{ownLibraryId}/books/{victimBookId}/restore", null);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
BookEntity? victimBook = await dbContext.Books.FirstOrDefaultAsync(book => book.Id == victimBookId);
Assert.NotNull(victimBook);
Assert.True(victimBook!.IsDeleted);
}
/// <summary>
/// Seeds an ebook library owned by <paramref name="userId"/>, together with a book in the requested deletion state.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="isDeleted">Whether the seeded book is soft deleted.</param>
/// <returns>The Ids of the seeded library and book.</returns>
private async Task<(Guid libraryId, Guid bookId)> SeedLibraryAndDeletedBookAsync(Guid userId, bool isDeleted = true)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid libraryId = Guid.NewGuid();
BookEntity book = _bookEntityFixture.Create(libraryId: libraryId, path: $"/books/{Guid.NewGuid():N}.epub", isDeleted: isDeleted, includeMetadata: false);
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Victim Library", libraryType: LibraryType.EBook, contentLocations: []));
dbContext.Books.Add(book);
await dbContext.SaveChangesAsync();
return (libraryId, book.Id);
}
/// <summary>
/// Removes the users created by the tests.
/// </summary>
public void Dispose()
{
_client.Dispose();
foreach (string username in _seededUsernames)
_apiFactory.RemoveTestUser(username);
}
}
@@ -0,0 +1,133 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeleteBook;
/// <summary>
/// Contains security tests for the <see cref="DeleteBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeleteBookEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public DeleteBookEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task DeleteBook_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverDeleteAnotherBook(string maliciousId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
string normalizedId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{libraryId}/books/{normalizedId}");
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(maliciousId, libraryId.ToString());
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains($"libraries/{libraryId}/books/{normalizedId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task DeleteBook_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
string normalizedId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterDeleteSuccess($"libraries/{normalizedId}/books/{bookId}");
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId.ToString(), maliciousLibraryId);
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains($"libraries/{normalizedId}/books/{bookId}", _apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task DeleteBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid bookId = Guid.NewGuid();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(bookId.ToString(), libraryId.ToString());
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
[Fact]
public async Task DeleteBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(deleteRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
}
/// <summary>
/// Builds the delete request for the book identified by the route, with the owning library passed through the query string.
/// </summary>
/// <param name="bookId">The raw route value of the book Id.</param>
/// <param name="libraryId">The raw query value of the library Id.</param>
/// <returns>The configured delete request.</returns>
private static HttpRequestMessage CreateDeleteRequest(string bookId, string libraryId)
{
HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-delete-book?libraryId={Uri.EscapeDataString(libraryId)}")
{
// The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation.
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return deleteRequest;
}
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.DeletedBooks;
/// <summary>
/// Contains security tests for the <see cref="DeletedBooksViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletedBooksViewEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="DeletedBooksViewEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public DeletedBooksViewEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task DeletedBooksView_WhenNotAuthenticated_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
// Act
HttpResponseMessage response = await anonymousClient.GetAsync($"/en-us/library/written-content-library/books-library/books/deleted-items?libraryId={Guid.NewGuid()}");
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
}
}
@@ -0,0 +1,133 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.SecurityTests.Common.Setup;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
#endregion
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.WrittenContentLibrary.BookLibrary.Books.RestoreBook;
/// <summary>
/// Contains security tests for the <see cref="RestoreBookEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RestoreBookEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RestoreBookEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public RestoreBookEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task RestoreBook_WithSQLInjectionInRouteId_ShouldNormalizeTheIdAndNeverRestoreAnotherBook(string maliciousId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
string normalizedId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{libraryId}/books/{normalizedId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(maliciousId, libraryId.ToString());
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains($"libraries/{libraryId}/books/{normalizedId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(request => request.Endpoint));
}
[Theory]
[InlineData("'; DROP TABLE Books; --")] // destructive injection
[InlineData("' OR '1'='1")] // boolean-based injection
public async Task RestoreBook_WithSQLInjectionInLibraryQueryId_ShouldNormalizeTheLibraryId(string maliciousLibraryId)
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid bookId = Guid.NewGuid();
string normalizedId = Guid.Empty.ToString();
_apiFactory.ApiClientStub.RegisterPostResponse<object>($"libraries/{normalizedId}/books/{bookId}/restore", new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(bookId.ToString(), maliciousLibraryId);
restoreRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
Assert.Contains($"libraries/{normalizedId}/books/{bookId}/restore", _apiFactory.ApiClientStub.PostRequests.Select(request => request.Endpoint));
}
[Fact]
public async Task RestoreBook_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
_apiFactory.ApiClientStub.Reset();
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
[Fact]
public async Task RestoreBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
HttpRequestMessage restoreRequest = CreateRestoreRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
// Act
HttpResponseMessage response = await anonymousClient.SendAsync(restoreRequest);
// Assert
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
Assert.Empty(_apiFactory.ApiClientStub.PostRequests);
}
/// <summary>
/// Builds the restore request for the book identified by the route, with the owning library passed through the query string.
/// </summary>
/// <param name="bookId">The raw route value of the book Id.</param>
/// <param name="libraryId">The raw query value of the library Id.</param>
/// <returns>The configured restore request.</returns>
private static HttpRequestMessage CreateRestoreRequest(string bookId, string libraryId)
{
HttpRequestMessage restoreRequest = new(HttpMethod.Post, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-restore-book?libraryId={Uri.EscapeDataString(libraryId)}")
{
// The front-end sends the JSON content type even for bodyless POST requests, which triggers the antiforgery validation.
Content = new StringContent("{}", Encoding.UTF8, "application/json")
};
// The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted.
restoreRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
restoreRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return restoreRequest;
}
}