mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
363 lines
19 KiB
C#
363 lines
19 KiB
C#
#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.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);
|
|
// Read the resource directly from the file. Loading the assembly would fail for a runtime whose architecture differs from the test process.
|
|
byte[] publishedManifestBytes = PublishedAssemblyResourceReader.ReadEmbeddedResource(publishedApiAssemblyPath, CURRENT_MANIFEST_RESOURCE_NAME);
|
|
using (MemoryStream manifestStream = new(publishedManifestBytes))
|
|
{
|
|
// 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);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <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);
|
|
}
|
|
}
|