#region ========================================================================= USING ===================================================================================== using Microsoft.Extensions.DependencyInjection; using Nemera.Contracts.DTO.Common; using Nemera.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Nemera.Contracts.Fixtures.Core.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary; using Nemera.Plugins.Calibre.Core; using Nemera.Plugins.Calibre.Core.Opf; using Nemera.Plugins.Contracts.Core.Metadata; using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; using System.Threading.Tasks; #endregion namespace Nemera.Plugins.Calibre.SecurityTests.Core.Opf; /// /// Contains security tests for the class, exercised through the public metadata provider surface. /// [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 = """]>&xxe;"""; 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!).Metadata!.Title); } finally { Directory.Delete(bookDirectory, true); } } [Fact] public async Task GetMetadataAsync_WhenOpfContainsBillionLaughsStyleEntityExpansion_ShouldNotExpandTheEntities() { // Arrange string bookDirectory = CreateTempDirectory(); try { string opfContent = """]>&lol3;"""; 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!).Metadata!.Title); } finally { Directory.Delete(bookDirectory, true); } } [Fact] public async Task GetMetadataAsync_WhenOpfIsOversized_ShouldNotParseIt() { // Arrange string bookDirectory = CreateTempDirectory(); try { string oversizedContent = $"""{new string('a', MAX_OPF_FILE_SIZE_BYTES + 100)}"""; 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!).Metadata!.Title); } finally { Directory.Delete(bookDirectory, true); } } [Fact] public async Task GetMetadataAsync_WhenOpfIsMalformedXml_ShouldNotExposeAnException() { // Arrange string bookDirectory = CreateTempDirectory(); try { string bookPath = WriteBookWithOpf(bookDirectory, """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!).Metadata!.Title); } finally { Directory.Delete(bookDirectory, true); } } /// /// Creates the Calibre metadata provider by registering the plugin services and resolving the keyed metadata provider. /// /// The created Calibre metadata provider. private static IMetadataProvider CreateMetadataProvider() { ServiceCollection services = new(); new CalibrePlugin().RegisterServices(services); ServiceProvider serviceProvider = services.BuildServiceProvider(); return serviceProvider.GetKeyedService(CalibrePlugin.s_pluginId)!; } /// /// Writes an OPF file with the given content into the book directory, and returns the path of the book. /// /// The file system path of the directory the OPF file is written into. /// The content of the OPF file to write. /// The file system path of the book. 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; } /// /// Creates a unique temporary directory for the book. /// /// The file system path of the created temporary directory. private static string CreateTempDirectory() { string directoryPath = Path.Combine(Path.GetTempPath(), $"nemera-security-opf-{Guid.NewGuid():N}"); Directory.CreateDirectory(directoryPath); return directoryPath; } }