#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
#endregion
namespace Nemera.Presentation.Api.Core.Plugins;
///
/// Reads the trust manifests of the bundled plugin binaries embedded in the API assembly.
///
internal static class BundledPluginManifestReader
{
///
/// 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";
///
/// Reads the trusted SHA-256 checksums of the bundled plugin binaries from the embedded trust manifests.
/// The current build's manifest is read only for an official release build, so a local build cannot certify its own plugins.
/// Denied checksums are removed from the historical and current trust lists.
///
/// A dictionary that maps each bundled plugin assembly file name to the checksums it is allowed to have.
public static IReadOnlyDictionary> ReadExpectedChecksums()
{
// The historical list is always embedded, because it carries the hashes of earlier releases and those binaries must stay trusted after an upgrade.
using (Stream historicalManifestStream = GetManifestResourceStream(HISTORICAL_MANIFEST_RESOURCE_NAME))
{
// The deny list is always embedded too, so revoking a hash does not depend on the release being rebuilt.
using (Stream denyManifestStream = GetManifestResourceStream(DENY_MANIFEST_RESOURCE_NAME))
{
// A normal build cannot certify its own plugins. Only an official release build embeds the current manifest,
// so a developer cannot make a locally built plugin appear Official just by building the project.
if (!IsOfficialReleaseBuild())
return ReadExpectedChecksums(historicalManifestStream, null, denyManifestStream);
using (Stream currentManifestStream = GetManifestResourceStream(CURRENT_MANIFEST_RESOURCE_NAME))
return ReadExpectedChecksums(historicalManifestStream, currentManifestStream, denyManifestStream);
}
}
}
///
/// Reads the trusted SHA-256 checksums of the bundled plugin binaries from the provided trust manifest streams.
///
/// The stream that contains the append-only trust list of previously released bundled plugin binaries.
/// The stream that contains the trust list generated for the current build's bundled plugin binaries, or when the build is not an official release build.
/// The stream that contains the checksums that are no longer trusted, or when no deny list is available.
/// A dictionary that maps each bundled plugin assembly file name to the checksums it is allowed to have.
internal static IReadOnlyDictionary> ReadExpectedChecksums(Stream historicalManifestStream, Stream? currentManifestStream = null, Stream? denyManifestStream = null)
{
// Assembly file names are compared case-insensitively because the plugins directory is case-insensitive on Windows.
Dictionary> checksumsByAssemblyFileName = new(StringComparer.OrdinalIgnoreCase);
// The historical list comes first so the current release can add hashes without replacing the earlier ones.
ReadManifest(historicalManifestStream, HISTORICAL_MANIFEST_RESOURCE_NAME, checksumsByAssemblyFileName);
if (currentManifestStream is not null)
ReadManifest(currentManifestStream, CURRENT_MANIFEST_RESOURCE_NAME, checksumsByAssemblyFileName);
// Revocation is applied last so a denied hash wins over every trust list, including the current release's own entries.
if (denyManifestStream is not null)
RemoveDeniedChecksums(denyManifestStream, checksumsByAssemblyFileName);
// The loader only reads the trust list, so the result exposes the sets as read-only even though they were built as mutable sets.
Dictionary> expectedChecksums = new(StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair> checksums in checksumsByAssemblyFileName)
expectedChecksums[checksums.Key] = checksums.Value;
return expectedChecksums;
}
///
/// Removes the checksums of the deny list from the accumulated trust list.
///
/// The stream that contains the checksums that are no longer trusted.
/// The dictionary that accumulates the trust list entries.
private static void RemoveDeniedChecksums(Stream denyManifestStream, Dictionary> checksumsByAssemblyFileName)
{
// The deny list is parsed on its own first, so an entry for an unknown or retired assembly can be ignored without failing the whole manifest.
Dictionary> deniedChecksumsByAssemblyFileName = new(StringComparer.OrdinalIgnoreCase);
ReadManifest(denyManifestStream, DENY_MANIFEST_RESOURCE_NAME, deniedChecksumsByAssemblyFileName);
foreach (KeyValuePair> deniedChecksums in deniedChecksumsByAssemblyFileName)
{
// A deny entry for an assembly that is not trusted anywhere is harmless.
if (!checksumsByAssemblyFileName.TryGetValue(deniedChecksums.Key, out HashSet? assemblyChecksums))
continue;
assemblyChecksums.ExceptWith(deniedChecksums.Value);
// An assembly with no trusted hashes left is removed, so the result never carries an empty trust set.
if (assemblyChecksums.Count == 0)
checksumsByAssemblyFileName.Remove(deniedChecksums.Key);
}
}
///
/// Determines whether the API assembly was produced by an official release build.
///
/// when the assembly carries the official release marker, otherwise.
private static bool IsOfficialReleaseBuild()
{
// The official build injects this marker from the OFFICIAL_RELEASE_BUILD compilation symbol. build.proj defines the symbol only for the
// official release flow, so a normal build has no marker and does not embed a current manifest of its own binaries.
return typeof(BundledPluginManifestReader).Assembly
.GetCustomAttributes()
.Any(attribute => attribute.Key == "OfficialReleaseBuild" && attribute.Value == "true");
}
///
/// Opens an embedded trust manifest resource.
///
/// The name of the embedded manifest resource.
/// The stream that contains the manifest.
private static Stream GetManifestResourceStream(string resourceName)
{
// The historical and deny manifests are required for every build. A missing resource means the packaging step is broken,
// and failing fast is safer than starting with an empty trust list that marks every bundled plugin as not Official.
return typeof(BundledPluginManifestReader).Assembly.GetManifestResourceStream(resourceName)
?? throw new InvalidOperationException($"The bundled plugin manifest resource '{resourceName}' is missing.");
}
///
/// Reads one trust manifest and adds its entries to .
///
/// The stream that contains the manifest.
/// The name of the manifest resource, used in error messages.
/// The dictionary that accumulates the trust list entries.
private static void ReadManifest(Stream manifestStream, string resourceName, Dictionary> checksumsByAssemblyFileName)
{
// Each entry is "assembly-file-name|sha256". Blank lines and lines starting with # are ignored, so the checked-in list can carry release notes.
using (StreamReader reader = new(manifestStream))
{
int lineNumber = 0;
string? line;
while ((line = reader.ReadLine()) is not null)
{
lineNumber++;
string trimmedLine = line.Trim();
if (trimmedLine.Length == 0 || trimmedLine.StartsWith('#'))
continue;
// A malformed entry is a build error rather than a skipped line, because silently ignoring it could hide a plugin that the release intended to trust.
string[] parts = trimmedLine.Split('|');
if (parts.Length != 2)
throw new InvalidOperationException($"The bundled plugin manifest resource '{resourceName}' contains an invalid entry at line {lineNumber}.");
string assemblyFileName = parts[0].Trim();
string checksum = parts[1].Trim();
// A SHA-256 checksum is 64 hexadecimal characters. The length check gives a clearer error than the conversion below.
if (assemblyFileName.Length == 0 || checksum.Length != 64)
throw new InvalidOperationException($"The bundled plugin manifest resource '{resourceName}' contains an invalid entry at line {lineNumber}.");
int checksumLength;
try
{
checksumLength = Convert.FromHexString(checksum).Length;
}
catch (FormatException exception)
{
throw new InvalidOperationException($"The bundled plugin manifest resource '{resourceName}' contains an invalid checksum at line {lineNumber}.", exception);
}
// The byte count is checked as well, so a future change to the length check cannot let a non-SHA-256 value through.
if (checksumLength != 32)
throw new InvalidOperationException($"The bundled plugin manifest resource '{resourceName}' contains an invalid checksum at line {lineNumber}.");
// The historical and current manifests can list the same hash. The set makes that duplicate harmless.
if (!checksumsByAssemblyFileName.TryGetValue(assemblyFileName, out HashSet? assemblyChecksums))
{
assemblyChecksums = new HashSet(StringComparer.OrdinalIgnoreCase);
checksumsByAssemblyFileName[assemblyFileName] = assemblyChecksums;
}
assemblyChecksums.Add(checksum);
}
}
}
}