mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds bundled plugin trust and cross-platform native deployment
- embeds the append-only historical and deny trust lists in the API and marks matching bundled plugins as Official without blocking loading - builds and records the current plugin manifest only for official release builds - deploys the PDF native libraries for the supported Linux, macOS and Windows runtimes from the plugin dependency manifest - records release hashes by appending only missing entries to master's manifest and rejects any diff that removes a line - documents the release flow, the supported runtimes and the plugin installer limits
This commit is contained in:
1 parent
3fb8912c7f
commit
b30cbd6b9e
114 files changed
+2708
-243
No files matched your search
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
+5
-2
@@ -29,6 +29,7 @@ public class PluginResponseFixture
|
||||
/// <param name="loadStatus">Optional. The load status of the plugin.</param>
|
||||
/// <param name="loadError">Optional. The error message when the plugin failed to load.</param>
|
||||
/// <param name="settings">Optional. The settings of the plugin.</param>
|
||||
/// <param name="isOfficial">Optional. Whether the plugin matches a trusted bundled plugin binary.</param>
|
||||
/// <returns>The created <see cref="PluginResponse"/>.</returns>
|
||||
public PluginResponse Create(
|
||||
Guid? id = null,
|
||||
@@ -38,7 +39,8 @@ public class PluginResponseFixture
|
||||
string? description = null,
|
||||
PluginLoadStatus? loadStatus = null,
|
||||
string? loadError = null,
|
||||
IReadOnlyDictionary<string, string>? settings = null)
|
||||
IReadOnlyDictionary<string, string>? settings = null,
|
||||
bool isOfficial = false)
|
||||
{
|
||||
return new PluginResponse(
|
||||
id ?? Guid.NewGuid(),
|
||||
@@ -51,7 +53,8 @@ public class PluginResponseFixture
|
||||
settings ?? new Dictionary<string, string>
|
||||
{
|
||||
[_faker.Lorem.Word()] = _faker.Lorem.Word()
|
||||
}
|
||||
},
|
||||
isOfficial
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
-1
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
-1
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
-1
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
-1
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
-1
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
-1
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
@@ -18,7 +17,6 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\..\plugins\Nemera.Plugins.Pdf\Nemera.Plugins.Pdf.csproj" />
|
||||
<ProjectReference Include="..\..\..\src\Nemera.Plugins.Contracts\Nemera.Plugins.Contracts.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Nemera.Contracts.Fixtures\Nemera.Contracts.Fixtures.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
#endregion
|
||||
|
||||
namespace Nemera.Presentation.Api.Fixtures.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for computing the SHA-256 checksums of bundled plugin files.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BundledPluginFileHashFixture
|
||||
{
|
||||
/// <summary>
|
||||
/// Computes the SHA-256 checksum of the file at <paramref name="path"/>, in the uppercase hexadecimal form the trust manifest uses.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to hash.</param>
|
||||
/// <returns>The uppercase hexadecimal SHA-256 checksum.</returns>
|
||||
public string Create(string path)
|
||||
{
|
||||
// Convert.ToHexString returns uppercase hexadecimal, which is the form the trust manifest uses.
|
||||
using (FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
return Convert.ToHexString(SHA256.HashData(fileStream));
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
+4
-2
@@ -26,8 +26,9 @@ public class PluginDtoFixture
|
||||
/// <param name="author">Optional author of the plugin.</param>
|
||||
/// <param name="version">Optional version of the plugin.</param>
|
||||
/// <param name="loadStatus">Optional load status of the plugin.</param>
|
||||
/// <param name="isOfficial">Optional. Whether the plugin matches a trusted bundled plugin binary.</param>
|
||||
/// <returns>A configured <see cref="PluginDto"/> instance.</returns>
|
||||
public PluginDto Create(Guid? id = null, string? name = null, string? author = null, string? version = null, PluginLoadStatus? loadStatus = null)
|
||||
public PluginDto Create(Guid? id = null, string? name = null, string? author = null, string? version = null, PluginLoadStatus? loadStatus = null, bool isOfficial = false)
|
||||
{
|
||||
return new PluginDto
|
||||
{
|
||||
@@ -38,7 +39,8 @@ public class PluginDtoFixture
|
||||
Description = _faker.Lorem.Sentence(),
|
||||
LoadStatus = loadStatus ?? PluginLoadStatus.Loaded,
|
||||
LoadError = null,
|
||||
Settings = null
|
||||
Settings = null,
|
||||
IsOfficial = isOfficial
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\web\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<IsPackable>false</IsPackable>
|
||||
<IsTestProject>false</IsTestProject>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<Project>
|
||||
<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)..'))" />
|
||||
|
||||
<!-- Test binaries stay under the repository bin directory when a test project is built outside the solution. Each project keeps its own folder so manifests and dependencies do not collide. -->
|
||||
<PropertyGroup>
|
||||
<BaseOutputPath>$(RepoRoot)bin/tests/$(MSBuildProjectName)/</BaseOutputPath>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
+3
-3
@@ -19,7 +19,7 @@ public class PluginLoadContextTests
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
|
||||
PluginLoadContext sut = new(Path.Combine(temporaryPluginDirectory.Path, "Plugin.dll"), "test-context");
|
||||
|
||||
// Act
|
||||
Assembly result = sut.LoadFromAssemblyName(typeof(object).Assembly.GetName());
|
||||
@@ -35,7 +35,7 @@ public class PluginLoadContextTests
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
string destinationPath = temporaryPluginDirectory.CopyDll(Path.Combine(AppContext.BaseDirectory, "Nemera.TestPlugin.dll"), "PluginLocalDependency.dll");
|
||||
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
|
||||
PluginLoadContext sut = new(destinationPath, "test-context");
|
||||
MethodInfo loadMethod = typeof(PluginLoadContext).GetMethod("Load", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
|
||||
// Act
|
||||
@@ -52,7 +52,7 @@ public class PluginLoadContextTests
|
||||
{
|
||||
// Arrange
|
||||
using TemporaryPluginDirectory temporaryPluginDirectory = new();
|
||||
PluginLoadContext sut = new(temporaryPluginDirectory.Path, "test-context");
|
||||
PluginLoadContext sut = new(Path.Combine(temporaryPluginDirectory.Path, "Missing.dll"), "test-context");
|
||||
|
||||
// Act
|
||||
Action act = () => sut.LoadFromAssemblyName(new AssemblyName($"Definitely.Not.Resolvable.{Guid.NewGuid()}"));
|
||||
|
||||
+227
-13
@@ -1,12 +1,18 @@
|
||||
#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 Microsoft.Extensions.DependencyInjection;
|
||||
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.Linq;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Nemera.Infrastructure.IntegrationTests.Core.Plugins;
|
||||
@@ -17,6 +23,46 @@ namespace Nemera.Infrastructure.IntegrationTests.Core.Plugins;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginLoaderTests
|
||||
{
|
||||
private static readonly IReadOnlyDictionary<string, IReadOnlySet<string>> s_emptyBundledPluginChecksums = new Dictionary<string, IReadOnlySet<string>>();
|
||||
|
||||
/// <summary>
|
||||
/// The unique identifier of the bundled PDF plugin used by the deployed plugin loading test.
|
||||
/// </summary>
|
||||
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<IBookReader>(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()
|
||||
{
|
||||
@@ -25,11 +71,12 @@ public class PluginLoaderTests
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(nonExistentDirectory, services);
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(nonExistentDirectory, services, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
Assert.Empty(result.Errors);
|
||||
Assert.Empty(result.LoadedPlugins);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -41,7 +88,7 @@ public class PluginLoaderTests
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
@@ -60,7 +107,7 @@ public class PluginLoaderTests
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
@@ -77,7 +124,7 @@ public class PluginLoaderTests
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
@@ -93,14 +140,16 @@ public class PluginLoaderTests
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
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");
|
||||
Assert.Contains(services, descriptor => (descriptor.ImplementationInstance as string) == "plugin-services-registered");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -112,7 +161,7 @@ public class PluginLoaderTests
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
Assert.Single(result.Plugins);
|
||||
@@ -121,6 +170,130 @@ public class PluginLoaderTests
|
||||
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<string, IReadOnlySet<string>> 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<string, IReadOnlySet<string>> 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<string, IReadOnlySet<string>> 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<string, IReadOnlySet<string>> 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()
|
||||
{
|
||||
@@ -134,7 +307,7 @@ public class PluginLoaderTests
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
IPlugin loadedPlugin = Assert.Single(result.Plugins);
|
||||
@@ -154,7 +327,7 @@ public class PluginLoaderTests
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
@@ -173,7 +346,7 @@ public class PluginLoaderTests
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
@@ -192,7 +365,7 @@ public class PluginLoaderTests
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
|
||||
// Act
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services);
|
||||
PluginLoadResultDto result = PluginLoader.LoadPlugins(temporaryPluginDirectory.Path, services, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result.Plugins);
|
||||
@@ -224,6 +397,47 @@ public class PluginLoaderTests
|
||||
return Path.Combine(AppContext.BaseDirectory, "Microsoft.AspNetCore.SignalR.Core.dll");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a bundled plugin trust list containing one assembly with the provided checksums.
|
||||
/// </summary>
|
||||
/// <param name="assemblyFileName">The file name of the bundled plugin assembly.</param>
|
||||
/// <param name="checksums">The checksums the assembly is allowed to have.</param>
|
||||
/// <returns>The bundled plugin trust list.</returns>
|
||||
private static IReadOnlyDictionary<string, IReadOnlySet<string>> CreateBundledPluginChecksums(string assemblyFileName, params string[] checksums)
|
||||
{
|
||||
return new Dictionary<string, IReadOnlySet<string>>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[assemblyFileName] = new HashSet<string>(checksums, StringComparer.OrdinalIgnoreCase)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Computes the SHA-256 checksum of the file at <paramref name="path"/>, in the hexadecimal form the bundled plugin trust manifest uses.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the file to hash.</param>
|
||||
/// <returns>The uppercase hexadecimal SHA-256 checksum.</returns>
|
||||
private static string ComputeChecksum(string path)
|
||||
{
|
||||
using (FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
return Convert.ToHexString(SHA256.HashData(fileStream));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locates the repository root from the test output directory.
|
||||
/// </summary>
|
||||
/// <returns>The absolute path of the repository root.</returns>
|
||||
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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Test helper managing a temporary plugins directory, deleted when the test finishes.
|
||||
/// </summary>
|
||||
|
||||
+1
@@ -44,6 +44,7 @@
|
||||
<ProjectReference Include="..\..\Common\Nemera.Application.Fixtures\Nemera.Application.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Nemera.Contracts.Fixtures\Nemera.Contracts.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Nemera.Infrastructure.Fixtures\Nemera.Infrastructure.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Nemera.Plugins.Pdf.Fixtures\Nemera.Plugins.Pdf.Fixtures.csproj" />
|
||||
<ProjectReference Include="..\..\Common\Nemera.TestPlugin\Nemera.TestPlugin.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
#endregion
|
||||
|
||||
namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Locates the files and directories used by the bundled plugin manifest tests.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The tests run from a configuration and target framework folder under bin/tests, so the repository root is found by walking up to the solution instead of hardcoding a machine-specific path.
|
||||
/// </remarks>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class BundledPluginManifestTestPaths
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of the directory that holds the build scripts.
|
||||
/// </summary>
|
||||
public const string BUILD_DIRECTORY_NAME = "build";
|
||||
|
||||
/// <summary>
|
||||
/// The name of the directory that holds the build outputs.
|
||||
/// </summary>
|
||||
public const string BIN_DIRECTORY_NAME = "bin";
|
||||
|
||||
/// <summary>
|
||||
/// The name of the directory that holds the solution.
|
||||
/// </summary>
|
||||
public const string SOLUTION_DIRECTORY_NAME = "src";
|
||||
|
||||
/// <summary>
|
||||
/// The file name of the solution.
|
||||
/// </summary>
|
||||
public const string SOLUTION_FILE_NAME = "Nemera.slnx";
|
||||
|
||||
/// <summary>
|
||||
/// The name of the append-only bundled plugin trust manifest.
|
||||
/// </summary>
|
||||
public const string BUNDLED_PLUGINS_MANIFEST_FILE_NAME = "BundledPlugins.manifest";
|
||||
|
||||
/// <summary>
|
||||
/// The name of the bundled plugin revocation manifest.
|
||||
/// </summary>
|
||||
public const string BUNDLED_PLUGINS_DENY_MANIFEST_FILE_NAME = "BundledPlugins.deny.manifest";
|
||||
|
||||
/// <summary>
|
||||
/// The name of the bundled plugin release catalog.
|
||||
/// </summary>
|
||||
public const string BUNDLED_PLUGINS_PROPS_FILE_NAME = "BundledPlugins.props";
|
||||
|
||||
/// <summary>
|
||||
/// The name of the directory that holds the plugin projects.
|
||||
/// </summary>
|
||||
public const string PLUGINS_PROJECT_DIRECTORY_NAME = "plugins";
|
||||
|
||||
/// <summary>
|
||||
/// The name of the API output directory under the repository bin directory.
|
||||
/// </summary>
|
||||
public const string API_OUTPUT_DIRECTORY_NAME = "api";
|
||||
|
||||
/// <summary>
|
||||
/// The name of the directory that holds the deployed plugin assemblies.
|
||||
/// </summary>
|
||||
public const string PLUGINS_DIRECTORY_NAME = "plugins";
|
||||
|
||||
/// <summary>
|
||||
/// The file name of the published API assembly.
|
||||
/// </summary>
|
||||
public const string PUBLISHED_API_ASSEMBLY_FILE_NAME = "Nemera.Presentation.Api.dll";
|
||||
|
||||
/// <summary>
|
||||
/// The search pattern of the bundled plugin assemblies.
|
||||
/// </summary>
|
||||
public const string PLUGIN_ASSEMBLY_SEARCH_PATTERN = "Nemera.Plugins.*.dll";
|
||||
|
||||
/// <summary>
|
||||
/// The search pattern of the plugin project files.
|
||||
/// </summary>
|
||||
public const string PLUGIN_PROJECT_SEARCH_PATTERN = "*.csproj";
|
||||
|
||||
/// <summary>
|
||||
/// The extension of the bundled plugin assemblies.
|
||||
/// </summary>
|
||||
public const string PLUGIN_ASSEMBLY_EXTENSION = ".dll";
|
||||
|
||||
/// <summary>
|
||||
/// Locates the repository root from the test output directory.
|
||||
/// </summary>
|
||||
/// <returns>The absolute path of the repository root.</returns>
|
||||
public static string GetRepositoryRoot()
|
||||
{
|
||||
// Walk up from the test output directory until the solution file is found. This works regardless of how many folders the output is nested under bin.
|
||||
DirectoryInfo? directory = new(AppContext.BaseDirectory);
|
||||
while (directory is not null)
|
||||
{
|
||||
if (File.Exists(Path.Combine(directory.FullName, SOLUTION_DIRECTORY_NAME, SOLUTION_FILE_NAME)))
|
||||
return directory.FullName;
|
||||
directory = directory.Parent;
|
||||
}
|
||||
throw new InvalidOperationException("The repository root could not be located from the test output directory.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locates the append-only bundled plugin trust manifest.
|
||||
/// </summary>
|
||||
/// <param name="repositoryRoot">The absolute path of the repository root.</param>
|
||||
/// <returns>The absolute path of the trust manifest.</returns>
|
||||
public static string GetBundledPluginsManifestPath(string repositoryRoot)
|
||||
{
|
||||
return Path.Combine(repositoryRoot, BUILD_DIRECTORY_NAME, BUNDLED_PLUGINS_MANIFEST_FILE_NAME);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locates the bundled plugin revocation manifest.
|
||||
/// </summary>
|
||||
/// <param name="repositoryRoot">The absolute path of the repository root.</param>
|
||||
/// <returns>The absolute path of the revocation manifest.</returns>
|
||||
public static string GetBundledPluginsDenyManifestPath(string repositoryRoot)
|
||||
{
|
||||
return Path.Combine(repositoryRoot, BUILD_DIRECTORY_NAME, BUNDLED_PLUGINS_DENY_MANIFEST_FILE_NAME);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locates the bundled plugin release catalog.
|
||||
/// </summary>
|
||||
/// <param name="repositoryRoot">The absolute path of the repository root.</param>
|
||||
/// <returns>The absolute path of the release catalog.</returns>
|
||||
public static string GetBundledPluginsPropsPath(string repositoryRoot)
|
||||
{
|
||||
return Path.Combine(repositoryRoot, BUILD_DIRECTORY_NAME, BUNDLED_PLUGINS_PROPS_FILE_NAME);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locates the solution file.
|
||||
/// </summary>
|
||||
/// <param name="repositoryRoot">The absolute path of the repository root.</param>
|
||||
/// <returns>The absolute path of the solution file.</returns>
|
||||
public static string GetSolutionPath(string repositoryRoot)
|
||||
{
|
||||
return Path.Combine(repositoryRoot, SOLUTION_DIRECTORY_NAME, SOLUTION_FILE_NAME);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locates the directory that holds the plugin projects.
|
||||
/// </summary>
|
||||
/// <param name="repositoryRoot">The absolute path of the repository root.</param>
|
||||
/// <returns>The absolute path of the plugin project directory.</returns>
|
||||
public static string GetPluginsProjectDirectory(string repositoryRoot)
|
||||
{
|
||||
return Path.Combine(repositoryRoot, PLUGINS_PROJECT_DIRECTORY_NAME);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locates the plugins directory of the API build output for the current test configuration.
|
||||
/// </summary>
|
||||
/// <param name="repositoryRoot">The absolute path of the repository root.</param>
|
||||
/// <returns>The absolute path of the deployed plugins directory, whether or not it exists.</returns>
|
||||
public static string GetDeployedPluginsDirectory(string repositoryRoot)
|
||||
{
|
||||
// The test output folder is bin/tests/<project>/<configuration>/<target-framework>, so its parent names the configuration
|
||||
// and its own name is the target framework. The API output mirrors that layout under bin/api.
|
||||
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;
|
||||
return Path.Combine(repositoryRoot, BIN_DIRECTORY_NAME, API_OUTPUT_DIRECTORY_NAME, configuration, targetFramework, PLUGINS_DIRECTORY_NAME);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locates the published API assembly in the publish output directory.
|
||||
/// </summary>
|
||||
/// <param name="publishDirectory">The absolute path of the publish output directory.</param>
|
||||
/// <returns>The absolute path of the published API assembly.</returns>
|
||||
public static string GetPublishedApiAssemblyPath(string publishDirectory)
|
||||
{
|
||||
return Path.Combine(publishDirectory, PUBLISHED_API_ASSEMBLY_FILE_NAME);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Locates the published plugins directory in the publish output directory.
|
||||
/// </summary>
|
||||
/// <param name="publishDirectory">The absolute path of the publish output directory.</param>
|
||||
/// <returns>The absolute path of the published plugins directory.</returns>
|
||||
public static string GetPublishedPluginsDirectory(string publishDirectory)
|
||||
{
|
||||
return Path.Combine(publishDirectory, PLUGINS_DIRECTORY_NAME);
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using Xunit;
|
||||
#endregion
|
||||
|
||||
namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test that only runs when the API assembly was produced by an official release build and the deployed bundled plugins are present.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class DeployedBundledPluginsFactAttribute : FactAttribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the reason to skip the test. If set, the test will be skipped instead of executed.
|
||||
/// </summary>
|
||||
public override string Skip
|
||||
{
|
||||
get
|
||||
{
|
||||
// xUnit evaluates Skip during discovery. Missing deployed plugins mean the solution was not built, which is normal locally,
|
||||
// so the test is skipped with a reason instead of failing.
|
||||
if (!OfficialReleaseBuildDetector.IsOfficialReleaseBuild())
|
||||
return "The API assembly was not produced by an official release build.";
|
||||
try
|
||||
{
|
||||
string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot();
|
||||
string pluginsDirectory = BundledPluginManifestTestPaths.GetDeployedPluginsDirectory(repositoryRoot);
|
||||
// The deployed folder is produced by the solution build. If it is missing or empty there is no artifact to verify,
|
||||
// so the test is skipped and the reason points at the path that was expected.
|
||||
if (!Directory.Exists(pluginsDirectory))
|
||||
return $"The deployed bundled plugins directory '{pluginsDirectory}' does not exist.";
|
||||
if (!Directory.EnumerateFiles(pluginsDirectory, BundledPluginManifestTestPaths.PLUGIN_ASSEMBLY_SEARCH_PATTERN).Any())
|
||||
return $"The deployed bundled plugins directory '{pluginsDirectory}' does not contain any bundled plugin assemblies.";
|
||||
return string.Empty;
|
||||
}
|
||||
catch (InvalidOperationException exception)
|
||||
{
|
||||
return exception.Message;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Xunit;
|
||||
#endregion
|
||||
|
||||
namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test that only runs when the named environment variable is set.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class EnvironmentVariableFactAttribute : FactAttribute
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of the environment variable that must be set for the test to run.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The name is stored because Skip is evaluated later, during test discovery.
|
||||
/// </remarks>
|
||||
private readonly string _environmentVariableName;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EnvironmentVariableFactAttribute"/> class.
|
||||
/// </summary>
|
||||
/// <param name="environmentVariableName">The name of the environment variable that must be set for the test to run.</param>
|
||||
public EnvironmentVariableFactAttribute(string environmentVariableName)
|
||||
{
|
||||
_environmentVariableName = environmentVariableName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the reason to skip the test. If set, the test will be skipped instead of executed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The published-artifact verification is opt-in: build/build.proj sets the variable only when it checks a publish output. Without it, the test would inspect a directory that does not exist, so it is skipped with a reason instead.
|
||||
/// </remarks>
|
||||
public override string Skip => string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(_environmentVariableName))
|
||||
? $"The environment variable '{_environmentVariableName}' is not set."
|
||||
: string.Empty;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Nemera.Presentation.Api;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
#endregion
|
||||
|
||||
namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the API assembly was produced by an official release build.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class OfficialReleaseBuildDetector
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether the API assembly was produced by an official release build.
|
||||
/// </summary>
|
||||
/// <returns><see langword="true"/> when the assembly carries the official release marker, <see langword="false"/> otherwise.</returns>
|
||||
public static bool IsOfficialReleaseBuild()
|
||||
{
|
||||
// The marker is injected by OfficialReleaseBuildAssemblyInfo.cs when the official build defines OFFICIAL_RELEASE_BUILD.
|
||||
// The tests inspect Program's assembly rather than their own, because the test assembly is not the shipped API assembly.
|
||||
return typeof(Program).Assembly
|
||||
.GetCustomAttributes<AssemblyMetadataAttribute>()
|
||||
.Any(attribute => attribute.Key == "OfficialReleaseBuild" && attribute.Value == "true");
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using Xunit;
|
||||
#endregion
|
||||
|
||||
namespace Nemera.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
|
||||
/// <summary>
|
||||
/// Marks a test that only runs when the API assembly was produced by an official release build.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
[ExcludeFromCodeCoverage]
|
||||
public sealed class OfficialReleaseFactAttribute : FactAttribute
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the reason to skip the test. If set, the test will be skipped instead of executed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// xUnit evaluates Skip during test discovery, so the attribute decides at runtime whether the test runs. A normal test run skips official-only tests instead of failing them.
|
||||
/// </remarks>
|
||||
public override string Skip => OfficialReleaseBuildDetector.IsOfficialReleaseBuild()
|
||||
? string.Empty
|
||||
: "The API assembly was not produced by an official release build.";
|
||||
}
|
||||
+10
-2
@@ -1,14 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Nemera.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Nemera.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Nemera.DataAccess.Core.UoW;
|
||||
using Nemera.Domain.SharedKernel.Common.Enums.Plugins;
|
||||
using Nemera.Presentation.Api.Core.Endpoints.Plugins.GetPlugins;
|
||||
using Nemera.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Json;
|
||||
@@ -66,9 +67,16 @@ public class GetPluginsEndpointTests : IClassFixture<AuthenticatedNemeraApiFacto
|
||||
// Assert
|
||||
response.EnsureSuccessStatusCode();
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
List<Nemera.Contracts.Responses.Plugins.PluginResponse>? plugins = await response.Content.ReadFromJsonAsync<List<Nemera.Contracts.Responses.Plugins.PluginResponse>>(_jsonOptions);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
List<Nemera.Contracts.Responses.Plugins.PluginResponse>? plugins = JsonSerializer.Deserialize<List<Nemera.Contracts.Responses.Plugins.PluginResponse>>(content, _jsonOptions);
|
||||
Assert.NotNull(plugins);
|
||||
Assert.Contains(plugins!, plugin => plugin.Id == pluginId && plugin.Name == "Test Plugin");
|
||||
using (JsonDocument document = JsonDocument.Parse(content))
|
||||
{
|
||||
JsonElement seededPlugin = document.RootElement.EnumerateArray().Single(element => element.GetProperty("id").GetGuid() == pluginId);
|
||||
Assert.True(seededPlugin.TryGetProperty("isOfficial", out JsonElement isOfficial));
|
||||
Assert.False(isOfficial.GetBoolean());
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Nemera.Presentation.Api.Core.Plugins;
|
||||
using Nemera.Presentation.Api.Fixtures.Core.Plugins;
|
||||
using Nemera.Presentation.Api.IntegrationTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.Loader;
|
||||
using System.Xml.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Nemera.Presentation.Api.IntegrationTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="BundledPluginManifestReader"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BundledPluginManifestReaderTests
|
||||
{
|
||||
/// <summary>
|
||||
/// The resource name of the append-only trust list of previously released bundled plugin binaries.
|
||||
/// </summary>
|
||||
private const string HISTORICAL_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.historical.manifest";
|
||||
|
||||
/// <summary>
|
||||
/// The resource name of the trust list generated for the current build's bundled plugin binaries.
|
||||
/// </summary>
|
||||
private const string CURRENT_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.current.manifest";
|
||||
|
||||
/// <summary>
|
||||
/// The resource name of the list of bundled plugin checksums that are no longer trusted.
|
||||
/// </summary>
|
||||
private const string DENY_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.deny.manifest";
|
||||
|
||||
/// <summary>
|
||||
/// The environment variable that points the published artifact verification at the publish output directory.
|
||||
/// </summary>
|
||||
private const string PUBLISH_DIRECTORY_ENVIRONMENT_VARIABLE = "NEMERA_API_PUBLISH_DIRECTORY";
|
||||
|
||||
/// <summary>
|
||||
/// The fixture that computes the SHA-256 checksums of the bundled plugin files.
|
||||
/// </summary>
|
||||
private readonly BundledPluginFileHashFixture _bundledPluginFileHashFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void HistoricalManifest_WhenBuilt_ShouldBeEmbeddedUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot();
|
||||
string sourceManifestPath = BundledPluginManifestTestPaths.GetBundledPluginsManifestPath(repositoryRoot);
|
||||
string sourceManifest = File.ReadAllText(sourceManifestPath);
|
||||
string embeddedManifest = ReadManifestResource(HISTORICAL_MANIFEST_RESOURCE_NAME);
|
||||
|
||||
// Act
|
||||
// The checked-in file and the embedded copy can use different line endings, so normalize both before comparing.
|
||||
string normalizedSourceManifest = NormalizeLineEndings(sourceManifest);
|
||||
string normalizedEmbeddedManifest = NormalizeLineEndings(embeddedManifest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(normalizedSourceManifest, normalizedEmbeddedManifest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DenyManifest_WhenBuilt_ShouldBeEmbeddedUnchanged()
|
||||
{
|
||||
// Arrange
|
||||
string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot();
|
||||
string sourceManifestPath = BundledPluginManifestTestPaths.GetBundledPluginsDenyManifestPath(repositoryRoot);
|
||||
string sourceManifest = File.ReadAllText(sourceManifestPath);
|
||||
string embeddedManifest = ReadManifestResource(DENY_MANIFEST_RESOURCE_NAME);
|
||||
|
||||
// Act
|
||||
// The checked-in file and the embedded copy can use different line endings, so normalize both before comparing.
|
||||
string normalizedSourceManifest = NormalizeLineEndings(sourceManifest);
|
||||
string normalizedEmbeddedManifest = NormalizeLineEndings(embeddedManifest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(normalizedSourceManifest, normalizedEmbeddedManifest);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HistoricalManifest_WhenParsed_ShouldContainEveryNonCommentEntry()
|
||||
{
|
||||
// Arrange
|
||||
string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot();
|
||||
string sourceManifestPath = BundledPluginManifestTestPaths.GetBundledPluginsManifestPath(repositoryRoot);
|
||||
string sourceManifest = File.ReadAllText(sourceManifestPath);
|
||||
|
||||
// Act
|
||||
using (FileStream manifestStream = new(sourceManifestPath, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> actualChecksums = BundledPluginManifestReader.ReadExpectedChecksums(manifestStream);
|
||||
|
||||
// Assert
|
||||
// Every non-comment, non-blank line must produce one checksum; the count catches silently skipped entries.
|
||||
Assert.Equal(CountManifestEntries(sourceManifest), CountChecksums(actualChecksums));
|
||||
Assert.All(actualChecksums, entry =>
|
||||
{
|
||||
Assert.False(string.IsNullOrWhiteSpace(entry.Key));
|
||||
Assert.NotEmpty(entry.Value);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DenyManifest_WhenParsedWithTheSameEntriesTrusted_ShouldRemoveEveryCheckedInEntry()
|
||||
{
|
||||
// Arrange
|
||||
string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot();
|
||||
string sourceManifestPath = BundledPluginManifestTestPaths.GetBundledPluginsDenyManifestPath(repositoryRoot);
|
||||
string sourceManifest = File.ReadAllText(sourceManifestPath);
|
||||
|
||||
// Act
|
||||
// Using the deny list as the trust list proves that every deny entry revokes a matching trusted entry.
|
||||
using (FileStream trustStream = new(sourceManifestPath, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> trustedChecksums = BundledPluginManifestReader.ReadExpectedChecksums(trustStream);
|
||||
using (FileStream historicalStream = new(sourceManifestPath, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
using (FileStream denyStream = new(sourceManifestPath, FileMode.Open, FileAccess.Read, FileShare.Read))
|
||||
{
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> remainingChecksums = BundledPluginManifestReader.ReadExpectedChecksums(historicalStream, null, denyStream);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(CountManifestEntries(sourceManifest), CountChecksums(trustedChecksums));
|
||||
Assert.Empty(remainingChecksums);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BundledPluginCatalog_WhenCheckedIn_ShouldMatchTheSolutionAndPluginProjects()
|
||||
{
|
||||
// Arrange
|
||||
string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot();
|
||||
string solutionPath = BundledPluginManifestTestPaths.GetSolutionPath(repositoryRoot);
|
||||
string catalogPath = BundledPluginManifestTestPaths.GetBundledPluginsPropsPath(repositoryRoot);
|
||||
string pluginsDirectory = BundledPluginManifestTestPaths.GetPluginsProjectDirectory(repositoryRoot);
|
||||
// The solution, the release catalog and the project folders on disk must agree. Drift here means a plugin would be built or published inconsistently.
|
||||
string[] solutionPluginProjects = ReadSolutionPluginProjects(solutionPath);
|
||||
string[] catalogPluginProjects = ReadCatalogPluginProjects(catalogPath);
|
||||
string[] diskPluginProjects = [.. Directory.EnumerateFiles(pluginsDirectory, BundledPluginManifestTestPaths.PLUGIN_PROJECT_SEARCH_PATTERN, SearchOption.AllDirectories)];
|
||||
|
||||
// Act
|
||||
string[] normalizedSolutionProjects = NormalizeAndSort(solutionPluginProjects);
|
||||
string[] normalizedCatalogProjects = NormalizeAndSort(catalogPluginProjects);
|
||||
string[] normalizedDiskProjects = NormalizeAndSort(diskPluginProjects);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(normalizedSolutionProjects, normalizedDiskProjects, StringComparer.OrdinalIgnoreCase);
|
||||
Assert.Equal(normalizedCatalogProjects, normalizedDiskProjects, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CurrentManifest_WhenBuilt_ShouldBePresentOnlyForOfficialReleaseBuilds()
|
||||
{
|
||||
// Act
|
||||
// A normal build must not embed a current manifest, otherwise it could certify its own locally built plugins.
|
||||
bool hasCurrentManifest = HasManifestResource(CURRENT_MANIFEST_RESOURCE_NAME);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(OfficialReleaseBuildDetector.IsOfficialReleaseBuild(), hasCurrentManifest);
|
||||
}
|
||||
|
||||
[OfficialReleaseFact]
|
||||
public void CurrentManifest_WhenOfficialReleaseBuild_ShouldContainEveryBundledPluginProject()
|
||||
{
|
||||
// Arrange
|
||||
string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot();
|
||||
string pluginsProjectDirectory = BundledPluginManifestTestPaths.GetPluginsProjectDirectory(repositoryRoot);
|
||||
// Every plugin project under plugins must contribute exactly one assembly hash to the current manifest.
|
||||
string[] bundledPluginAssemblyNames = [.. Directory.EnumerateFiles(pluginsProjectDirectory, BundledPluginManifestTestPaths.PLUGIN_PROJECT_SEARCH_PATTERN, SearchOption.AllDirectories)
|
||||
.Select(projectPath => Path.GetFileNameWithoutExtension(projectPath) + BundledPluginManifestTestPaths.PLUGIN_ASSEMBLY_EXTENSION)];
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> currentManifestEntries = ReadCurrentManifest();
|
||||
|
||||
// Assert
|
||||
Assert.NotEmpty(bundledPluginAssemblyNames);
|
||||
Assert.Equal(bundledPluginAssemblyNames.Length, currentManifestEntries.Count);
|
||||
Assert.All(currentManifestEntries, entry => Assert.Single(entry.Value));
|
||||
foreach (string assemblyName in bundledPluginAssemblyNames)
|
||||
Assert.Contains(assemblyName, currentManifestEntries.Keys, StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[DeployedBundledPluginsFact]
|
||||
public void CurrentManifest_WhenOfficialReleaseBuild_ShouldMatchTheDeployedPluginAssemblies()
|
||||
{
|
||||
// Arrange
|
||||
string repositoryRoot = BundledPluginManifestTestPaths.GetRepositoryRoot();
|
||||
string pluginsDirectory = BundledPluginManifestTestPaths.GetDeployedPluginsDirectory(repositoryRoot);
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> currentManifestEntries = ReadCurrentManifest();
|
||||
|
||||
// Assert
|
||||
// The embedded hashes must describe the binaries that were actually deployed, not merely the ones that were built.
|
||||
foreach (KeyValuePair<string, IReadOnlySet<string>> entry in currentManifestEntries)
|
||||
{
|
||||
string assemblyPath = Path.Combine(pluginsDirectory, entry.Key);
|
||||
Assert.True(File.Exists(assemblyPath), $"The bundled plugin assembly '{entry.Key}' is missing from '{pluginsDirectory}'.");
|
||||
string actualSha256 = _bundledPluginFileHashFixture.Create(assemblyPath);
|
||||
string expectedSha256 = Assert.Single(entry.Value);
|
||||
Assert.Equal(expectedSha256, actualSha256, ignoreCase: true);
|
||||
}
|
||||
}
|
||||
|
||||
[EnvironmentVariableFact(PUBLISH_DIRECTORY_ENVIRONMENT_VARIABLE)]
|
||||
public void PublishedBundledPluginManifest_WhenPublishDirectoryIsProvided_ShouldMatchThePublishedPluginAssemblies()
|
||||
{
|
||||
// Arrange
|
||||
string publishDirectory = Environment.GetEnvironmentVariable(PUBLISH_DIRECTORY_ENVIRONMENT_VARIABLE)
|
||||
?? throw new InvalidOperationException($"The environment variable '{PUBLISH_DIRECTORY_ENVIRONMENT_VARIABLE}' is not set.");
|
||||
string publishedApiAssemblyPath = BundledPluginManifestTestPaths.GetPublishedApiAssemblyPath(publishDirectory);
|
||||
string publishedPluginsDirectory = BundledPluginManifestTestPaths.GetPublishedPluginsDirectory(publishDirectory);
|
||||
// Load the published API assembly in its own context, so the test reads the exact shipped binary without loading it into the test process.
|
||||
AssemblyLoadContext loadContext = new("PublishedBundledPluginManifestVerification", isCollectible: true);
|
||||
try
|
||||
{
|
||||
Assembly publishedApiAssembly = loadContext.LoadFromAssemblyPath(publishedApiAssemblyPath);
|
||||
// The published assembly must embed the current manifest. A missing resource means the official publish step did not run.
|
||||
using (Stream manifestStream = publishedApiAssembly.GetManifestResourceStream(CURRENT_MANIFEST_RESOURCE_NAME)
|
||||
?? throw new InvalidOperationException("The published API assembly does not embed the current bundled plugin manifest."))
|
||||
{
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> publishedManifestEntries = BundledPluginManifestReader.ReadExpectedChecksums(manifestStream);
|
||||
|
||||
// Assert
|
||||
Assert.NotEmpty(publishedManifestEntries);
|
||||
// The manifest and the published plugin folder must agree exactly: every entry has a file, and the counts match.
|
||||
string[] publishedPluginAssemblyFileNames = [.. Directory.EnumerateFiles(publishedPluginsDirectory, BundledPluginManifestTestPaths.PLUGIN_ASSEMBLY_SEARCH_PATTERN)
|
||||
.Select(Path.GetFileName)
|
||||
.OfType<string>()];
|
||||
Assert.Equal(publishedManifestEntries.Count, publishedPluginAssemblyFileNames.Length);
|
||||
foreach (KeyValuePair<string, IReadOnlySet<string>> entry in publishedManifestEntries)
|
||||
{
|
||||
Assert.Contains(entry.Key, publishedPluginAssemblyFileNames, StringComparer.OrdinalIgnoreCase);
|
||||
string publishedAssemblyPath = Path.Combine(publishedPluginsDirectory, entry.Key);
|
||||
Assert.True(File.Exists(publishedAssemblyPath), $"The published plugin assembly '{entry.Key}' is missing from '{publishedPluginsDirectory}'.");
|
||||
string actualSha256 = _bundledPluginFileHashFixture.Create(publishedAssemblyPath);
|
||||
string expectedSha256 = Assert.Single(entry.Value);
|
||||
Assert.Equal(expectedSha256, actualSha256, ignoreCase: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Unload the collectible context so the published assembly does not stay locked for later test runs.
|
||||
loadContext.Unload();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the embedded current bundled plugin trust manifest through the production reader.
|
||||
/// </summary>
|
||||
/// <returns>A dictionary that maps each bundled plugin assembly file name to the checksums it is allowed to have.</returns>
|
||||
private static IReadOnlyDictionary<string, IReadOnlySet<string>> ReadCurrentManifest()
|
||||
{
|
||||
using (Stream manifestStream = typeof(Program).Assembly.GetManifestResourceStream(CURRENT_MANIFEST_RESOURCE_NAME)
|
||||
?? throw new InvalidOperationException($"The embedded manifest resource '{CURRENT_MANIFEST_RESOURCE_NAME}' is missing."))
|
||||
return BundledPluginManifestReader.ReadExpectedChecksums(manifestStream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the API assembly contains the named embedded manifest resource.
|
||||
/// </summary>
|
||||
/// <param name="resourceName">The name of the embedded manifest resource.</param>
|
||||
/// <returns><see langword="true"/> when the resource exists, <see langword="false"/> otherwise.</returns>
|
||||
private static bool HasManifestResource(string resourceName)
|
||||
{
|
||||
using (Stream? stream = typeof(Program).Assembly.GetManifestResourceStream(resourceName))
|
||||
return stream is not null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads an embedded manifest resource from the API assembly.
|
||||
/// </summary>
|
||||
/// <param name="resourceName">The name of the embedded manifest resource.</param>
|
||||
/// <returns>The text of the manifest.</returns>
|
||||
private static string ReadManifestResource(string resourceName)
|
||||
{
|
||||
using (Stream stream = typeof(Program).Assembly.GetManifestResourceStream(resourceName)
|
||||
?? throw new InvalidOperationException($"The embedded manifest resource '{resourceName}' is missing."))
|
||||
using (StreamReader reader = new(stream))
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the plugin project paths declared in the solution.
|
||||
/// </summary>
|
||||
/// <param name="solutionPath">The absolute path of the solution file.</param>
|
||||
/// <returns>The absolute paths of the plugin projects declared under the plugins solution folder.</returns>
|
||||
private static string[] ReadSolutionPluginProjects(string solutionPath)
|
||||
{
|
||||
string solutionDirectory = Path.GetDirectoryName(solutionPath)
|
||||
?? throw new InvalidOperationException($"The solution directory could not be determined from '{solutionPath}'.");
|
||||
// Only projects under the /plugins/ solution folder are bundled plugins. Test and fixture projects are not part of the release.
|
||||
return [.. XDocument.Load(solutionPath)
|
||||
.Root!
|
||||
.Elements("Folder")
|
||||
.Where(folder => string.Equals((string?)folder.Attribute("Name"), "/plugins/", StringComparison.Ordinal))
|
||||
.Elements("Project")
|
||||
.Select(project => (string?)project.Attribute("Path"))
|
||||
.OfType<string>()
|
||||
.Select(path => Path.GetFullPath(Path.Combine(solutionDirectory, path)))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the plugin project paths declared in the bundled plugin release catalog.
|
||||
/// </summary>
|
||||
/// <param name="catalogPath">The absolute path of the release catalog.</param>
|
||||
/// <returns>The absolute paths of the bundled plugin projects.</returns>
|
||||
private static string[] ReadCatalogPluginProjects(string catalogPath)
|
||||
{
|
||||
string catalogDirectory = Path.GetDirectoryName(catalogPath)
|
||||
?? throw new InvalidOperationException($"The catalog directory could not be determined from '{catalogPath}'.");
|
||||
string msbuildThisFileDirectory = catalogDirectory + Path.DirectorySeparatorChar;
|
||||
// The catalog stores MSBuild-relative paths, so expand $(MSBuildThisFileDirectory) before resolving them.
|
||||
return [.. XDocument.Load(catalogPath)
|
||||
.Descendants("BundledPluginProject")
|
||||
.Select(project => (string?)project.Attribute("Include"))
|
||||
.OfType<string>()
|
||||
.Select(path => path.Replace("$(MSBuildThisFileDirectory)", msbuildThisFileDirectory, StringComparison.Ordinal))
|
||||
.Select(path => Path.GetFullPath(path))];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes and sorts project paths for comparison.
|
||||
/// </summary>
|
||||
/// <param name="paths">The project paths to normalize.</param>
|
||||
/// <returns>The distinct, sorted project paths.</returns>
|
||||
private static string[] NormalizeAndSort(IEnumerable<string> paths)
|
||||
{
|
||||
// Paths are compared case-insensitively because Windows paths are case-insensitive, and the order of the items does not matter.
|
||||
return [.. paths.Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(path => path, StringComparer.OrdinalIgnoreCase)];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Counts the non-comment, non-blank entries of a manifest.
|
||||
/// </summary>
|
||||
/// <param name="manifest">The manifest text.</param>
|
||||
/// <returns>The number of entries.</returns>
|
||||
private static int CountManifestEntries(string manifest)
|
||||
{
|
||||
// The parser ignores comments and blank lines, so the expected count uses the same rule.
|
||||
return manifest.Split('\n')
|
||||
.Select(line => line.Trim())
|
||||
.Count(line => line.Length > 0 && !line.StartsWith('#'));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Counts the checksums parsed for every assembly.
|
||||
/// </summary>
|
||||
/// <param name="checksums">The parsed checksums.</param>
|
||||
/// <returns>The number of checksums.</returns>
|
||||
private static int CountChecksums(IReadOnlyDictionary<string, IReadOnlySet<string>> checksums)
|
||||
{
|
||||
return checksums.Values.Sum(assemblyChecksums => assemblyChecksums.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Normalizes the line endings of a manifest text, so the source file and the embedded copy compare identically on every platform.
|
||||
/// </summary>
|
||||
/// <param name="manifest">The manifest text to normalize.</param>
|
||||
/// <returns>The manifest text with LF line endings.</returns>
|
||||
private static string NormalizeLineEndings(string manifest)
|
||||
{
|
||||
// The checked-in file can use CRLF on Windows while the embedded copy is read as text, so compare with LF endings.
|
||||
return manifest.Replace("\r\n", "\n", StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -1,4 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Nemera.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
using Nemera.Application.Core.MediaLibrary.WrittenContentLibrary.BookLibrary.Artwork;
|
||||
using Nemera.Application.Fixtures.Common.Infrastructure.Models.DTO.Configuration;
|
||||
@@ -13,9 +16,6 @@ using Nemera.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.File
|
||||
using Nemera.Domain.Fixtures.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.ValueObjects;
|
||||
using Nemera.Domain.SharedKernel.Common.Enums.PhotoLibrary;
|
||||
using Nemera.Infrastructure.Common.DependencyInjection;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
@@ -57,7 +57,7 @@ public class BookArtworkServiceSecurityTests
|
||||
mockConfiguration.GetSection(Arg.Any<string>()).Returns(Substitute.For<IConfigurationSection>());
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddInfrastructureLayerServices(mockConfiguration);
|
||||
services.AddInfrastructureLayerServices(mockConfiguration, new Dictionary<string, IReadOnlySet<string>>());
|
||||
services.AddScoped(_ => mockEnvironmentContext);
|
||||
// The real path service is used, so that the sanitization of hostile segment names is exercised.
|
||||
services.AddScoped(_ => CreateRealPathService());
|
||||
|
||||
+15
-1
@@ -26,7 +26,7 @@ public class PluginEntityMappingTests
|
||||
IReadOnlyDictionary<string, string>? expectedSettings = JsonSerializer.Deserialize<Dictionary<string, string>>(entity.SettingsJson!);
|
||||
|
||||
// Act
|
||||
PluginResponse result = entity.ToResponse();
|
||||
PluginResponse result = entity.ToResponse(isOfficial: true);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
@@ -38,6 +38,20 @@ public class PluginEntityMappingTests
|
||||
Assert.Equal(entity.LoadStatus, result.LoadStatus);
|
||||
Assert.Equal(entity.LoadError, result.LoadError);
|
||||
Assert.Equal(expectedSettings, result.Settings);
|
||||
Assert.True(result.IsOfficial);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenPluginIsNotOfficial_ShouldSetIsOfficialFalse()
|
||||
{
|
||||
// Arrange
|
||||
PluginEntity entity = _pluginEntityFixture.Create();
|
||||
|
||||
// Act
|
||||
PluginResponse result = entity.ToResponse(isOfficial: false);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsOfficial);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
+40
-2
@@ -3,7 +3,7 @@ using Nemera.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Nemera.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Nemera.Application.Common.DataAccess.UoW;
|
||||
using Nemera.Application.Common.DTO.Filtering;
|
||||
using Nemera.Application.Common.DTO.Pagination;
|
||||
using Nemera.Application.Common.Infrastructure.Plugins;
|
||||
using Nemera.Application.Core.Plugins.Queries.GetPlugins;
|
||||
using Nemera.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
using Nemera.Application.Fixtures.Common.DTO.Pagination;
|
||||
@@ -27,6 +27,7 @@ public class GetPluginsQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IPluginRepository _mockPluginRepository;
|
||||
private readonly IPluginManager _mockPluginManager;
|
||||
private readonly GetPluginsQueryHandler _sut;
|
||||
private readonly GetPluginsQueryFixture _getPluginsQueryFixture = new();
|
||||
private readonly PluginEntityFixture _pluginEntityFixture = new();
|
||||
@@ -41,7 +42,8 @@ public class GetPluginsQueryHandlerTests
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockPluginRepository = Substitute.For<IPluginRepository>();
|
||||
_mockUnitOfWork.PluginRepository.Returns(_mockPluginRepository);
|
||||
_sut = new GetPluginsQueryHandler(_mockUnitOfWork);
|
||||
_mockPluginManager = Substitute.For<IPluginManager>();
|
||||
_sut = new GetPluginsQueryHandler(_mockUnitOfWork, _mockPluginManager);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -62,6 +64,42 @@ public class GetPluginsQueryHandlerTests
|
||||
Assert.Equal(plugins[0].Id, result.Value[0].Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPluginIsOfficial_ShouldReturnItAsOfficial()
|
||||
{
|
||||
// Arrange
|
||||
PluginEntity plugin = _pluginEntityFixture.Create();
|
||||
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [plugin], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
|
||||
_mockPluginManager.IsOfficial(plugin.Id).Returns(true);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<PluginResponse>> result = await _sut.HandleAsync(_getPluginsQueryFixture.Create(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PluginResponse response = Assert.Single(result.Value);
|
||||
Assert.True(response.IsOfficial);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPluginIsNotOfficial_ShouldReturnItAsNotOfficial()
|
||||
{
|
||||
// Arrange
|
||||
PluginEntity plugin = _pluginEntityFixture.Create();
|
||||
_mockPluginRepository.GetAllAsync<BaseFilterDto>(cancellationToken: Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_paginatedResultDtoFixture.Create(data: [plugin], currentPage: 1, perPage: 1, count: 1, numberOfPages: 1)));
|
||||
_mockPluginManager.IsOfficial(plugin.Id).Returns(false);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<PluginResponse>> result = await _sut.HandleAsync(_getPluginsQueryFixture.Create(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
PluginResponse response = Assert.Single(result.Value);
|
||||
Assert.False(response.IsOfficial);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnError()
|
||||
{
|
||||
|
||||
+8
-6
@@ -1,4 +1,7 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Nemera.Application.Common.DomainEvents;
|
||||
using Nemera.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
|
||||
using Nemera.Application.Common.Infrastructure.Models.DTO.Configuration;
|
||||
@@ -18,9 +21,6 @@ using Nemera.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback
|
||||
using Nemera.Infrastructure.Core.Security;
|
||||
using Nemera.Infrastructure.Core.Time;
|
||||
using Nemera.Plugins.Contracts.Core.Plugins;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
@@ -35,6 +35,8 @@ namespace Nemera.Infrastructure.UnitTests.Common.DependencyInjection;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class InfrastructureLayerServicesTests
|
||||
{
|
||||
private static readonly IReadOnlyDictionary<string, IReadOnlySet<string>> s_emptyBundledPluginChecksums = new Dictionary<string, IReadOnlySet<string>>();
|
||||
|
||||
[Fact]
|
||||
public void AddInfrastructureLayerServices_WhenCalled_ShouldRegisterCoreInfrastructureServices()
|
||||
{
|
||||
@@ -43,7 +45,7 @@ public class InfrastructureLayerServicesTests
|
||||
IConfiguration configuration = CreateConfiguration();
|
||||
|
||||
// Act
|
||||
services.AddInfrastructureLayerServices(configuration);
|
||||
services.AddInfrastructureLayerServices(configuration, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IFileHashService) && descriptor.ImplementationType == typeof(FileHashService));
|
||||
@@ -68,7 +70,7 @@ public class InfrastructureLayerServicesTests
|
||||
IConfiguration configuration = CreateConfiguration();
|
||||
|
||||
// Act
|
||||
services.AddInfrastructureLayerServices(configuration);
|
||||
services.AddInfrastructureLayerServices(configuration, s_emptyBundledPluginChecksums);
|
||||
|
||||
// Assert
|
||||
Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator<PluginsSettingsDto>));
|
||||
@@ -82,7 +84,7 @@ public class InfrastructureLayerServicesTests
|
||||
// Arrange
|
||||
IServiceCollection services = new ServiceCollection();
|
||||
IConfiguration configuration = CreateConfiguration();
|
||||
services.AddInfrastructureLayerServices(configuration);
|
||||
services.AddInfrastructureLayerServices(configuration, s_emptyBundledPluginChecksums);
|
||||
// A plugin registers its typed client after the infrastructure layer, so the defaults must reach it too.
|
||||
services.AddHttpClient("plugin-client");
|
||||
using ServiceProvider serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
+26
-7
@@ -1,11 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Nemera.Application.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Nemera.Application.Common.DataAccess.Entities.Plugins;
|
||||
using Nemera.Application.Common.DataAccess.Repositories.MediaLibrary;
|
||||
using Nemera.Application.Common.DataAccess.Repositories.Plugins;
|
||||
using Nemera.Application.Common.DataAccess.UoW;
|
||||
using Nemera.Application.Common.DTO.Filtering;
|
||||
using Nemera.Application.Common.DTO.Pagination;
|
||||
using Nemera.Application.Common.Infrastructure.Plugins;
|
||||
using Nemera.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
|
||||
using Nemera.Application.Fixtures.Common.DataAccess.Entities.Plugins;
|
||||
@@ -17,13 +19,9 @@ using Nemera.Infrastructure.Common.Models.DTO.Plugins;
|
||||
using Nemera.Infrastructure.Core.Plugins;
|
||||
using Nemera.Infrastructure.Fixtures.Common.Models.DTO.Plugins;
|
||||
using Nemera.Plugins.Contracts.Core.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
@@ -149,6 +147,26 @@ public class PluginDetectionSyncJobTests
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenWarningsExist_ShouldLogThemAsWarnings()
|
||||
{
|
||||
// Arrange
|
||||
_mockLogger.IsEnabled(Arg.Any<LogLevel>()).Returns(true);
|
||||
_mockPluginManager.GetPlugins().Returns([]);
|
||||
PluginDetectionSyncJob sut = CreateSut(warnings: ["The SHA-256 checksum of plugin assembly 'LockedPlugin.dll' could not be computed."]);
|
||||
|
||||
// Act
|
||||
await StartAndWaitForExecutionAsync(sut);
|
||||
|
||||
// Assert
|
||||
_mockLogger.Received(1).Log(
|
||||
LogLevel.Warning,
|
||||
Arg.Any<EventId>(),
|
||||
Arg.Is<object>(state => state.ToString()!.Contains("Plugin warning")),
|
||||
Arg.Any<Exception?>(),
|
||||
Arg.Any<Func<object, Exception?, string>>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StartAsync_WhenNoPluginsAreLoaded_ShouldOnlySaveChanges()
|
||||
{
|
||||
@@ -287,10 +305,11 @@ public class PluginDetectionSyncJobTests
|
||||
/// Creates the system under test wired to the mocked dependencies.
|
||||
/// </summary>
|
||||
/// <param name="loadErrors">The plugin load errors to feed to the job, when any.</param>
|
||||
/// <param name="warnings">The plugin load warnings to feed to the job, when any.</param>
|
||||
/// <returns>The created job instance.</returns>
|
||||
private PluginDetectionSyncJob CreateSut(IReadOnlyList<PluginLoadErrorDto>? loadErrors = null)
|
||||
private PluginDetectionSyncJob CreateSut(IReadOnlyList<PluginLoadErrorDto>? loadErrors = null, IReadOnlyList<string>? warnings = null)
|
||||
{
|
||||
return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, loadErrors ?? [], _mockLogger);
|
||||
return new PluginDetectionSyncJob(_mockServiceScopeFactory, _mockPluginManager, loadErrors ?? [], warnings ?? [], _mockLogger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -15,16 +15,18 @@ namespace Nemera.Infrastructure.UnitTests.Core.Plugins;
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class PluginManagerTests
|
||||
{
|
||||
private PluginManager _sut = new([], [], new HashSet<Guid>());
|
||||
|
||||
[Fact]
|
||||
public void GetPlugins_WhenCalled_ShouldReturnAllLoadedPlugins()
|
||||
{
|
||||
// Arrange
|
||||
IPlugin firstPlugin = CreatePlugin(Guid.NewGuid(), "First Plugin");
|
||||
IPlugin secondPlugin = CreatePlugin(Guid.NewGuid(), "Second Plugin");
|
||||
PluginManager sut = new([firstPlugin, secondPlugin], []);
|
||||
_sut = new([firstPlugin, secondPlugin], [], new HashSet<Guid>());
|
||||
|
||||
// Act
|
||||
IReadOnlyList<IPlugin> result = sut.GetPlugins();
|
||||
IReadOnlyList<IPlugin> result = _sut.GetPlugins();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, result.Count);
|
||||
@@ -36,10 +38,10 @@ public class PluginManagerTests
|
||||
public void GetPlugins_WhenNoPluginsWereLoaded_ShouldReturnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
PluginManager sut = new([], []);
|
||||
_sut = new([], [], new HashSet<Guid>());
|
||||
|
||||
// Act
|
||||
IReadOnlyList<IPlugin> result = sut.GetPlugins();
|
||||
IReadOnlyList<IPlugin> result = _sut.GetPlugins();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
@@ -51,10 +53,10 @@ public class PluginManagerTests
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
IPlugin expectedPlugin = CreatePlugin(pluginId, "Expected Plugin");
|
||||
PluginManager sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")], []);
|
||||
_sut = new([expectedPlugin, CreatePlugin(Guid.NewGuid(), "Other Plugin")], [], new HashSet<Guid>());
|
||||
|
||||
// Act
|
||||
IPlugin? result = sut.GetPlugin(pluginId);
|
||||
IPlugin? result = _sut.GetPlugin(pluginId);
|
||||
|
||||
// Assert
|
||||
Assert.Same(expectedPlugin, result);
|
||||
@@ -64,15 +66,43 @@ public class PluginManagerTests
|
||||
public void GetPlugin_WhenPluginWithIdWasNotLoaded_ShouldReturnNull()
|
||||
{
|
||||
// Arrange
|
||||
PluginManager sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")], []);
|
||||
_sut = new([CreatePlugin(Guid.NewGuid(), "Loaded Plugin")], [], new HashSet<Guid>());
|
||||
|
||||
// Act
|
||||
IPlugin? result = sut.GetPlugin(Guid.NewGuid());
|
||||
IPlugin? result = _sut.GetPlugin(Guid.NewGuid());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsOfficial_WhenPluginIsInTheOfficialSet_ShouldReturnTrue()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
_sut = new([CreatePlugin(pluginId, "Official Plugin")], [], new HashSet<Guid> { pluginId });
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsOfficial(pluginId);
|
||||
|
||||
// Assert
|
||||
Assert.True(result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IsOfficial_WhenPluginIsNotInTheOfficialSet_ShouldReturnFalse()
|
||||
{
|
||||
// Arrange
|
||||
Guid pluginId = Guid.NewGuid();
|
||||
_sut = new([CreatePlugin(pluginId, "Unofficial Plugin")], [], new HashSet<Guid>());
|
||||
|
||||
// Act
|
||||
bool result = _sut.IsOfficial(pluginId);
|
||||
|
||||
// Assert
|
||||
Assert.False(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a mocked plugin with the provided identity.
|
||||
/// </summary>
|
||||
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Nemera.Presentation.Api.Core.Plugins;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
#endregion
|
||||
|
||||
namespace Nemera.Presentation.Api.UnitTests.Core.Plugins;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="BundledPluginManifestReader"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class BundledPluginManifestReaderTests
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of the bundled plugin assembly used by the tests.
|
||||
/// </summary>
|
||||
private const string ASSEMBLY_FILE_NAME = "Nemera.Plugins.Epub.dll";
|
||||
|
||||
/// <summary>
|
||||
/// The name of another bundled plugin assembly used by the tests.
|
||||
/// </summary>
|
||||
private const string OTHER_ASSEMBLY_FILE_NAME = "Nemera.Plugins.Pdf.dll";
|
||||
|
||||
/// <summary>
|
||||
/// A valid SHA-256 checksum used by the tests.
|
||||
/// </summary>
|
||||
private const string CHECKSUM = "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF";
|
||||
|
||||
/// <summary>
|
||||
/// Another valid SHA-256 checksum used by the tests.
|
||||
/// </summary>
|
||||
private const string OTHER_CHECKSUM = "FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210FEDCBA9876543210";
|
||||
|
||||
[Fact]
|
||||
public void ReadExpectedChecksums_WhenManifestContainsCommentsAndBlankLines_ShouldIgnoreThem()
|
||||
{
|
||||
// Arrange
|
||||
string manifest = string.Join(Environment.NewLine, "# Bundled plugin trust list.", string.Empty, $" {ASSEMBLY_FILE_NAME} | {CHECKSUM} ");
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> actualChecksums = ReadHistoricalManifest(manifest);
|
||||
|
||||
// Assert
|
||||
KeyValuePair<string, IReadOnlySet<string>> entry = Assert.Single(actualChecksums);
|
||||
Assert.Equal(ASSEMBLY_FILE_NAME, entry.Key);
|
||||
Assert.True(entry.Value.SetEquals([CHECKSUM]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadExpectedChecksums_WhenAssemblyIsListedMultipleTimes_ShouldMergeItsChecksums()
|
||||
{
|
||||
// Arrange
|
||||
string manifest = string.Join(Environment.NewLine,
|
||||
$"{ASSEMBLY_FILE_NAME}|{CHECKSUM}",
|
||||
// The second line uses the uppercase spelling to prove that assembly names are merged case-insensitively.
|
||||
$"{ASSEMBLY_FILE_NAME.ToUpperInvariant()}|{OTHER_CHECKSUM}");
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> actualChecksums = ReadHistoricalManifest(manifest);
|
||||
|
||||
// Assert
|
||||
KeyValuePair<string, IReadOnlySet<string>> entry = Assert.Single(actualChecksums);
|
||||
Assert.Equal(ASSEMBLY_FILE_NAME, entry.Key);
|
||||
Assert.True(entry.Value.SetEquals([CHECKSUM, OTHER_CHECKSUM]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadExpectedChecksums_WhenCurrentManifestIsProvided_ShouldMergeBothManifests()
|
||||
{
|
||||
// Arrange
|
||||
string historicalManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}";
|
||||
string currentManifest = $"{OTHER_ASSEMBLY_FILE_NAME}|{OTHER_CHECKSUM}";
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> actualChecksums = ReadManifests(historicalManifest, currentManifest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(2, actualChecksums.Count);
|
||||
Assert.True(actualChecksums[ASSEMBLY_FILE_NAME].SetEquals([CHECKSUM]));
|
||||
Assert.True(actualChecksums[OTHER_ASSEMBLY_FILE_NAME].SetEquals([OTHER_CHECKSUM]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadExpectedChecksums_WhenDenyManifestRevokesOneChecksum_ShouldKeepTheOther()
|
||||
{
|
||||
// Arrange
|
||||
string historicalManifest = string.Join(Environment.NewLine,
|
||||
$"{ASSEMBLY_FILE_NAME}|{CHECKSUM}",
|
||||
$"{ASSEMBLY_FILE_NAME}|{OTHER_CHECKSUM}");
|
||||
string denyManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}";
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> actualChecksums = ReadManifests(historicalManifest, string.Empty, denyManifest);
|
||||
|
||||
// Assert
|
||||
KeyValuePair<string, IReadOnlySet<string>> entry = Assert.Single(actualChecksums);
|
||||
Assert.True(entry.Value.SetEquals([OTHER_CHECKSUM]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadExpectedChecksums_WhenDenyManifestRevokesEveryChecksum_ShouldRemoveTheAssembly()
|
||||
{
|
||||
// Arrange
|
||||
string historicalManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}";
|
||||
string denyManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}";
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> actualChecksums = ReadManifests(historicalManifest, string.Empty, denyManifest);
|
||||
|
||||
// Assert
|
||||
Assert.Empty(actualChecksums);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadExpectedChecksums_WhenDenyManifestTargetsAnotherAssembly_ShouldKeepTheTrustedAssembly()
|
||||
{
|
||||
// Arrange
|
||||
string historicalManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}";
|
||||
string denyManifest = $"{OTHER_ASSEMBLY_FILE_NAME}|{OTHER_CHECKSUM}";
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> actualChecksums = ReadManifests(historicalManifest, string.Empty, denyManifest);
|
||||
|
||||
// Assert
|
||||
KeyValuePair<string, IReadOnlySet<string>> entry = Assert.Single(actualChecksums);
|
||||
Assert.Equal(ASSEMBLY_FILE_NAME, entry.Key);
|
||||
Assert.True(entry.Value.SetEquals([CHECKSUM]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadExpectedChecksums_WhenDenyManifestRevokesACurrentManifestChecksum_ShouldRemoveIt()
|
||||
{
|
||||
// Arrange
|
||||
string historicalManifest = $"{ASSEMBLY_FILE_NAME}|{CHECKSUM}";
|
||||
string currentManifest = $"{ASSEMBLY_FILE_NAME}|{OTHER_CHECKSUM}";
|
||||
// Revocation must apply to the current release's hashes as well as to historical ones.
|
||||
string denyManifest = $"{ASSEMBLY_FILE_NAME}|{OTHER_CHECKSUM}";
|
||||
|
||||
// Act
|
||||
IReadOnlyDictionary<string, IReadOnlySet<string>> actualChecksums = ReadManifests(historicalManifest, currentManifest, denyManifest);
|
||||
|
||||
// Assert
|
||||
KeyValuePair<string, IReadOnlySet<string>> entry = Assert.Single(actualChecksums);
|
||||
Assert.True(entry.Value.SetEquals([CHECKSUM]));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadExpectedChecksums_WhenAssemblyFileNameIsEmpty_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
string manifest = $"|{CHECKSUM}";
|
||||
|
||||
// Act & Assert
|
||||
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => ReadHistoricalManifest(manifest));
|
||||
Assert.Contains("line 1", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(ASSEMBLY_FILE_NAME)] // Missing the separator and the checksum.
|
||||
[InlineData(ASSEMBLY_FILE_NAME + "|" + CHECKSUM + "|extra")] // More than one separator.
|
||||
public void ReadExpectedChecksums_WhenEntryDoesNotHaveTwoFields_ShouldThrowInvalidOperationException(string manifest)
|
||||
{
|
||||
// Act & Assert
|
||||
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => ReadHistoricalManifest(manifest));
|
||||
Assert.Contains("line 1", exception.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(63)] // Truncated checksum.
|
||||
[InlineData(65)] // Checksum with an extra character.
|
||||
public void ReadExpectedChecksums_WhenChecksumDoesNotHave64Characters_ShouldThrowInvalidOperationException(int checksumLength)
|
||||
{
|
||||
// Arrange
|
||||
string checksum = checksumLength < CHECKSUM.Length ? CHECKSUM[..checksumLength] : CHECKSUM + "0";
|
||||
string manifest = $"{ASSEMBLY_FILE_NAME}|{checksum}";
|
||||
|
||||
// Act & Assert
|
||||
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => ReadHistoricalManifest(manifest));
|
||||
Assert.Contains("line 1", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ReadExpectedChecksums_WhenChecksumIsNotHexadecimal_ShouldThrowInvalidOperationException()
|
||||
{
|
||||
// Arrange
|
||||
string checksum = new('Z', 64);
|
||||
string manifest = $"{ASSEMBLY_FILE_NAME}|{checksum}";
|
||||
|
||||
// Act & Assert
|
||||
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => ReadHistoricalManifest(manifest));
|
||||
Assert.Contains("line 1", exception.Message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a historical trust manifest through the production reader.
|
||||
/// </summary>
|
||||
/// <param name="manifest">The manifest text.</param>
|
||||
/// <returns>The checksums parsed from the manifest.</returns>
|
||||
private static IReadOnlyDictionary<string, IReadOnlySet<string>> ReadHistoricalManifest(string manifest)
|
||||
{
|
||||
using (MemoryStream manifestStream = CreateManifestStream(manifest))
|
||||
return BundledPluginManifestReader.ReadExpectedChecksums(manifestStream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a historical and a current trust manifest through the production reader.
|
||||
/// </summary>
|
||||
/// <param name="historicalManifest">The historical manifest text.</param>
|
||||
/// <param name="currentManifest">The current manifest text.</param>
|
||||
/// <param name="denyManifest">The optional deny manifest text.</param>
|
||||
/// <returns>The checksums parsed from both manifests.</returns>
|
||||
private static IReadOnlyDictionary<string, IReadOnlySet<string>> ReadManifests(string historicalManifest, string currentManifest, string? denyManifest = null)
|
||||
{
|
||||
using (MemoryStream historicalManifestStream = CreateManifestStream(historicalManifest))
|
||||
{
|
||||
using (MemoryStream currentManifestStream = CreateManifestStream(currentManifest))
|
||||
{
|
||||
// A null deny manifest means the test only exercises the historical and current merge.
|
||||
if (denyManifest is null)
|
||||
return BundledPluginManifestReader.ReadExpectedChecksums(historicalManifestStream, currentManifestStream);
|
||||
using (MemoryStream denyManifestStream = CreateManifestStream(denyManifest))
|
||||
return BundledPluginManifestReader.ReadExpectedChecksums(historicalManifestStream, currentManifestStream, denyManifestStream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a stream that contains the provided trust manifest.
|
||||
/// </summary>
|
||||
/// <param name="manifest">The manifest text.</param>
|
||||
/// <returns>A stream over the UTF-8 encoded manifest text.</returns>
|
||||
private static MemoryStream CreateManifestStream(string manifest)
|
||||
{
|
||||
// The production reader consumes a stream, so the tests use an in-memory UTF-8 stream instead of writing temporary files.
|
||||
return new(Encoding.UTF8.GetBytes(manifest));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user