#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; /// /// Contains integration tests for the class. /// [ExcludeFromCodeCoverage] public class BundledPluginManifestReaderTests { /// /// The resource name of the append-only trust list of previously released bundled plugin binaries. /// private const string HISTORICAL_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.historical.manifest"; /// /// The resource name of the trust list generated for the current build's bundled plugin binaries. /// private const string CURRENT_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.current.manifest"; /// /// The resource name of the list of bundled plugin checksums that are no longer trusted. /// private const string DENY_MANIFEST_RESOURCE_NAME = "Nemera.Presentation.Api.BundledPlugins.deny.manifest"; /// /// The environment variable that points the published artifact verification at the publish output directory. /// private const string PUBLISH_DIRECTORY_ENVIRONMENT_VARIABLE = "NEMERA_API_PUBLISH_DIRECTORY"; /// /// The fixture that computes the SHA-256 checksums of the bundled plugin files. /// 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> 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> 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> 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> 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> currentManifestEntries = ReadCurrentManifest(); // Assert // The embedded hashes must describe the binaries that were actually deployed, not merely the ones that were built. foreach (KeyValuePair> 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> 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()]; Assert.Equal(publishedManifestEntries.Count, publishedPluginAssemblyFileNames.Length); foreach (KeyValuePair> 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); } } } /// /// Reads the embedded current bundled plugin trust manifest through the production reader. /// /// A dictionary that maps each bundled plugin assembly file name to the checksums it is allowed to have. private static IReadOnlyDictionary> 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); } /// /// Determines whether the API assembly contains the named embedded manifest resource. /// /// The name of the embedded manifest resource. /// when the resource exists, otherwise. private static bool HasManifestResource(string resourceName) { using (Stream? stream = typeof(Program).Assembly.GetManifestResourceStream(resourceName)) return stream is not null; } /// /// Reads an embedded manifest resource from the API assembly. /// /// The name of the embedded manifest resource. /// The text of the manifest. 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(); } /// /// Reads the plugin project paths declared in the solution. /// /// The absolute path of the solution file. /// The absolute paths of the plugin projects declared under the plugins solution folder. 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() .Select(path => Path.GetFullPath(Path.Combine(solutionDirectory, path)))]; } /// /// Reads the plugin project paths declared in the bundled plugin release catalog. /// /// The absolute path of the release catalog. /// The absolute paths of the bundled plugin projects. 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() .Select(path => path.Replace("$(MSBuildThisFileDirectory)", msbuildThisFileDirectory, StringComparison.Ordinal)) .Select(path => Path.GetFullPath(path))]; } /// /// Normalizes and sorts project paths for comparison. /// /// The project paths to normalize. /// The distinct, sorted project paths. private static string[] NormalizeAndSort(IEnumerable 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)]; } /// /// Counts the non-comment, non-blank entries of a manifest. /// /// The manifest text. /// The number of entries. 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('#')); } /// /// Counts the checksums parsed for every assembly. /// /// The parsed checksums. /// The number of checksums. private static int CountChecksums(IReadOnlyDictionary> checksums) { return checksums.Values.Sum(assemblyChecksums => assemblyChecksums.Count); } /// /// Normalizes the line endings of a manifest text, so the source file and the embedded copy compare identically on every platform. /// /// The manifest text to normalize. /// The manifest text with LF line endings. 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); } }