Adds artwork provider system and Calibre plugin

This commit is contained in:
BinaryAlley committed 2026-08-24 14:18:14 -07:00
1 parent c82fadc7a2
commit 6693ff3f60
124 files changed
+9715 -74

No files matched your search

@@ -0,0 +1,119 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
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.Plugins.GetLibraryArtworkProviders;
/// <summary>
/// Contains security tests for the <c>/libraries/{libraryId}/artwork-providers</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetLibraryArtworkProvidersEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task GetLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
// Act
HttpResponseMessage response = await _client.GetAsync($"/api/v1/libraries/{libraryId}/artwork-providers");
// 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("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
public async Task GetLibraryArtworkProviders_WithSQLInjectionInLibraryId_ShouldNotLeakOrError(string maliciousLibraryId)
{
// Arrange
// authenticate with an admin user and seed a library with an artwork provider configuration, so a valid id would reach the handler
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedConfigurationAsync(libraryId);
// Act
HttpResponseMessage response = await client.GetAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/artwork-providers");
// Assert
// note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
// note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,133 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.ReorderLibraryArtworkProviders;
/// <summary>
/// Contains security tests for the <c>/libraries/{libraryId}/artwork-providers/reorder</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderLibraryArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public ReorderLibraryArtworkProvidersEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task ReorderLibraryArtworkProviders_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
libraryId: Guid.NewGuid(),
pluginIds: [Guid.NewGuid()]
);
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", request);
// 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("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/reorder", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Plugins--")] // destructive injection
public async Task ReorderLibraryArtworkProviders_WithSQLInjectionInPluginIds_ShouldNotLeakOrError(string maliciousPluginId)
{
// Arrange
// authenticate with an admin user and seed a library with artwork provider configurations, so valid ids would reach the handler
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedConfigurationAsync(libraryId, rank: 1);
await SeedConfigurationAsync(libraryId, rank: 2);
// Act
// the malicious value cannot bind to the Guid-typed PluginIds request property, so the body fails JSON deserialization
// before it ever reaches the endpoint handler
HttpResponseMessage response = await client.PutAsJsonAsync(
$"/api/v1/libraries/{libraryId}/artwork-providers/reorder",
new { libraryId, pluginIds = new[] { maliciousPluginId } });
// Assert
// note: observed status is 500 because the JSON body cannot be deserialized into the Guid-typed PluginIds property, and
// FastEndpoints, combined with DontCatchExceptions(), turns the resulting JsonException into a 500 response instead of 400
// (pre-existing production bug, not fixed here)
// note: that 500 body leaks the JsonException details, so no DoesNotContain("Exception") is asserted here
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <param name="rank">The rank of the provider.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId, int rank)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: rank));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,126 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Fixtures.Common.DataAccess.Entities.Plugins;
using Lumina.Contracts.Fixtures.Core.Requests.Plugins;
using Lumina.Contracts.Requests.Plugins;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Presentation.Api.SecurityTests.Common.Setup;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Plugins.SetLibraryArtworkProviderEnabled;
/// <summary>
/// Contains security tests for the <c>/libraries/{libraryId}/artwork-providers/{pluginId}/enabled</c> route.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledEndpointTests : IClassFixture<LuminaApiFactory>
{
private readonly HttpClient _client;
private readonly LuminaApiFactory _apiFactory;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
private readonly LibraryEntityFixture _libraryEntityFixture = new();
private readonly LibraryArtworkProviderConfigurationEntityFixture _libraryArtworkProviderConfigurationEntityFixture = new();
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetLibraryArtworkProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public SetLibraryArtworkProviderEnabledEndpointTests(LuminaApiFactory apiFactory)
{
_apiFactory = apiFactory;
_client = apiFactory.CreateClient();
}
[Fact]
public async Task SetLibraryArtworkProviderEnabled_WhenUnauthorized_ShouldReturnUnauthorizedResult()
{
// Arrange
string libraryId = Guid.NewGuid().ToString();
string pluginId = Guid.NewGuid().ToString();
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create();
// Act
HttpResponseMessage response = await _client.PutAsJsonAsync($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", request);
// 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("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
Assert.Equal("Unauthorized", problemDetails["title"].GetString());
Assert.Equal($"/api/v1/libraries/{libraryId}/artwork-providers/{pluginId}/enabled", problemDetails["instance"].GetProperty("value").GetString());
Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
}
[Theory]
[InlineData("' OR '1'='1")] // basic SQL injection
[InlineData("'; DROP TABLE Libraries--")] // destructive injection
public async Task SetLibraryArtworkProviderEnabled_WithSQLInjectionInRouteParameters_ShouldNotLeakOrError(string maliciousId)
{
// Arrange
// authenticate with an admin user and seed a library with an artwork provider configuration, so valid ids would reach the handler
HttpClient client = _apiFactory.CreateClient();
Guid userId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(client);
Guid libraryId = await SeedLibraryAsync(userId);
await SeedConfigurationAsync(libraryId);
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), isEnabled: true);
// Act
HttpResponseMessage response = await client.PutAsJsonAsync($"/api/v1/libraries/{Uri.EscapeDataString(maliciousId)}/artwork-providers/{Guid.NewGuid()}/enabled", request);
// Assert
// note: the {libraryId} route parameter is Guid-typed, so the malicious value fails model binding before it reaches the handler
// note: observed status is 500 because FastEndpoints, combined with DontCatchExceptions(), turns the binding
// ValidationFailureException into a 500 response instead of 400/422 (pre-existing production bug, not fixed here)
// note: that 500 body leaks the ValidationFailureException details, so no DoesNotContain("Exception") is asserted here
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Seeds a <see cref="Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management.LibraryEntity"/> owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a <see cref="LibraryArtworkProviderConfigurationEntity"/> for the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the media library.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task SeedConfigurationAsync(Guid libraryId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.LibraryArtworkProviderConfigurations.Add(_libraryArtworkProviderConfigurationEntityFixture.Create(libraryId: libraryId, pluginId: Guid.NewGuid(), rank: 1, isEnabled: false));
await dbContext.SaveChangesAsync();
}
}
@@ -0,0 +1,236 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Application.Core.MediaLibrary.WrittenContentLibrary.BooksLibrary.Artwork;
using Lumina.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
using Lumina.Contracts.Fixtures.Core.DTO.Common;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Environment;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Path;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Strategies.Platform;
using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.PhotoLibrary;
using Lumina.Infrastructure.Common.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NSubstitute;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.MediaLibrary.Artwork;
/// <summary>
/// Contains security tests for the <see cref="IBookArtworkService"/> contract, exercised through the real <see cref="BookArtworkService"/> implementation resolved from the dependency injection container.
/// </summary>
[ExcludeFromCodeCoverage]
public class BookArtworkServiceSecurityTests
{
private readonly IFileTypeService _mockFileTypeService;
private readonly IFileProviderService _mockFileProviderService;
private readonly IDirectoryProviderService _mockDirectoryProviderService;
private readonly IBookArtworkService _sut;
private readonly FileSystemPathIdFixture _fileSystemPathIdFixture = new();
private readonly ArtworkDtoFixture _artworkDtoFixture = new();
private readonly MediaSettingsDtoFixture _mediaSettingsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="BookArtworkServiceSecurityTests"/> class.
/// </summary>
public BookArtworkServiceSecurityTests()
{
IEnvironmentContext mockEnvironmentContext = Substitute.For<IEnvironmentContext>();
_mockFileTypeService = Substitute.For<IFileTypeService>();
_mockFileProviderService = Substitute.For<IFileProviderService>();
_mockDirectoryProviderService = Substitute.For<IDirectoryProviderService>();
mockEnvironmentContext.FileTypeService.Returns(_mockFileTypeService);
mockEnvironmentContext.FileProviderService.Returns(_mockFileProviderService);
mockEnvironmentContext.DirectoryProviderService.Returns(_mockDirectoryProviderService);
MediaSettingsDto mediaSettings = _mediaSettingsDtoFixture.Create(rootDirectory: "media", librariesDirectory: "libraries", booksDirectory: "books");
IConfiguration mockConfiguration = Substitute.For<IConfiguration>();
mockConfiguration.GetSection(Arg.Any<string>()).Returns(Substitute.For<IConfigurationSection>());
ServiceCollection services = new();
services.AddInfrastructureLayerServices(mockConfiguration);
services.AddScoped(_ => mockEnvironmentContext);
// the real path service is used, so that the sanitization of hostile segment names is exercised
services.AddScoped(_ => CreateRealPathService());
services.AddSingleton(Options.Create(mediaSettings));
ServiceProvider serviceProvider = services.BuildServiceProvider();
using IServiceScope scope = serviceProvider.CreateScope();
_sut = scope.ServiceProvider.GetRequiredService<IBookArtworkService>();
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLocalArtworkIsAReparsePoint_ShouldRejectIt()
{
// Arrange
string targetDirectory = Path.Combine(Path.GetTempPath(), $"lumina-security-junction-target-{Guid.NewGuid():N}");
Directory.CreateDirectory(targetDirectory);
string linkPath = Path.Combine(Path.GetTempPath(), $"lumina-security-junction-link-{Guid.NewGuid():N}");
if (!TryCreateJunction(linkPath, targetDirectory))
{
Directory.Delete(targetDirectory, true);
return; // the environment does not support creating reparse points
}
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), "Library", "Author", "Title", _artworkDtoFixture.Create(localPath: linkPath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
Assert.Equal(Errors.FileSystemManagement.InvalidPath, result.FirstError);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
// Windows removes a junction with Directory.Delete, while Unix-like platforms unlink the symbolic link with File.Delete
if (OperatingSystem.IsWindows())
Directory.Delete(linkPath, true);
else
File.Delete(linkPath);
Directory.Delete(targetDirectory, true);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenNameSegmentsContainPathTraversal_ShouldSanitizeThemIntoLiteralSegments()
{
// Arrange
string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-security-source-{Guid.NewGuid():N}.jpg");
File.WriteAllBytes(sourcePath, new byte[1024]);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
_mockDirectoryProviderService.DirectoryExists(Arg.Any<FileSystemPathId>())
.Returns(Result.From(true));
_mockFileProviderService.GetFilePaths(Arg.Any<FileSystemPathId>(), true)
.Returns(Result.From<IEnumerable<FileSystemPathId>>([]));
string capturedDestinationPath = string.Empty;
_mockFileProviderService.CopyFile(Arg.Any<FileSystemPathId>(), Arg.Do<FileSystemPathId>(destination => capturedDestinationPath = destination.Path), true)
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpg"))));
_mockFileProviderService.RenameFile(Arg.Any<FileSystemPathId>(), "cover.jpeg")
.Returns(Result.From(_fileSystemPathIdFixture.Create(Path.Combine(AppContext.BaseDirectory, "media", "books", "cover.jpeg"))));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(
Guid.NewGuid(),
Guid.NewGuid(),
libraryName: "..\\..\\Library",
authorName: "..\\evil",
bookTitle: "..\\..\\cover",
_artworkDtoFixture.Create(localPath: sourcePath),
CancellationToken.None);
// Assert
Assert.False(result.IsFailure);
Assert.False(string.IsNullOrEmpty(capturedDestinationPath));
string[] segments = capturedDestinationPath.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries);
Assert.DoesNotContain(segments, segment => segment == "..");
Assert.DoesNotContain(segments, segment => segment == ".");
Assert.DoesNotContain(result.Value.Split(['\\', '/'], StringSplitOptions.RemoveEmptyEntries), segment => segment == "..");
}
finally
{
File.Delete(sourcePath);
}
}
[Fact]
public async Task SaveBookArtworkAsync_WhenLibraryNameIsADotDotSegment_ShouldReturnInvalidPath()
{
// Arrange
string sourcePath = Path.Combine(Path.GetTempPath(), $"lumina-security-source-{Guid.NewGuid():N}.jpg");
File.WriteAllBytes(sourcePath, new byte[1024]);
try
{
_mockFileProviderService.FileExists(Arg.Any<FileSystemPathId>()).Returns(Result.From(true));
_mockFileTypeService.GetImageTypeAsync(Arg.Any<FileSystemPathId>(), Arg.Any<CancellationToken>())
.Returns(Result.From(ImageType.JPEG));
// Act
Result<string> result = await _sut.SaveBookArtworkAsync(Guid.NewGuid(), Guid.NewGuid(), libraryName: "..", authorName: "Author", bookTitle: "Title", _artworkDtoFixture.Create(localPath: sourcePath), CancellationToken.None);
// Assert
Assert.True(result.IsFailure);
_mockFileProviderService.DidNotReceive().CopyFile(Arg.Any<FileSystemPathId>(), Arg.Any<FileSystemPathId>(), true);
}
finally
{
File.Delete(sourcePath);
}
}
/// <summary>
/// Creates a real <see cref="PathService"/> backed by a stubbed path strategy, so that the sanitization of hostile segment names is exercised.
/// </summary>
/// <returns>The created real path service.</returns>
private static IPathService CreateRealPathService()
{
IPathStrategy mockPathStrategy = Substitute.For<IPathStrategy>();
mockPathStrategy.PathSeparator.Returns(Path.DirectorySeparatorChar);
mockPathStrategy.GetInvalidPathSegmentCharsForPlatform().Returns(Path.GetInvalidFileNameChars());
mockPathStrategy.CombinePath(Arg.Any<FileSystemPathId>(), Arg.Any<string>())
.Returns(callInfo => Result.From(FileSystemPathId.Create(Path.Combine(callInfo.Arg<FileSystemPathId>().Path, callInfo.Arg<string>())).Value));
mockPathStrategy.IsValidPath(Arg.Any<FileSystemPathId>()).Returns(true);
IPlatformContext mockPlatformContext = Substitute.For<IPlatformContext>();
mockPlatformContext.PathStrategy.Returns(mockPathStrategy);
IPlatformContextManager mockPlatformContextManager = Substitute.For<IPlatformContextManager>();
mockPlatformContextManager.GetCurrentContext().Returns(mockPlatformContext);
return new PathService(mockPlatformContextManager);
}
/// <summary>
/// Creates a file system link that points to the target directory: a junction on Windows, and a symbolic link on Unix-like platforms.
/// </summary>
/// <param name="linkPath">The file system path of the link to create.</param>
/// <param name="targetDirectory">The file system path of the directory the link points to.</param>
/// <returns><see langword="true"/> when the link was created, <see langword="false"/> otherwise.</returns>
private static bool TryCreateJunction(string linkPath, string targetDirectory)
{
try
{
System.Diagnostics.ProcessStartInfo startInfo = OperatingSystem.IsWindows()
? new()
{
FileName = "cmd.exe",
Arguments = $"/c mklink /J \"{linkPath}\" \"{targetDirectory}\"",
CreateNoWindow = true,
UseShellExecute = false
}
: new()
{
FileName = "ln",
CreateNoWindow = true,
UseShellExecute = false
};
if (!OperatingSystem.IsWindows())
{
startInfo.ArgumentList.Add("-s");
startInfo.ArgumentList.Add(targetDirectory);
startInfo.ArgumentList.Add(linkPath);
}
System.Diagnostics.Process process = System.Diagnostics.Process.Start(startInfo)!;
process.WaitForExit(5000);
return process.ExitCode == 0;
}
catch (Exception)
{
return false;
}
}
}
@@ -0,0 +1,110 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Plugins.Calibre.Core;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Plugins.Calibre;
/// <summary>
/// Contains security tests for the <see cref="CalibreArtworkProvider"/> class, exercised through the public artwork provider surface.
/// </summary>
[ExcludeFromCodeCoverage]
public class CalibreArtworkProviderSecurityTests
{
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
[Fact]
public async Task GetArtworkAsync_WhenCoverHrefIsABareFileName_ShouldReturnTheCoverInsideTheBookDirectory()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = WriteBookWithCoverReference(bookDirectory, "cover.jpg");
File.WriteAllText(Path.Combine(bookDirectory, "cover.jpg"), "image-bytes");
IArtworkProvider provider = CreateArtworkProvider();
// Act
ArtworkDto? result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Equal(Path.Combine(bookDirectory, "cover.jpg"), result!.LocalPath);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Theory]
[InlineData("../cover.jpg")] // parent directory escape
[InlineData("../../cover.jpg")] // multiple parent directory escape
[InlineData("sub/cover.jpg")] // forward slash path traversal
[InlineData("sub\\cover.jpg")] // backslash path traversal
[InlineData(@"C:\Windows\System32\drivers\etc\hosts")] // absolute Windows path
[InlineData("/etc/passwd")] // absolute Unix path
[InlineData("http://evil.example/cover.jpg")] // remote URL
[InlineData("file:///etc/passwd")] // file URI
public async Task GetArtworkAsync_WhenCoverHrefEscapesTheBookDirectory_ShouldReturnNull(string coverHref)
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = WriteBookWithCoverReference(bookDirectory, coverHref);
IArtworkProvider provider = CreateArtworkProvider();
// Act
ArtworkDto? result = await provider.GetArtworkAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
Assert.Null(result);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
/// <summary>
/// Creates the Calibre artwork provider by registering the plugin services and resolving the keyed artwork provider.
/// </summary>
/// <returns>The created Calibre artwork provider.</returns>
private static IArtworkProvider CreateArtworkProvider()
{
ServiceCollection services = new();
new CalibrePlugin().RegisterServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
return serviceProvider.GetKeyedService<IArtworkProvider>(CalibrePlugin.s_pluginId)!;
}
/// <summary>
/// Writes an OPF file that references the given cover into the book directory, and returns the path of the book.
/// </summary>
/// <param name="bookDirectory">The file system path of the directory the OPF file is written into.</param>
/// <param name="coverHref">The href of the cover the OPF file references.</param>
/// <returns>The file system path of the book.</returns>
private static string WriteBookWithCoverReference(string bookDirectory, string coverHref)
{
string opf = $$"""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>Test</dc:title></metadata><guide><reference type="cover" href="{{coverHref}}"/></guide></package>""";
string bookPath = Path.Combine(bookDirectory, "book.epub");
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opf);
return bookPath;
}
/// <summary>
/// Creates a unique temporary directory for the book.
/// </summary>
/// <returns>The file system path of the created temporary directory.</returns>
private static string CreateTempDirectory()
{
string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-security-artwork-{Guid.NewGuid():N}");
Directory.CreateDirectory(directoryPath);
return directoryPath;
}
}
@@ -0,0 +1,155 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Plugins.Calibre.Core;
using Lumina.Plugins.Calibre.Core.Opf;
using Lumina.Plugins.Contracts.Core.Metadata;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Api.SecurityTests.Core.Plugins.Calibre.Opf;
/// <summary>
/// Contains security tests for the <see cref="OpfReader"/> class, exercised through the public metadata provider surface.
/// </summary>
[ExcludeFromCodeCoverage]
public class OpfReaderSecurityTests
{
private const int MAX_OPF_FILE_SIZE_BYTES = 5 * 1024 * 1024;
private readonly BookMetadataLookupDtoFixture _bookMetadataLookupDtoFixture = new();
[Fact]
public async Task GetMetadataAsync_WhenOpfContainsADoctypeWithAnExternalEntity_ShouldNotExpandTheEntity()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
// the OPF is untrusted XML, so a DTD with an external entity must be rejected instead of being read and expanded
string opfContent = """<?xml version="1.0" encoding="utf-8"?><!DOCTYPE package [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>&xxe;</dc:title></metadata></package>""";
string bookPath = WriteBookWithOpf(bookDirectory, opfContent);
IMetadataProvider provider = CreateMetadataProvider();
// Act
MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Null(((BookMetadataDto)result!).Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetMetadataAsync_WhenOpfContainsBillionLaughsStyleEntityExpansion_ShouldNotExpandTheEntities()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string opfContent = """<?xml version="1.0" encoding="utf-8"?><!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"><!ENTITY lol3 "&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;">]><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>&lol3;</dc:title></metadata></package>""";
string bookPath = WriteBookWithOpf(bookDirectory, opfContent);
IMetadataProvider provider = CreateMetadataProvider();
// Act
MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Null(((BookMetadataDto)result!).Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetMetadataAsync_WhenOpfIsOversized_ShouldNotParseIt()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string oversizedContent = $"""<?xml version="1.0" encoding="utf-8"?><package xmlns="http://www.idpf.org/2007/opf"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>{new string('a', MAX_OPF_FILE_SIZE_BYTES + 100)}</dc:title></metadata></package>""";
string bookPath = WriteBookWithOpf(bookDirectory, oversizedContent);
IMetadataProvider provider = CreateMetadataProvider();
// Act
MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Null(((BookMetadataDto)result!).Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
[Fact]
public async Task GetMetadataAsync_WhenOpfIsMalformedXml_ShouldNotExposeAnException()
{
// Arrange
string bookDirectory = CreateTempDirectory();
try
{
string bookPath = WriteBookWithOpf(bookDirectory, """<package xmlns="http://www.idpf.org/2007/opf"><metadata><dc:title>Unclosed""");
IMetadataProvider provider = CreateMetadataProvider();
// Act
MetadataDto? result = await provider.GetMetadataAsync(_bookMetadataLookupDtoFixture.Create(path: bookPath), CancellationToken.None);
// Assert
// a malformed OPF must be swallowed and must not leak an exception to the caller
Assert.NotNull(result);
Assert.Null(((BookMetadataDto)result!).Title);
}
finally
{
Directory.Delete(bookDirectory, true);
}
}
/// <summary>
/// Creates the Calibre metadata provider by registering the plugin services and resolving the keyed metadata provider.
/// </summary>
/// <returns>The created Calibre metadata provider.</returns>
private static IMetadataProvider CreateMetadataProvider()
{
ServiceCollection services = new();
new CalibrePlugin().RegisterServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
return serviceProvider.GetKeyedService<IMetadataProvider>(CalibrePlugin.s_pluginId)!;
}
/// <summary>
/// Writes an OPF file with the given content into the book directory, and returns the path of the book.
/// </summary>
/// <param name="bookDirectory">The file system path of the directory the OPF file is written into.</param>
/// <param name="opfContent">The content of the OPF file to write.</param>
/// <returns>The file system path of the book.</returns>
private static string WriteBookWithOpf(string bookDirectory, string opfContent)
{
string bookPath = Path.Combine(bookDirectory, "book.epub");
File.WriteAllText(Path.Combine(bookDirectory, "metadata.opf"), opfContent);
return bookPath;
}
/// <summary>
/// Creates a unique temporary directory for the book.
/// </summary>
/// <returns>The file system path of the created temporary directory.</returns>
private static string CreateTempDirectory()
{
string directoryPath = Path.Combine(Path.GetTempPath(), $"lumina-security-opf-{Guid.NewGuid():N}");
Directory.CreateDirectory(directoryPath);
return directoryPath;
}
}