using System.Buffers.Binary; using System.Security.Cryptography; using System.Text; using Titano.Core.Packaging; using Titano.Testing; namespace Titano.Core.Tests.Packaging; /// Synthetic stubs, component trees and hand-made installers for the packaging tests. internal sealed class PackagingFixture(TestContext context) { public static readonly DateTime FixedTime = new(2026, 3, 14, 15, 9, 26, DateTimeKind.Utc); private static readonly byte[] CraftStub = [(byte)'M', (byte)'Z', 1, 2, 3, 4, 5, 6, 7, 8, 9]; public string Root { get; } = context.CreateTempDirectory("packaging"); /// A setup "program": any bytes work, the format does not interpret the stub unless it is a PE. public string Stub(int length = 4096) { var path = Path.Combine(Root, "Titano.Setup.exe"); var bytes = new byte[length]; new Random(7).NextBytes(bytes); "MZ"u8.CopyTo(bytes); File.WriteAllBytes(path, bytes); return path; } /// Creates (payload path → content) under a new folder with a fixed mtime. public string Folder(string name, params (string Path, byte[] Content)[] files) { var dir = Path.Combine(Root, name); Directory.CreateDirectory(dir); foreach (var (relative, content) in files) { var path = Path.Combine(dir, relative.Replace('/', Path.DirectorySeparatorChar)); Directory.CreateDirectory(Path.GetDirectoryName(path)!); File.WriteAllBytes(path, content); File.SetLastWriteTimeUtc(path, FixedTime); } return dir; } public static byte[] Text(string s, int repeat = 1) => Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat(s, repeat))); public static byte[] Random(int length, int seed) { var bytes = new byte[length]; new Random(seed).NextBytes(bytes); return bytes; } public static PayloadSource Source(params PayloadComponentSource[] components) => new() { Product = "Titano", Version = "1.2.3", Components = components, }; public string Pack(string stub, PayloadSource source, string name = "Titano-Setup.exe") { var output = Path.Combine(Root, "out", name); Directory.CreateDirectory(Path.GetDirectoryName(output)!); PayloadWriter.Write(stub, source, output); return output; } /// /// A minimal PE32+ header (no sections) followed by filler, with an optional certificate table at the end the /// way signtool lays it out: 8-byte aligned, pointed at by the security data directory. /// public static byte[] PortableExecutable(int fillerLength, byte[]? certificate = null) { const int peOffset = 0x80; const int optionalHeaderSize = 240; var headerLength = peOffset + 4 + 20 + optionalHeaderSize; var image = new byte[headerLength + fillerLength]; "MZ"u8.CopyTo(image); BinaryPrimitives.WriteInt32LittleEndian(image.AsSpan(0x3C), peOffset); "PE\0\0"u8.CopyTo(image.AsSpan(peOffset)); var coff = image.AsSpan(peOffset + 4); BinaryPrimitives.WriteUInt16LittleEndian(coff, 0x8664); BinaryPrimitives.WriteUInt16LittleEndian(coff[16..], optionalHeaderSize); BinaryPrimitives.WriteUInt16LittleEndian(coff[18..], 0x0022); var optional = image.AsSpan(peOffset + 24); BinaryPrimitives.WriteUInt16LittleEndian(optional, 0x20B); BinaryPrimitives.WriteUInt32LittleEndian(optional[32..], 0x1000); // SectionAlignment BinaryPrimitives.WriteUInt32LittleEndian(optional[36..], 0x200); // FileAlignment BinaryPrimitives.WriteUInt32LittleEndian(optional[108..], 16); // NumberOfRvaAndSizes new Random(3).NextBytes(image.AsSpan(headerLength)); return certificate is null ? image : Sign(image, certificate); } /// Appends a certificate table and points the security directory at it, as signtool does. public static byte[] Sign(byte[] file, byte[] certificate) { var aligned = (file.Length + 7) / 8 * 8; var signed = new byte[aligned + certificate.Length]; file.CopyTo(signed, 0); certificate.CopyTo(signed, aligned); var entry = SecurityDirectoryOffset(signed); BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(entry), (uint)aligned); BinaryPrimitives.WriteUInt32LittleEndian(signed.AsSpan(entry + 4), (uint)certificate.Length); return signed; } /// File offset of the security data directory entry of an image built by . public static int SecurityDirectoryOffset(byte[] image) => BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(0x3C)) + 4 + 20 + 112 + 4 * 8; /// Assembles an installer by hand from a manifest and data region, bypassing the writer's checks. public string Craft(PayloadManifest manifest, byte[] data, string name = "crafted.exe") => Craft(manifest.ToJsonBytes(), data, name); /// Same with raw manifest bytes, which need not be valid JSON; the footer hash always matches them. public string Craft(byte[] json, byte[] data, string name = "crafted.exe") { var stub = CraftStub; using var ms = new MemoryStream(); ms.Write(stub); ms.Write(json); ms.Write(data); ms.Write(new byte[(8 - ms.Length % 8) % 8]); var footer = new byte[PayloadFormat.FooterLength]; new PayloadFooter(stub.Length, json.Length, data.Length, SHA256.HashData(json)).WriteTo(footer); ms.Write(footer); var path = Path.Combine(Root, name); File.WriteAllBytes(path, ms.ToArray()); return path; } public static string Sha256(byte[] content) => Convert.ToHexStringLower(SHA256.HashData(content)); }