#region ========================================================================= USING ===================================================================================== using Microsoft.Extensions.DependencyInjection; using Nemera.Contracts.DTO.MediaLibrary.WrittenContentLibrary.BookLibrary.Reading; using Nemera.Infrastructure.Common.Models.DTO.Plugins; using Nemera.Infrastructure.Core.Plugins; using Nemera.Plugins.Contracts.Core.Plugins; using Nemera.Plugins.Contracts.Core.Reading; using Nemera.Plugins.Pdf.Fixtures.Core.Pdf; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; #endregion namespace Nemera.Infrastructure.IntegrationTests.Core.Plugins; /// /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class PluginLoaderTests { private static readonly IReadOnlyDictionary> s_emptyBundledPluginChecksums = new Dictionary>(); /// /// The unique identifier of the bundled PDF plugin used by the deployed plugin loading test. /// private static readonly Guid s_pdfPluginId = new("c2f9b8f0-5a4b-4e3d-8b2f-7e4a9c1d3e5f"); [Fact] public async Task LoadPlugins_WhenLoadingTheBundledPdfPlugin_ShouldRenderAPdfPage() { // Arrange string repositoryRoot = FindRepositoryRoot(); DirectoryInfo testOutputDirectory = new(AppContext.BaseDirectory); string configuration = testOutputDirectory.Parent?.Name ?? throw new InvalidOperationException("The test configuration could not be determined from the test output directory."); string targetFramework = testOutputDirectory.Name; string pluginsDirectory = Path.Combine(repositoryRoot, "bin", "api", configuration, targetFramework, "plugins"); Assert.True(Directory.Exists(pluginsDirectory), $"The deployed plugins directory '{pluginsDirectory}' does not exist. Build the solution before running this test so the bundled plugins are deployed."); using TemporaryPluginDirectory temporaryDirectory = new(); string pdfPath = Path.Combine(temporaryDirectory.Path, "minimal.pdf"); TestPdfFileFactory.CreateMinimalPdf(pdfPath); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(pluginsDirectory, services, s_emptyBundledPluginChecksums); using ServiceProvider serviceProvider = services.BuildServiceProvider(); IBookReader pdfReader = serviceProvider.GetRequiredKeyedService(s_pdfPluginId); string workingDirectory = Path.Combine(temporaryDirectory.Path, "work"); ReadingDocumentDto document = await pdfReader.OpenAsync(pdfPath, workingDirectory, shouldRenderPdfAsImages: false, CancellationToken.None); byte[] pageImage = await pdfReader.GetResourceAsync(pdfPath, workingDirectory, "page:1", CancellationToken.None); // Assert Assert.Empty(result.Errors); Assert.Empty(result.Warnings); Assert.Contains(result.Plugins, plugin => plugin.Id == s_pdfPluginId); Assert.NotEmpty(result.LoadedPlugins); Assert.Single(document.Spine); Assert.NotEmpty(pageImage); } [Fact] public void LoadPlugins_WhenDirectoryDoesNotExist_ShouldReturnNoPluginsAndNoErrors() { // Arrange string nonExistentDirectory = Path.Combine(Path.GetTempPath(), $"nemera-plugins-{Guid.NewGuid()}"); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(nonExistentDirectory, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); Assert.Empty(result.Errors); Assert.Empty(result.LoadedPlugins); } [Fact] public void LoadPlugins_WhenDirectoryContainsInvalidAssembly_ShouldRecordError() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); temporaryPluginDirectory.CreateFile("invalid.dll", "this is not a valid assembly"); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); PluginLoadErrorDto error = Assert.Single(result.Errors); Assert.Equal("invalid", error.AssemblyName); Assert.Contains("invalid.dll", error.ErrorMessage); } [Fact] public void LoadPlugins_WhenDirectoryContainsNativeLibrary_ShouldSkipItSilently() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); // A native library (like pdfium.dll) is a valid PE image starting with the DOS signature, but it is not a managed assembly. temporaryPluginDirectory.CreateFile("native.dll", "MZ\u0001\u0000\u0000\u0000garbage native library content"); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); Assert.Empty(result.Errors); Assert.Empty(result.LoadContexts); } [Fact] public void LoadPlugins_WhenDirectoryContainsAssemblyWithoutPluginDescriptors_ShouldReturnNoPluginsAndNoErrors() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); temporaryPluginDirectory.CopyDll(typeof(IPlugin).Assembly.Location); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); Assert.Empty(result.Errors); } [Fact] public void LoadPlugins_WhenDirectoryContainsValidPluginAssembly_ShouldLoadPluginAndRegisterItsServices() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert IPlugin loadedPlugin = Assert.Single(result.Plugins); Assert.Empty(result.Errors); // A plugin that is not Official is expected to come from an uploaded assembly without a dependency manifest, so the loader does not warn. Assert.Empty(result.Warnings); Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id); Assert.Equal("Test Plugin", loadedPlugin.Name); Assert.Contains(services, descriptor => (descriptor.ImplementationInstance as string) == "plugin-services-registered"); } [Fact] public void LoadPlugins_WhenDirectoryContainsValidPluginAssembly_ShouldRetainTheLoadContextOfThePlugin() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Single(result.Plugins); // A collectible load context is only kept alive by a direct reference to the context object itself, so the context of every loaded plugin is retained // for the lifetime of the host, keeping the plugin assemblies from being unloaded by the garbage collector. Assert.Single(result.LoadContexts); } [Fact] public void LoadPlugins_WhenPluginDependencyManifestIsInvalid_ShouldLoadPluginAndRecordWarning() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); temporaryPluginDirectory.CreateFile("Nemera.TestPlugin.deps.json", "{ this is not a valid dependency manifest"); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Single(result.Plugins); Assert.Empty(result.Errors); string warning = Assert.Single(result.Warnings); Assert.Contains("Nemera.TestPlugin.dll", warning); Assert.Contains("dependency manifest", warning); } [Fact] public void LoadPlugins_WhenOfficialPluginHasNoDependencyManifest_ShouldLoadPluginAndRecordWarning() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); string assemblyPath = GetTestPluginAssemblyPath(); temporaryPluginDirectory.CopyDll(assemblyPath); IReadOnlyDictionary> bundledPluginChecksums = CreateBundledPluginChecksums("Nemera.TestPlugin.dll", ComputeChecksum(assemblyPath)); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, bundledPluginChecksums); // Assert Assert.Single(result.Plugins); Assert.Empty(result.Errors); string warning = Assert.Single(result.Warnings); Assert.Contains("Nemera.TestPlugin.dll", warning); Assert.Contains("no dependency manifest", warning); } [Fact] public void LoadPlugins_WhenBundledPluginChecksumMatches_ShouldLoadPluginAndMarkItOfficial() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); string assemblyPath = GetTestPluginAssemblyPath(); temporaryPluginDirectory.CopyDll(assemblyPath); IReadOnlyDictionary> bundledPluginChecksums = CreateBundledPluginChecksums("Nemera.TestPlugin.dll", ComputeChecksum(assemblyPath)); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, bundledPluginChecksums); // Assert IPlugin loadedPlugin = Assert.Single(result.Plugins); Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id); Assert.Empty(result.Errors); LoadedPluginMetadataDto metadata = Assert.Single(result.LoadedPlugins); Assert.Equal("Nemera.TestPlugin.dll", metadata.AssemblyFileName); Assert.True(metadata.IsOfficial); } [Fact] public void LoadPlugins_WhenBundledPluginChecksumDoesNotMatch_ShouldLoadPluginWithoutMarkingItOfficial() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); IReadOnlyDictionary> bundledPluginChecksums = CreateBundledPluginChecksums("Nemera.TestPlugin.dll", new string('0', 64)); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, bundledPluginChecksums); // Assert Assert.Single(result.Plugins); Assert.Empty(result.Errors); LoadedPluginMetadataDto metadata = Assert.Single(result.LoadedPlugins); Assert.False(metadata.IsOfficial); } [Fact] public void LoadPlugins_WhenPluginIsNotInTheBundledManifest_ShouldLoadPluginWithoutMarkingItOfficial() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Single(result.Plugins); Assert.Empty(result.Errors); LoadedPluginMetadataDto metadata = Assert.Single(result.LoadedPlugins); Assert.False(metadata.IsOfficial); } [Fact] public void LoadPlugins_WhenBundledManifestListsMultipleChecksums_ShouldMarkTheMatchingOneOfficial() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); string assemblyPath = GetTestPluginAssemblyPath(); temporaryPluginDirectory.CopyDll(assemblyPath); IReadOnlyDictionary> bundledPluginChecksums = CreateBundledPluginChecksums("Nemera.TestPlugin.dll", new string('0', 64), ComputeChecksum(assemblyPath)); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, bundledPluginChecksums); // Assert Assert.Single(result.Plugins); Assert.Empty(result.Errors); LoadedPluginMetadataDto metadata = Assert.Single(result.LoadedPlugins); Assert.True(metadata.IsOfficial); } [Fact] public void LoadPlugins_WhenDirectoryContainsManagedDependencyAssemblyAlongsideAPlugin_ShouldSkipTheDependencyAndLoadOnlyThePlugin() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); temporaryPluginDirectory.CopyDll(GetTestPluginAssemblyPath()); // A plugin ships its managed dependencies into the plugins directory (like PdfPig.dll and SkiaSharp.dll next to the PDF plugin). A managed dependency is a valid // assembly that does not reference the plugin contracts, so it is not a plugin and must be skipped without reflecting over its types, which would otherwise surface // spurious load errors for a file that is not a plugin. temporaryPluginDirectory.CopyDll(GetDependencyAssemblyPath()); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert IPlugin loadedPlugin = Assert.Single(result.Plugins); Assert.Equal(Guid.Parse("7B5A3E5D-9B7F-4A1E-8D9C-2F3A4B5C6D7E"), loadedPlugin.Id); Assert.Equal("Test Plugin", loadedPlugin.Name); Assert.Empty(result.Errors); Assert.Single(result.LoadContexts); } [Fact] public void LoadPlugins_WhenDirectoryContainsFileShorterThanDosSignature_ShouldRecordInvalidAssemblyError() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); // A single-character file is not long enough to carry the two-byte DOS signature "MZ", so it is not a PE image. temporaryPluginDirectory.CreateFile("tiny.dll", "M"); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); PluginLoadErrorDto error = Assert.Single(result.Errors); Assert.Equal("tiny", error.AssemblyName); Assert.Contains("tiny.dll", error.ErrorMessage); } [Fact] public void LoadPlugins_WhenDirectoryContainsFileWithWrongDosSignature_ShouldRecordInvalidAssemblyError() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); // The file starts with the wrong DOS signature, so it is not a PE image at all. temporaryPluginDirectory.CreateFile("notpe.dll", "XY\u0000\u0000\u0000some content that is not a PE image"); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); PluginLoadErrorDto error = Assert.Single(result.Errors); Assert.Equal("notpe", error.AssemblyName); Assert.Contains("notpe.dll", error.ErrorMessage); } [Fact] public void LoadPlugins_WhenDirectoryContainsLockedNativeLibrary_ShouldNotThrowAndRecordError() { // Arrange using TemporaryPluginDirectory temporaryPluginDirectory = new(); string nativePath = temporaryPluginDirectory.CreateFileReturningPath("locked.dll", "MZ\u0000\u0000\u0000locked native library content"); using FileStream lockStream = new(nativePath, FileMode.Open, FileAccess.Read, FileShare.None); IServiceCollection services = new ServiceCollection(); // Act PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums); // Assert Assert.Empty(result.Plugins); // The file cannot be read to verify its PE signature, so it is reported as not loadable rather than crashing the loader. PluginLoadErrorDto error = Assert.Single(result.Errors); Assert.Equal("locked", error.AssemblyName); } /// /// Gets the path of the Nemera.TestPlugin assembly from the test output directory. /// The assembly is referenced by the test project but no type from it is used, so it is not loaded /// into the default load context, which is what makes the plugin loading pipeline testable. /// /// The path of the test plugin assembly. private static string GetTestPluginAssemblyPath() { return Path.Combine(AppContext.BaseDirectory, "Nemera.TestPlugin.dll"); } /// /// Gets the path of a managed dependency assembly from the test output directory, standing in for the managed dependencies /// a plugin ships next to itself (like PdfPig.dll and SkiaSharp.dll next to the PDF plugin). The Microsoft.AspNetCore.SignalR.Core /// assembly is used because it does not reference the plugin contracts assembly, and reflecting over its types inside a plugin load /// context throws, which reproduces the spurious load errors the loader used to record for dependency assemblies. /// /// The path of the managed dependency assembly. private static string GetDependencyAssemblyPath() { return Path.Combine(AppContext.BaseDirectory, "Microsoft.AspNetCore.SignalR.Core.dll"); } /// /// Creates a bundled plugin trust list containing one assembly with the provided checksums. /// /// The file name of the bundled plugin assembly. /// The checksums the assembly is allowed to have. /// The bundled plugin trust list. private static IReadOnlyDictionary> CreateBundledPluginChecksums(string assemblyFileName, params string[] checksums) { return new Dictionary>(StringComparer.OrdinalIgnoreCase) { [assemblyFileName] = new HashSet(checksums, StringComparer.OrdinalIgnoreCase) }; } /// /// Computes the SHA-256 checksum of the file at , in the hexadecimal form the bundled plugin trust manifest uses. /// /// The path of the file to hash. /// The uppercase hexadecimal SHA-256 checksum. private static string ComputeChecksum(string path) { using (FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read)) return Convert.ToHexString(SHA256.HashData(fileStream)); } /// /// Locates the repository root from the test output directory. /// /// The absolute path of the repository root. private static string FindRepositoryRoot() { DirectoryInfo? directory = new(AppContext.BaseDirectory); while (directory is not null) { if (File.Exists(Path.Combine(directory.FullName, "src", "Nemera.slnx"))) return directory.FullName; directory = directory.Parent; } throw new InvalidOperationException("The repository root could not be located from the test output directory."); } /// /// Test helper managing a temporary plugins directory, deleted when the test finishes. /// private sealed class TemporaryPluginDirectory : IDisposable { private bool _disposed; public TemporaryPluginDirectory() { Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"nemera-plugin-loader-{Guid.NewGuid()}"); Directory.CreateDirectory(Path); } public string Path { get; } public void CreateFile(string fileName, string content) { File.WriteAllText(System.IO.Path.Combine(Path, fileName), content); } public string CreateFileReturningPath(string fileName, string content) { string filePath = System.IO.Path.Combine(Path, fileName); File.WriteAllText(filePath, content); return filePath; } public void CopyDll(string sourceDllPath) { File.Copy(sourceDllPath, System.IO.Path.Combine(Path, System.IO.Path.GetFileName(sourceDllPath))); } public void Dispose() { if (!_disposed) { try { Directory.Delete(Path, recursive: true); } catch (IOException) { // Best effort cleanup of the temporary plugins directory. } catch (UnauthorizedAccessException) { // The plugin assemblies are still locked by their load contexts, best effort cleanup only. } _disposed = true; } } } }