Files
Alby96andClaude Opus 5.5 f2b58522b9
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
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
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>
2026-10-23 12:45:18 +02:00

228 lines
11 KiB
C#

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..]);
}
}