refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

@@ -0,0 +1,103 @@
using Chronos.Core.Packaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Packaging;
public sealed class InstallTransactionTests(TestContext context)
{
[Test]
public void CommitReplacesFilesAndCleansUp()
{
var target = context.CreateTempDirectory();
File.WriteAllText(Path.Combine(target, "Chronos.exe"), "old");
File.WriteAllText(Path.Combine(target, "user-notes.txt"), "keep");
using (var tx = new InstallTransaction(target))
{
Write(tx.StagingDirectory, "Chronos.exe", "new");
Write(tx.StagingDirectory, "lib/new.dll", "dll");
tx.Commit(["Chronos.exe", "lib/new.dll"]);
}
Assert.Equal("new", File.ReadAllText(Path.Combine(target, "Chronos.exe")));
Assert.Equal("dll", File.ReadAllText(Path.Combine(target, "lib", "new.dll")));
Assert.Equal("keep", File.ReadAllText(Path.Combine(target, "user-notes.txt")));
Assert.Empty(Directory.GetDirectories(target, ".setup-*"));
}
[Test]
public void FailedCommitRestoresThePreviousInstall()
{
var target = context.CreateTempDirectory();
File.WriteAllText(Path.Combine(target, "Chronos.exe"), "old");
// A folder where the new version has a file makes the second move fail.
Directory.CreateDirectory(Path.Combine(target, "blocked"));
File.WriteAllText(Path.Combine(target, "blocked", "inside.txt"), "x");
using (var tx = new InstallTransaction(target))
{
Write(tx.StagingDirectory, "Chronos.exe", "new");
Write(tx.StagingDirectory, "added.dll", "added");
Write(tx.StagingDirectory, "blocked", "file");
// Linux reports IOException, Windows UnauthorizedAccessException for a file moved onto a folder.
var ex = Assert.Throws<Exception>(() => tx.Commit(["Chronos.exe", "added.dll", "blocked"]));
Assert.True(ex is IOException or UnauthorizedAccessException, ex.GetType().Name);
}
Assert.Equal("old", File.ReadAllText(Path.Combine(target, "Chronos.exe")));
Assert.FileMissing(Path.Combine(target, "added.dll"));
Assert.Equal("x", File.ReadAllText(Path.Combine(target, "blocked", "inside.txt")));
Assert.Empty(Directory.GetDirectories(target, ".setup-*"));
}
[Test]
public void StaleStagingFoldersFromAnInterruptedRunAreRemoved()
{
var target = context.CreateTempDirectory();
Directory.CreateDirectory(Path.Combine(target, ".setup-staging-deadbeef", "sub"));
Directory.CreateDirectory(Path.Combine(target, ".setup-other"));
using (new InstallTransaction(target))
{
}
Assert.False(Directory.Exists(Path.Combine(target, ".setup-staging-deadbeef")));
Assert.True(Directory.Exists(Path.Combine(target, ".setup-other")));
}
[Test]
public void RemoveDeletesOnlyLoggedFilesAndPrunesEmptyFolders()
{
var root = context.CreateTempDirectory();
Write(root, "Chronos.exe", "a");
Write(root, "lib/x/y.dll", "b");
Write(root, "lib/keep.txt", "user");
var failed = InstalledFiles.Remove(root, ["Chronos.exe", "lib/x/y.dll", "already-gone.dll"], removeEmptyRoot: true);
Assert.Empty(failed);
Assert.FileMissing(Path.Combine(root, "Chronos.exe"));
Assert.False(Directory.Exists(Path.Combine(root, "lib", "x")));
Assert.Equal("user", File.ReadAllText(Path.Combine(root, "lib", "keep.txt")));
Assert.True(Directory.Exists(root), "root keeps unlisted files");
InstalledFiles.Remove(root, ["lib/keep.txt"], removeEmptyRoot: true);
Assert.False(Directory.Exists(root));
}
[Test]
public void RemoveRefusesPathsOutsideTheRoot()
{
var parent = context.CreateTempDirectory();
var root = Path.Combine(parent, "install");
Directory.CreateDirectory(root);
Write(parent, "outside.txt", "precious");
Assert.Throws<PayloadException>(() => InstalledFiles.Remove(root, ["../outside.txt"]));
Assert.FileExists(Path.Combine(parent, "outside.txt"));
}
private static void Write(string root, string relative, string content)
{
var path = Path.Combine(root, relative.Replace('/', Path.DirectorySeparatorChar));
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, content);
}
}
@@ -0,0 +1,132 @@
using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Packaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Packaging;
/// <summary>Synthetic stubs, component trees and hand-made installers for the packaging tests.</summary>
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");
/// <summary>A setup "program": any bytes work, the format does not interpret the stub unless it is a PE.</summary>
public string Stub(int length = 4096)
{
var path = Path.Combine(Root, "Chronos.Setup.exe");
var bytes = new byte[length];
new Random(7).NextBytes(bytes);
"MZ"u8.CopyTo(bytes);
File.WriteAllBytes(path, bytes);
return path;
}
/// <summary>Creates <paramref name="files"/> (payload path → content) under a new folder with a fixed mtime.</summary>
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 = "Chronos",
Version = "1.2.3",
Components = components,
};
public string Pack(string stub, PayloadSource source, string name = "Chronos-Setup.exe")
{
var output = Path.Combine(Root, "out", name);
Directory.CreateDirectory(Path.GetDirectoryName(output)!);
PayloadWriter.Write(stub, source, output);
return output;
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>Appends a certificate table and points the security directory at it, as signtool does.</summary>
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;
}
/// <summary>File offset of the security data directory entry of an image built by <see cref="PortableExecutable"/>.</summary>
public static int SecurityDirectoryOffset(byte[] image) =>
BinaryPrimitives.ReadInt32LittleEndian(image.AsSpan(0x3C)) + 4 + 20 + 112 + 4 * 8;
/// <summary>Assembles an installer by hand from a manifest and data region, bypassing the writer's checks.</summary>
public string Craft(PayloadManifest manifest, byte[] data, string name = "crafted.exe") => Craft(manifest.ToJsonBytes(), data, name);
/// <summary>Same with raw manifest bytes, which need not be valid JSON; the footer hash always matches them.</summary>
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));
}
@@ -0,0 +1,227 @@
using System.Buffers.Binary;
using System.IO.Compression;
using Chronos.Core.Packaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Packaging;
public sealed class PayloadIntegrityTests(TestContext context)
{
private readonly PackagingFixture _fx = new(context);
private (string Installer, long PayloadOffset, byte[] Bytes) PackSample()
{
var app = _fx.Folder("app",
("Chronos.exe", PackagingFixture.Text("program ", 3000)),
("noise.bin", PackagingFixture.Random(40_000, 5)),
("docs/readme.txt", PackagingFixture.Text("read me ", 200)));
var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Chronos", "Chronos", true, app)));
using var reader = PayloadReader.Open(installer);
return (installer, reader.PayloadOffset, File.ReadAllBytes(installer));
}
[Test]
public void TamperedManifestIsRejected()
{
var (installer, offset, bytes) = PackSample();
// Flip the first letter of "Chronos" in "product":"Chronos".
var at = (int)offset + bytes.AsSpan((int)offset).IndexOf("\"Chronos\""u8) + 1;
Assert.True(at > offset, "the manifest names the product");
bytes[at] = (byte)'X';
File.WriteAllBytes(installer, bytes);
var ex = Assert.Throws<PayloadException>(() => PayloadReader.Open(installer));
Assert.Equal(PayloadError.Corrupt, ex.Error);
Assert.Contains("SHA-256", ex.Message);
}
[Test]
public void TamperedFooterHashIsRejected()
{
var (installer, _, bytes) = PackSample();
bytes[^1] ^= 0x5A;
File.WriteAllBytes(installer, bytes);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void FooterPointingOutsideTheFileIsRejected()
{
var (installer, _, bytes) = PackSample();
BinaryPrimitives.WriteInt64LittleEndian(bytes.AsSpan(bytes.Length - PayloadFormat.FooterLength + 16), long.MaxValue - 3);
File.WriteAllBytes(installer, bytes);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void CorruptStoredEntryFailsItsHash()
{
var (installer, _, bytes) = PackSample();
PayloadFile noise;
long dataOffset;
using (var reader = PayloadReader.Open(installer))
{
noise = reader.Manifest.Files.Single(f => f.Path == "noise.bin");
dataOffset = DataOffset(bytes, reader.PayloadOffset);
}
Assert.Equal(PayloadCompression.Stored, noise.Compression);
bytes[dataOffset + noise.Offset + 1234] ^= 0xFF;
File.WriteAllBytes(installer, bytes);
using var tampered = PayloadReader.Open(installer);
var ex = Assert.Throws<PayloadException>(() => tampered.Extract([noise], context.CreateTempDirectory()));
Assert.Equal(PayloadError.Corrupt, ex.Error);
Assert.Contains("noise.bin", ex.Message);
}
[Test]
public void EveryCorruptPayloadByteIsDetectedOrHarmless()
{
var (installer, offset, original) = PackSample();
var expected = new Dictionary<string, byte[]>
{
["Chronos.exe"] = PackagingFixture.Text("program ", 3000),
["noise.bin"] = PackagingFixture.Random(40_000, 5),
["docs/readme.txt"] = PackagingFixture.Text("read me ", 200),
};
var step = Math.Max(1, (int)((original.Length - offset) / 150));
for (var at = offset; at < original.Length; at += step)
{
var bytes = (byte[])original.Clone();
bytes[at] ^= 0xFF;
File.WriteAllBytes(installer, bytes);
var target = context.CreateTempDirectory("fuzz");
try
{
using var reader = PayloadReader.Open(installer);
reader.Extract(reader.Manifest.Files, target);
foreach (var (path, content) in expected)
Assert.BytesEqual(content, File.ReadAllBytes(Path.Combine(target, path.Replace('/', Path.DirectorySeparatorChar))), $"flip at {at} produced wrong {path}");
}
catch (PayloadException)
{
// Detected: the expected outcome for almost every byte.
}
}
}
[Test]
public void TruncatedInstallersFailCleanly()
{
var (installer, _, original) = PackSample();
var lengths = new List<int> { 0, 1, 7, PayloadFormat.FooterLength - 1, PayloadFormat.FooterLength, original.Length - 1, original.Length - PayloadFormat.FooterLength };
for (var n = 97; n < original.Length; n += original.Length / 60) lengths.Add(n);
foreach (var length in lengths)
{
File.WriteAllBytes(installer, original.AsSpan(0, length).ToArray());
var ex = Assert.Throws<PayloadException>(() => PayloadReader.Open(installer), $"truncated to {length}");
Assert.True(ex.Error is PayloadError.NotFound or PayloadError.Corrupt, $"truncated to {length}: {ex.Error}");
}
}
[Test]
public void MissingFileIsReportedAsNotFound() =>
Assert.Equal(PayloadError.NotFound, Assert.Throws<PayloadException>(() => PayloadReader.Open(Path.Combine(_fx.Root, "nope.exe"))).Error);
[Theory]
[Case("../evil.txt")]
[Case("a/../../evil.txt")]
[Case("/etc/passwd")]
[Case("C:/Windows/evil.dll")]
[Case("sub\\evil.txt")]
[Case("file.txt:stream")]
public void ManifestPathEscapingTheTargetIsRejected(string path)
{
var content = PackagingFixture.Text("x");
var manifest = new PayloadManifest
{
Product = "Chronos",
Version = "1.0.0",
Components = [new PayloadComponent { Id = "Chronos", DisplayName = "Chronos", DefaultSelected = true, EstimatedSize = 1 }],
Files = [new PayloadFile { Path = path, Component = "Chronos", Size = 1, Sha256 = PackagingFixture.Sha256(content), Compression = PayloadCompression.Stored, Offset = 0, Length = 1 }],
};
var installer = _fx.Craft(manifest, content);
Assert.Equal(PayloadError.UnsafePath, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Theory]
[Case("not json at all")]
[Case("{\"formatVersion\":1,\"version\":\"1.0\"}")]
[Case("{\"formatVersion\":1,\"product\":null,\"version\":\"1.0\"}")]
[Case("{\"formatVersion\":2,\"product\":\"Chronos\",\"version\":\"1.0\",\"components\":[{\"id\":\"Chronos\",\"displayName\":\"Chronos\"}]}")]
[Case("{\"formatVersion\":1,\"product\":\"..\",\"version\":\"1.0\",\"components\":[{\"id\":\"Chronos\",\"displayName\":\"Chronos\"}]}")]
[Case("{\"formatVersion\":1,\"product\":\"Chronos\",\"version\":\"1.0\",\"components\":[]}")]
public void MalformedManifestWithMatchingHashIsCorrupt(string json)
{
var installer = _fx.Craft(System.Text.Encoding.UTF8.GetBytes(json), []);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void DeclaredSizeBeyondTheDeflateLimitIsRejectedUpFront()
{
var manifest = new PayloadManifest
{
Product = "Chronos",
Version = "1.0.0",
Components = [new PayloadComponent { Id = "Chronos", DisplayName = "Chronos" }],
Files = [new PayloadFile { Path = "bomb.bin", Component = "Chronos", Size = 1L << 40, Sha256 = new string('0', 64), Compression = PayloadCompression.Deflate, Offset = 0, Length = 16 }],
};
var installer = _fx.Craft(manifest, new byte[16]);
Assert.Equal(PayloadError.Corrupt, Assert.Throws<PayloadException>(() => PayloadReader.Open(installer)).Error);
}
[Test]
public void EntryInflatingPastItsDeclaredSizeStopsAtTheLimit()
{
var zeros = new byte[4 << 20];
using var compressed = new MemoryStream();
using (var deflate = new DeflateStream(compressed, CompressionLevel.SmallestSize, leaveOpen: true)) deflate.Write(zeros);
var data = compressed.ToArray();
var manifest = new PayloadManifest
{
Product = "Chronos",
Version = "1.0.0",
Components = [new PayloadComponent { Id = "Chronos", DisplayName = "Chronos" }],
Files = [new PayloadFile { Path = "bomb.bin", Component = "Chronos", Size = 1000, Sha256 = PackagingFixture.Sha256(new byte[1000]), Compression = PayloadCompression.Deflate, Offset = 0, Length = data.Length }],
};
using var reader = PayloadReader.Open(_fx.Craft(manifest, data));
var target = context.CreateTempDirectory();
var ex = Assert.Throws<PayloadException>(() => reader.Extract(reader.Manifest.Files, target));
Assert.Contains("larger", ex.Message);
Assert.True(new FileInfo(Path.Combine(target, "bomb.bin")).Length <= 1000);
}
[Test]
public void SignedStubLosesItsSignatureAndSignedInstallerStillOpens()
{
var stubBytes = PackagingFixture.PortableExecutable(5000, certificate: PackagingFixture.Random(1500, 9));
var stub = Path.Combine(_fx.Root, "signed-stub.exe");
File.WriteAllBytes(stub, stubBytes);
var app = _fx.Folder("app", ("Chronos.exe", PackagingFixture.Text("app", 50)));
var installer = _fx.Pack(stub, PackagingFixture.Source(new PayloadComponentSource("Chronos", "Chronos", true, app)));
var packed = File.ReadAllBytes(installer);
var entry = PackagingFixture.SecurityDirectoryOffset(packed);
Assert.Equal(0L, BinaryPrimitives.ReadInt64LittleEndian(packed.AsSpan(entry)), "stub signature directory cleared");
// Sign the whole installer the way signtool does, then read it back.
File.WriteAllBytes(installer, PackagingFixture.Sign(packed, PackagingFixture.Random(2048, 4)));
using var reader = PayloadReader.Open(installer);
Assert.Equal((long)(stubBytes.Length - 1500), reader.PayloadOffset);
var target = context.CreateTempDirectory();
reader.Extract(reader.Manifest.Files, target);
Assert.BytesEqual(PackagingFixture.Text("app", 50), File.ReadAllBytes(Path.Combine(target, "Chronos.exe")));
var copy = Path.Combine(target, "Uninstall Chronos.exe");
reader.WriteStub(copy);
var copied = File.ReadAllBytes(copy);
Assert.Equal(reader.PayloadOffset, (long)copied.Length);
Assert.Equal(0L, BinaryPrimitives.ReadInt64LittleEndian(copied.AsSpan(entry)), "uninstaller signature directory cleared");
}
private static long DataOffset(byte[] installer, long payloadOffset)
{
var footer = installer.AsSpan(installer.Length - PayloadFormat.FooterLength);
return payloadOffset + BinaryPrimitives.ReadInt64LittleEndian(footer[16..]);
}
}
@@ -0,0 +1,60 @@
using Chronos.Core.Packaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Packaging;
public sealed class PayloadPathTests(TestContext context)
{
[Theory]
[Case("Chronos.exe")]
[Case("lib/deep/file.dll")]
[Case("città/日本語 ✓.txt")]
[Case(".hidden")]
[Case("CONFIG.SYS")]
[Case("console.log")]
public void AcceptsCanonicalRelativePaths(string path) => Assert.True(PayloadPath.IsValid(path), path);
[Theory]
[Case("")]
[Case("..")]
[Case("../x")]
[Case("a/../b")]
[Case("a/./b")]
[Case("a//b")]
[Case("/rooted")]
[Case("trailing/")]
[Case("C:/x")]
[Case("a\\b")]
[Case("a:stream")]
[Case("con")]
[Case("aux.txt")]
[Case("COM1")]
[Case("lpt9.log")]
[Case("dot.")]
[Case("space ")]
[Case("tab\tname")]
[Case("star*")]
public void RejectsUnsafePaths(string path) => Assert.False(PayloadPath.IsValid(path), path);
[Test]
public void RejectsOverlongPaths()
{
Assert.False(PayloadPath.IsValid(new string('a', 256)));
Assert.False(PayloadPath.IsValid(string.Join('/', Enumerable.Repeat("abcdefghij", 100))));
}
[Test]
public void ResolveStaysInsideTheRoot()
{
var root = context.CreateTempDirectory();
Assert.Equal(Path.Combine(root, "a", "b.txt"), PayloadPath.Resolve(root, "a/b.txt"));
Assert.Equal(PayloadError.UnsafePath, Assert.Throws<PayloadException>(() => PayloadPath.Resolve(root, "../b.txt")).Error);
}
[Test]
public void ConvertsNativeSeparators()
{
Assert.Equal("a/b/c.txt", PayloadPath.FromRelative("a\\b\\c.txt"));
Assert.Throws<PayloadException>(() => PayloadPath.FromRelative("..\\c.txt"));
}
}
@@ -0,0 +1,172 @@
using Chronos.Core.Packaging;
using Chronos.Testing;
namespace Chronos.Core.Tests.Packaging;
public sealed class PayloadRoundTripTests(TestContext context)
{
private readonly PackagingFixture _fx = new(context);
[Test]
public void ExtractsNestedEmptyUnicodeAndIncompressibleFilesExactly()
{
var files = new (string Path, byte[] Content)[]
{
("Chronos.exe", PackagingFixture.Text("MZ program body ", 4000)),
("lib/deep/er/still/config.json", PackagingFixture.Text("{\"a\":1}", 50)),
("empty.txt", []),
("città/日本語 ✓.txt", PackagingFixture.Text("ciao 世界 ", 300)),
("media/noise.bin", PackagingFixture.Random(3 << 20, seed: 11)),
};
var app = _fx.Folder("app", files);
var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Chronos", "Chronos", true, app)));
using var reader = PayloadReader.Open(installer);
var manifest = reader.Manifest;
Assert.Equal("Chronos", manifest.Product);
Assert.Equal("1.2.3", manifest.Version);
Assert.Count(files.Length, manifest.Files);
Assert.Equal(files.Sum(f => (long)f.Content.Length), manifest.Components[0].EstimatedSize);
Assert.Equal(PayloadCompression.Stored, manifest.Files.Single(f => f.Path == "media/noise.bin").Compression);
Assert.Equal(PayloadCompression.Deflate, manifest.Files.Single(f => f.Path == "Chronos.exe").Compression);
var empty = manifest.Files.Single(f => f.Path == "empty.txt");
Assert.Equal(0L, empty.Length);
var target = context.CreateTempDirectory("extract");
reader.Extract(manifest.FilesFor(["Chronos"]), target);
foreach (var (relative, content) in files)
{
var path = Path.Combine(target, relative.Replace('/', Path.DirectorySeparatorChar));
Assert.BytesEqual(content, File.ReadAllBytes(path), relative);
Assert.Equal(PackagingFixture.FixedTime, File.GetLastWriteTimeUtc(path), relative);
}
}
[Test]
public void ReportsProgressUpToTheTotalSize()
{
var app = _fx.Folder("app", ("a.bin", PackagingFixture.Random(9 << 20, 1)), ("b.txt", PackagingFixture.Text("b", 10)));
var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Chronos", "Chronos", true, app)));
using var reader = PayloadReader.Open(installer);
var reports = new List<PayloadProgress>();
reader.Extract(reader.Manifest.Files, context.CreateTempDirectory(), new SyncProgress<PayloadProgress>(reports.Add));
Assert.True(reports.Count >= 3);
Assert.Monotonic(reports.Select(r => (double)r.Done));
Assert.Equal(reports[^1].Total, reports[^1].Done);
Assert.Equal((9L << 20) + 10, reports[^1].Total);
}
[Test]
public void IdenticalInputsProduceIdenticalInstallers()
{
var app = _fx.Folder("app", ("Chronos.exe", PackagingFixture.Text("app", 999)), ("sub/z.txt", PackagingFixture.Text("z")), ("sub/a.txt", PackagingFixture.Text("a")));
var up = _fx.Folder("uploader", ("Chronos.Uploader.exe", PackagingFixture.Text("uploader", 500)));
var stub = _fx.Stub();
var source = PackagingFixture.Source(
new PayloadComponentSource("Chronos", "Chronos", true, app),
new PayloadComponentSource("Uploader", "Chronos Uploader", false, up));
var first = _fx.Pack(stub, source, "first.exe");
var second = _fx.Pack(stub, source, "second.exe");
Assert.BytesEqual(File.ReadAllBytes(first), File.ReadAllBytes(second));
Assert.Equal(0L, new FileInfo(first).Length % PayloadFormat.Alignment);
}
[Test]
public void SharedFilesAreStoredOnceAndInstalledOnce()
{
var shared = PackagingFixture.Text("shared runtime ", 2000);
var app = _fx.Folder("app", ("Chronos.exe", PackagingFixture.Text("app", 100)), ("runtime.dll", shared));
var up = _fx.Folder("uploader", ("Chronos.Uploader.exe", PackagingFixture.Text("up", 100)), ("runtime.dll", shared));
var installer = _fx.Pack(_fx.Stub(), PackagingFixture.Source(
new PayloadComponentSource("Chronos", "Chronos", true, app),
new PayloadComponentSource("Uploader", "Uploader", true, up)));
using var reader = PayloadReader.Open(installer);
var copies = reader.Manifest.Files.Where(f => f.Path == "runtime.dll").ToList();
Assert.Count(2, copies);
Assert.Equal(copies[0].Offset, copies[1].Offset);
var both = reader.Manifest.FilesFor(["Chronos", "Uploader"]);
Assert.Count(3, both);
Assert.Count(2, reader.Manifest.FilesFor(["uploader"]));
Assert.Throws<ArgumentException>(() => reader.Manifest.FilesFor(["Server"]));
}
[Test]
public void DifferentContentAtTheSamePathAcrossComponentsIsRejected()
{
var app = _fx.Folder("app", ("same.dll", PackagingFixture.Text("one")));
var up = _fx.Folder("uploader", ("same.dll", PackagingFixture.Text("two")));
var ex = Assert.Throws<PayloadException>(() => _fx.Pack(_fx.Stub(), PackagingFixture.Source(
new PayloadComponentSource("Chronos", "Chronos", true, app),
new PayloadComponentSource("Uploader", "Uploader", true, up))));
Assert.Equal(PayloadError.Corrupt, ex.Error);
}
[Test]
public void ShortcutsAndAssociationsSurviveTheRoundTrip()
{
var app = _fx.Folder("app", ("Chronos.exe", PackagingFixture.Text("app")));
var source = new PayloadSource
{
Product = "Chronos",
Version = "2.0.0-beta.1",
Components = [new PayloadComponentSource("Chronos", "Chronos", true, app)],
Shortcuts = [new PayloadShortcut { Component = "Chronos", Name = "Chronos", Target = "Chronos.exe", StartMenu = true, Desktop = true }],
Associations = [new PayloadAssociation { Component = "Chronos", Extension = ".chronos", ProgId = "Chronos.Project", Description = "Chronos project", Target = "Chronos.exe" }],
};
using var reader = PayloadReader.Open(_fx.Pack(_fx.Stub(), source));
var shortcut = reader.Manifest.Shortcuts.Single();
Assert.True(shortcut.Desktop && shortcut.StartMenu);
Assert.Equal("Chronos.exe", shortcut.Target);
Assert.Equal("Chronos.Project", reader.Manifest.Associations.Single().ProgId);
}
[Test]
public void ShortcutToAFileOutsideItsComponentIsRejected()
{
var app = _fx.Folder("app", ("Chronos.exe", PackagingFixture.Text("app")));
var source = new PayloadSource
{
Product = "Chronos",
Version = "1.0.0",
Components = [new PayloadComponentSource("Chronos", "Chronos", true, app)],
Shortcuts = [new PayloadShortcut { Component = "Chronos", Name = "Missing", Target = "Missing.exe", StartMenu = true }],
};
Assert.Throws<PayloadException>(() => _fx.Pack(_fx.Stub(), source));
}
[Test]
public void StubCopyEndsAtThePayload()
{
var stub = _fx.Stub(10_000);
var app = _fx.Folder("app", ("Chronos.exe", PackagingFixture.Text("app", 10)));
using var reader = PayloadReader.Open(_fx.Pack(stub, PackagingFixture.Source(new PayloadComponentSource("Chronos", "Chronos", true, app))));
Assert.Equal(10_000L, reader.PayloadOffset);
var copy = Path.Combine(context.CreateTempDirectory(), "Uninstall Chronos.exe");
reader.WriteStub(copy);
Assert.BytesEqual(File.ReadAllBytes(stub), File.ReadAllBytes(copy));
Assert.Equal(PayloadError.NotFound, Assert.Throws<PayloadException>(() => PayloadReader.Open(copy)).Error);
}
[Test]
public void OutputInsideAComponentFolderIsRefused()
{
var app = _fx.Folder("app", ("Chronos.exe", PackagingFixture.Text("app")));
Assert.Throws<ArgumentException>(() => PayloadWriter.Write(_fx.Stub(), PackagingFixture.Source(new PayloadComponentSource("Chronos", "Chronos", true, app)), Path.Combine(app, "setup.exe")));
}
[Test]
public void AnInstallerCannotBeUsedAsStub()
{
var app = _fx.Folder("app", ("Chronos.exe", PackagingFixture.Text("app")));
var source = PackagingFixture.Source(new PayloadComponentSource("Chronos", "Chronos", true, app));
var installer = _fx.Pack(_fx.Stub(), source);
Assert.Throws<ArgumentException>(() => _fx.Pack(installer, source, "nested.exe"));
}
/// <summary>Synchronous <see cref="IProgress{T}"/> (Progress&lt;T&gt; posts to the thread pool).</summary>
private sealed class SyncProgress<T>(Action<T> report) : IProgress<T>
{
public void Report(T value) => report(value);
}
}